Class: N2M::Llm::OpenAi
- Inherits:
-
Object
- Object
- N2M::Llm::OpenAi
- Defined in:
- lib/n2b/llm/open_ai.rb
Constant Summary collapse
- API_URI =
URI.parse('https://api.openai.com/v1/chat/completions')
- MODELS =
{ 'gpt-4o' => 'gpt-4o','gpt-4o-mini'=>'gpt-4o-mini', 'gpt-35' => 'gpt-3.5-turbo-1106' }
Instance Method Summary collapse
-
#initialize(config) ⇒ OpenAi
constructor
A new instance of OpenAi.
- #make_request(content) ⇒ Object
Constructor Details
#initialize(config) ⇒ OpenAi
Returns a new instance of OpenAi.
11 12 13 |
# File 'lib/n2b/llm/open_ai.rb', line 11 def initialize(config) @config = config end |
Instance Method Details
#make_request(content) ⇒ Object
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 |
# File 'lib/n2b/llm/open_ai.rb', line 15 def make_request(content) request = Net::HTTP::Post.new(API_URI) request.content_type = 'application/json' request['Authorization'] = "Bearer #{@config['access_key']}" request.body = JSON.dump({ "model" => MODELS[@config['model']], response_format: { type: 'json_object' }, "messages" => [ { "role" => "user", "content" => content }] }) response = Net::HTTP.start(API_URI.hostname, API_URI.port, use_ssl: true) do |http| http.request(request) end # check for errors if response.code != '200' puts "Error: #{response.code} #{response.}" puts response.body exit 1 end answer = JSON.parse(response.body)['choices'].first['message']['content'] begin # remove everything before the first { and after the last } answer = answer.sub(/.*\{(.*)\}.*/m, '{\1}') unless answer.start_with?('{') answer = JSON.parse(answer) rescue JSON::ParserError answer = { 'commands' => answer.split("\n"), explanation: answer } end answer end |