Class: DeepAgents::Models::OpenAI

Inherits:
BaseModel
  • Object
show all
Defined in:
lib/deepagents/models.rb

Overview

OpenAI model adapter

Instance Attribute Summary

Attributes inherited from BaseModel

#model

Instance Method Summary collapse

Constructor Details

#initialize(api_key: nil, model: "gpt-4o") ⇒ OpenAI

Returns a new instance of OpenAI.



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/deepagents/models.rb', line 102

def initialize(api_key: nil, model: "gpt-4o")
  super(model: model)
  @api_key = api_key || ENV["OPENAI_API_KEY"]
  
  begin
    require 'openai'
  rescue LoadError
    raise LoadError, "The 'openai' gem is required for OpenAI models"
  end
  
  if @api_key.nil? || @api_key.empty?
    raise CredentialsError.new("OpenAI")
  end
  
  @client = ::OpenAI::Client.new(access_token: @api_key)
end

Instance Method Details

#generate(prompt, tools = nil) ⇒ Object



119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/deepagents/models.rb', line 119

def generate(prompt, tools = nil)
  begin
    messages = [{ role: "user", content: prompt }]
    
    params = {
      model: @model,
      messages: messages,
      temperature: 0.7,
      max_tokens: 4096
    }
    
    if tools && !tools.empty?
      tool_definitions = tools.map do |tool|
        {
          type: "function",
          function: {
            name: tool.name,
            description: tool.description,
            parameters: {
              type: "object",
              properties: Hash[tool.parameters.map { |param| [param, { type: "string" }] }],
              required: tool.parameters
            }
          }
        }
      end
      
      params[:tools] = tool_definitions
    end
    
    response = @client.chat(parameters: params)
    
    if tools && !tools.empty? && response.dig("choices", 0, "message", "tool_calls")
      tool_call = response.dig("choices", 0, "message", "tool_calls").first
      return {
        content: nil,
        tool_calls: [{
          name: tool_call["function"]["name"],
          arguments: JSON.parse(tool_call["function"]["arguments"])
        }]
      }
    else
      return {
        content: response.dig("choices", 0, "message", "content"),
        tool_calls: []
      }
    end
  rescue => e
    raise ModelError, "OpenAI API error: #{e.message}"
  end
end

#to_langchain_modelObject



171
172
173
174
175
176
177
178
# File 'lib/deepagents/models.rb', line 171

def to_langchain_model
  # Create and return a langchainrb OpenAI model
  require 'langchain'
  Langchain::LLM::OpenAI.new(
    api_key: @api_key,
    model_name: @model
  )
end