Module: Luogu::OpenAI
- Defined in:
- lib/luogu/openai.rb
Defined Under Namespace
Classes: ChatRequestParams, Messages
Class Method Summary
collapse
Class Method Details
.chat(parameters: nil, params: nil, retries: nil) ⇒ Object
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
# File 'lib/luogu/openai.rb', line 15
def chat(parameters: nil, params: nil, retries: nil)
params ||= parameters
retries_left = retries || Luogu::Application.config.openai.retries
begin
client.post('/v1/chat/completions', json: params)
rescue HTTP::Error => e
if retries_left > 0
puts "retrying ..."
retries_left -= 1
sleep(1)
retry
else
puts "Connection error #{e}"
return nil
end
end
end
|
.chat_response_handle(response) ⇒ Object
54
55
56
|
# File 'lib/luogu/openai.rb', line 54
def chat_response_handle(response)
parse_json get_content(response)
end
|
.client ⇒ Object
33
34
35
36
|
# File 'lib/luogu/openai.rb', line 33
def client
@client ||= HTTP.auth("Bearer #{Luogu::Application.config.openai.access_token}")
.persistent Luogu::Application.config.openai.host
end
|
.find_final_answer(content) ⇒ Object
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
# File 'lib/luogu/openai.rb', line 62
def find_final_answer(content)
if content.is_a?(Hash) && content['action'] == 'Final Answer'
content['action_input']
elsif content.is_a?(Array)
result = content.find { |element| element["action"] == "Final Answer" }
if result
result["action_input"]
else
nil
end
else
nil
end
end
|
.get_content(response) ⇒ Object
58
59
60
|
# File 'lib/luogu/openai.rb', line 58
def get_content(response)
response.parse.dig("choices", 0, "message", "content")
end
|
.parse_json(markdown) ⇒ Object
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
# File 'lib/luogu/openai.rb', line 38
def parse_json(markdown)
json_regex = /```json(.+?)```/im
json_blocks = markdown.scan(json_regex)
result_json = nil
json_blocks.each do |json_block|
json_string = json_block[0]
result_json = JSON.parse(json_string)
end
if result_json.nil?
JSON.parse markdown
else
result_json
end
end
|