-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_client.rb
50 lines (45 loc) · 1.19 KB
/
http_client.rb
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
module CLAI
class HTTPClient
def initialize(config)
@config = config
end
def chat(query, system_prompts: [])
system_prompts = system_prompts.map { |prompt| { role: :system, content: prompt } }
puts
client
.post("https://api.openai.com/v1/chat/completions",
json: {
model: @config.model,
messages: [
*system_prompts,
{ "role": "user", "content": query },
],
stream: true
}
).body.each_with_index do |chunk, i|
if i == 0
# TODO: remove workaround
splits = chunk.split("\n\n")
if splits.length > 1
chunk = splits[1]
else
chunk = splits[0]
end
end
data = chunk.match(/data: (.*)/) || []
break if data[1] == "[DONE]"
if data[1]
result = JSON.parse(data[1])
print result.dig('choices', 0, "delta", "content")
end
end
puts
end
private
def client
HTTP
.auth("Bearer #{@config.api_key}")
.headers(accept: "application/json")
end
end
end