Class: ActiveAgent::Providers::OpenAI

Inherits:
Base
  • Object
show all
Defined in:
lib/active_agent/providers/openai.rb

Constant Summary collapse

DEFAULT_URL =
'https://api.openai.com/v1/chat/completions'

Instance Attribute Summary

Attributes inherited from Base

#api_key, #api_url, #model

Instance Method Summary collapse

Constructor Details

#initialize(model: 'gpt-4o-mini', api_key: ENV.fetch('OPENAI_API_KEY', nil), api_url: nil) ⇒ OpenAI

Returns a new instance of OpenAI.

Raises:



10
11
12
13
14
15
# File 'lib/active_agent/providers/openai.rb', line 10

def initialize(model: 'gpt-4o-mini', api_key: ENV.fetch('OPENAI_API_KEY', nil), api_url: nil)
  url = api_url || DEFAULT_URL
  super(model: model, api_key: api_key, api_url: url)

  raise Error, 'OPENAI_API_KEY is required for OpenAI provider' unless @api_key || ENV['MOCK_AGENT_RESPONSE']
end

Instance Method Details

#chat(messages:, tools: []) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/active_agent/providers/openai.rb', line 17

def chat(messages:, tools: [])
  headers = {
    'Content-Type' => 'application/json',
    'Authorization' => "Bearer #{@api_key}"
  }

  payload = {
    model: @model,
    messages: messages,
    temperature: 0.2
  }

  payload[:tools] = tools.map { |t| { type: 'function', function: t.to_openai_function } } if tools && !tools.empty?

  data = http_post(@api_url, headers, payload)
  message = data.dig('choices', 0, 'message') || {}

  {
    content: message['content'],
    tool_calls: message['tool_calls']
  }
end