Class: RSmolagent::OpenAIProvider
- Inherits:
-
LLMProvider
- Object
- LLMProvider
- RSmolagent::OpenAIProvider
- Defined in:
- lib/rsmolagent/llm_provider.rb
Instance Attribute Summary
Attributes inherited from LLMProvider
#last_completion_tokens, #last_prompt_tokens
Instance Method Summary collapse
- #chat(messages, tools: nil, tool_choice: nil) ⇒ Object
- #extract_tool_calls(response) ⇒ Object
-
#initialize(model_id:, client:, **options) ⇒ OpenAIProvider
constructor
A new instance of OpenAIProvider.
Methods inherited from LLMProvider
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:, **) super(model_id: model_id, **) @client = client @max_retries = [:max_retries] || 3 @initial_backoff = [: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(, tools: nil, tool_choice: nil) params = { model: @model_id, 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. 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 |