Class: DeepAgents::Models::Claude

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

Overview

Claude model adapter

Instance Attribute Summary

Attributes inherited from BaseModel

#model

Instance Method Summary collapse

Constructor Details

#initialize(api_key: nil, model: "claude-3-sonnet-20240229") ⇒ Claude



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/deepagents/models.rb', line 24

def initialize(api_key: nil, model: "claude-3-sonnet-20240229")
  super(model: model)
  @api_key = api_key || ENV["ANTHROPIC_API_KEY"]
  
  begin
    require 'anthropic'
  rescue LoadError
    raise LoadError, "The 'anthropic' gem is required for Claude models"
  end
  
  if @api_key.nil? || @api_key.empty?
    raise CredentialsError.new("Claude")
  end
  
  @client = Anthropic::Client.new(api_key: @api_key)
end

Instance Method Details

#generate(prompt, tools = nil) ⇒ Object



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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/deepagents/models.rb', line 41

def generate(prompt, tools = nil)
  begin
    messages = [{ role: "user", content: prompt }]
    
    params = {
      model: @model,
      messages: messages,
      max_tokens: 4096,
      temperature: 0.7
    }
    
    if tools && !tools.empty?
      tool_definitions = tools.map do |tool|
        {
          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.messages.create(**params)
    
    if tools && !tools.empty? && response.content.first.type == "tool_use"
      tool_call = response.content.first.tool_use
      return {
        content: nil,
        tool_calls: [{
          name: tool_call.name,
          arguments: tool_call.parameters
        }]
      }
    else
      return {
        content: response.content.first.text,
        tool_calls: []
      }
    end
  rescue => e
    raise ModelError, "Claude API error: #{e.message}"
  end
end

#to_langchain_modelObject



90
91
92
93
94
95
96
97
# File 'lib/deepagents/models.rb', line 90

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