Module: Luogu::OpenAI
- Extended by:
- Dry::Configurable
- 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
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
# File 'lib/luogu/openai.rb', line 19
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
62
63
64
|
# File 'lib/luogu/openai.rb', line 62
def chat_response_handle(response)
parse_json get_content(response)
end
|
.client ⇒ Object
37
38
39
40
|
# File 'lib/luogu/openai.rb', line 37
def client
@client ||= HTTP.auth("Bearer #{Luogu::Application.config.openai.access_token}")
.persistent Luogu::Application.config.openai.host
end
|
.find_final_answer(content) ⇒ Object
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
# File 'lib/luogu/openai.rb', line 70
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
66
67
68
|
# File 'lib/luogu/openai.rb', line 66
def get_content(response)
response.parse.dig("choices", 0, "message", "content")
end
|
.parse_json(markdown) ⇒ Object
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
# File 'lib/luogu/openai.rb', line 42
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?
result_json = JSON.parse markdown
else
result_json
end
Luogu::OpenAI.config.after_parse_json.call(result_json)
rescue => e
Luogu::Application.logger.error "parse json error: #{markdown}"
Luogu::OpenAI.config.after_parse_json.call(markdown)
end
|