Class: Rubyagents::Models::RubyLLMAdapter

Inherits:
Rubyagents::Model show all
Defined in:
lib/rubyagents/models/ruby_llm_adapter.rb

Instance Attribute Summary collapse

Attributes inherited from Rubyagents::Model

#model_name

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Rubyagents::Model

for, register

Constructor Details

#initialize(model_name, provider: nil) ⇒ RubyLLMAdapter

Returns a new instance of RubyLLMAdapter.



8
9
10
11
# File 'lib/rubyagents/models/ruby_llm_adapter.rb', line 8

def initialize(model_name, provider: nil)
  super(model_name)
  @provider = provider&.to_sym
end

Instance Attribute Details

#provider ⇒ Object (readonly)

Returns the value of attribute provider.



6
7
8
# File 'lib/rubyagents/models/ruby_llm_adapter.rb', line 6

def provider
  @provider
end

Class Method Details

.configure_ruby_llm ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rubyagents/models/ruby_llm_adapter.rb', line 38

def self.configure_ruby_llm
  return if @configured

  RubyLLM.configure do |config|
    config.openai_api_key = ENV["OPENAI_API_KEY"] if ENV["OPENAI_API_KEY"]
    config.anthropic_api_key = ENV["ANTHROPIC_API_KEY"] if ENV["ANTHROPIC_API_KEY"]
    config.gemini_api_key = ENV["GEMINI_API_KEY"] if ENV["GEMINI_API_KEY"]
    config.deepseek_api_key = ENV["DEEPSEEK_API_KEY"] if ENV["DEEPSEEK_API_KEY"]
    config.openrouter_api_key = ENV["OPENROUTER_API_KEY"] if ENV["OPENROUTER_API_KEY"]
    config.ollama_api_base = ENV["OLLAMA_HOST"] if ENV["OLLAMA_HOST"]
  end

  @configured = true
end

Instance Method Details

#generate(messages, tools: nil, &on_stream) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/rubyagents/models/ruby_llm_adapter.rb', line 13

def generate(messages, tools: nil, &on_stream)
  require "ruby_llm"
  self.class.configure_ruby_llm

  chat = build_chat
  load_messages(chat, messages)
  load_tools(chat, tools) if tools&.any?

  response = if on_stream
    chat.complete { |chunk| on_stream.call(chunk.content) if chunk.content }
  else
    chat.complete
  end

  extract_response(chat, response)
rescue RubyLLM::ConfigurationError => e
  raise Error, "Model configuration error: #{e.message}. Set the appropriate API key env var."
rescue RubyLLM::ModelNotFoundError => e
  raise Error, "Unknown model '#{model_name}'. Check the model name or set a provider prefix (e.g. 'openai/#{model_name}')."
rescue RubyLLM::UnauthorizedError => e
  raise Error, "API authentication failed: #{e.message}. Check your API key."
rescue RubyLLM::Error => e
  raise Error, "LLM API error: #{e.message}"
end