Class: RSmolagent::OpenAIProvider

Inherits:
LLMProvider show all
Defined in:
lib/rsmolagent/llm_provider.rb

Instance Attribute Summary

Attributes inherited from LLMProvider

#last_completion_tokens, #last_prompt_tokens

Instance Method Summary collapse

Methods inherited from LLMProvider

#parse_json_if_needed

Constructor Details

#initialize(model_id:, client:, **options) ⇒ OpenAIProvider

Returns a new instance of OpenAIProvider.



32
33
34
35
36
37
# File 'lib/rsmolagent/llm_provider.rb', line 32

def initialize(model_id:, client:, **options)
  super(model_id: model_id, **options)
  @client = client
  @max_retries = options[:max_retries] || 3
  @initial_backoff = options[:initial_backoff] || 1
end

Instance Method Details

#chat(messages, tools: nil, tool_choice: nil) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/rsmolagent/llm_provider.rb', line 39

def chat(messages, tools: nil, tool_choice: nil)
  params = {
    model: @model_id,
    messages: messages,
    temperature: @options[:temperature] || 0.7,
  }

  # Add tools if provided
  if tools && !tools.empty?
    params[:tools] = tools.map(&:to_json_schema)
    params[:tool_choice] = tool_choice || "auto"
  end

  retries = 0
  begin
    response = @client.chat(parameters: params)
    
    # Update token counts
    @last_prompt_tokens = response.usage.prompt_tokens
    @last_completion_tokens = response.usage.completion_tokens
    
    response.choices.first.message
  rescue Faraday::TooManyRequestsError => e
    retries += 1
    if retries <= @max_retries
      # Exponential backoff with jitter
      sleep_time = @initial_backoff * (2 ** (retries - 1)) * (0.5 + rand)
      puts "Rate limited (429). Retrying in #{sleep_time.round(1)} seconds... (#{retries}/#{@max_retries})"
      sleep(sleep_time)
      retry
    else
      puts "Max retries (#{@max_retries}) exceeded. Rate limit error persists."
      raise e
    end
  end
end

#extract_tool_calls(response) ⇒ Object



76
77
78
79
80
81
82
83
84
85
# File 'lib/rsmolagent/llm_provider.rb', line 76

def extract_tool_calls(response)
  return [] unless response.tool_calls
  
  response.tool_calls.map do |tool_call|
    {
      name: tool_call.function.name,
      arguments: parse_json_if_needed(tool_call.function.arguments)
    }
  end
end