Class: Llm::Agent::Rails::Adapters::OpenAIAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/llm/agent/rails/adapters/openai_adapter.rb

Instance Method Summary collapse

Constructor Details

#initialize(api_key:, model:, temperature: 0) ⇒ OpenAIAdapter



7
8
9
10
11
# File 'lib/llm/agent/rails/adapters/openai_adapter.rb', line 7

def initialize(api_key:, model:, temperature: 0)
  @client = ::OpenAI::Client.new(api_key: api_key)
  @model = model
  @temperature = temperature
end

Instance Method Details

#step(system_prompt:, messages:, tools:, tool_results: []) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/llm/agent/rails/adapters/openai_adapter.rb', line 13

def step(system_prompt:, messages:, tools:, tool_results: [])
  response = @client.chat.completions.create(
    model: @model,
    temperature: @temperature,
    messages: [{ role: "system", content: system_prompt }] + messages + tool_results,
    tools: tools,
    tool_choice: "auto"
  )

  choice = response.choices.first
  msg    = choice.message

  tool_calls    = msg.respond_to?(:tool_calls)    ? msg.tool_calls    : nil
  function_call = msg.respond_to?(:function_call) ? msg.function_call : nil
  content       = msg.respond_to?(:content)       ? msg.content       : nil

  { tool_calls: tool_calls, function_call: function_call, content: content }
end

#tool_result_message(tool_call_id:, name:, content:) ⇒ Object



32
33
34
# File 'lib/llm/agent/rails/adapters/openai_adapter.rb', line 32

def tool_result_message(tool_call_id:, name:, content:)
  { role: "tool", tool_call_id: tool_call_id, name: name, content: content.to_json }
end