-
Notifications
You must be signed in to change notification settings - Fork 0
/
run-server
81 lines (64 loc) · 1.74 KB
/
run-server
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/usr/bin/env ruby
# encoding: utf-8
# Query and answer questions based on an index file
#
# Usage: run-server config.json
#
# Requires OpenAI API Key stored in DOT_OPENAI_KEY
require "json"
require "ostruct"
require "sinatra"
require_relative "server/retriever"
require_relative "server/memory"
if ARGV.length != 1
STDOUT << "Invalid arguments received, need a config file\n"
exit 1
end
config = JSON.parse(File.read(ARGV[0]))
CONFIG = OpenStruct.new(config)
CONFIG.paths = CONFIG.paths.map { |p| OpenStruct.new(p) }
CONFIG.path_map = {}
CONFIG.paths.each { |p| CONFIG.path_map[p.name] = p }
OPENAI_KEY = ENV["DOT_OPENAI_KEY"] || ""
if OPENAI_KEY.empty?
STDOUT << "Remember to set env DOT_OPENAI_KEY\n"
exit 9
end
# list all the paths that can be searched
get '/paths' do
content_type :json
resp = []
CONFIG.paths.each do |p|
resp << { "name": p.name }
end
resp.to_json
end
# query within the paths
post '/q' do
content_type :json
data = JSON.parse(request.body.read)
lookup_paths = (data["paths"] || CONFIG.paths_map.keys).map do |name|
CONFIG.path_map[name]
end
topN = (data["topN"] || 20).to_i
entries = retrieve_by_embedding(lookup_paths, data["q"])
entries = entries.sort_by { |item| -item["score"] }.take(topN)
resp = {
data: [],
eval: nil,
}
entries.each do |item|
resp[:data] << {
path: item["path"],
lookup: item["lookup"],
id: item["id"],
url: item["url"],
text: item["reader"].load.get_chunk(item["chunk"]),
score: item["score"],
}
end
if data["experiment"]
resp[:eval] = update_memory(data["q"], resp[:data])
end
resp.to_json
end