Class: DSPy::LM::AnthropicAdapter

Inherits:
Adapter
  • Object
show all
Defined in:
lib/dspy/lm/adapters/anthropic_adapter.rb

Instance Attribute Summary

Attributes inherited from Adapter

#api_key, #model

Instance Method Summary collapse

Constructor Details

#initialize(model:, api_key:) ⇒ AnthropicAdapter

Returns a new instance of AnthropicAdapter.



9
10
11
12
13
# File 'lib/dspy/lm/adapters/anthropic_adapter.rb', line 9

def initialize(model:, api_key:)
  super
  validate_api_key!(api_key, 'anthropic')
  @client = Anthropic::Client.new(api_key: api_key)
end

Instance Method Details

#chat(messages:, signature: nil, **extra_params, &block) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/dspy/lm/adapters/anthropic_adapter.rb', line 15

def chat(messages:, signature: nil, **extra_params, &block)
  normalized_messages = normalize_messages(messages)
  
  # Validate vision support if images are present
  if contains_images?(normalized_messages)
    VisionModels.validate_vision_support!('anthropic', model)
    # Convert messages to Anthropic format with proper image handling
    normalized_messages = format_multimodal_messages(normalized_messages)
  end
  
  # Anthropic requires system message to be separate from messages
  system_message, user_messages = extract_system_message(normalized_messages)
  
  # Check if this is a tool use request
  has_tools = extra_params.key?(:tools) && !extra_params[:tools].empty?
  
  # Apply JSON prefilling if needed for better Claude JSON compliance (but not for tool use)
  unless has_tools || contains_images?(normalized_messages)
    user_messages = prepare_messages_for_json(user_messages, system_message)
  end
  
  request_params = {
    model: model,
    messages: user_messages,
    max_tokens: 4096, # Required for Anthropic
    temperature: 0.0 # DSPy default for deterministic responses
  }.merge(extra_params)

  # Add system message if present
  request_params[:system] = system_message if system_message

  # Add streaming if block provided
  if block_given?
    request_params[:stream] = true
  end

  begin
    if block_given?
      content = ""
      @client.messages.stream(**request_params) do |chunk|
        if chunk.respond_to?(:delta) && chunk.delta.respond_to?(:text)
          chunk_text = chunk.delta.text
          content += chunk_text
          block.call(chunk)
        end
      end
      
      # Create typed metadata for streaming response
       = ResponseMetadataFactory.create('anthropic', {
        model: model,
        streaming: true
      })
      
      Response.new(
        content: content,
        usage: nil, # Usage not available in streaming
        metadata: 
      )
    else
      response = @client.messages.create(**request_params)
      
      if response.respond_to?(:error) && response.error
        raise AdapterError, "Anthropic API error: #{response.error}"
      end

      # Handle both text content and tool use
      content = ""
      tool_calls = []
      
      if response.content.is_a?(Array)
        response.content.each do |content_block|
          case content_block.type.to_s
          when "text"
            content += content_block.text
          when "tool_use"
            tool_calls << {
              id: content_block.id,
              name: content_block.name,
              input: content_block.input
            }
          end
        end
      end
      
      usage = response.usage

      # Convert usage data to typed struct
      usage_struct = UsageFactory.create('anthropic', usage)
      
       = {
        provider: 'anthropic',
        model: model,
        response_id: response.id,
        role: response.role
      }
      
      # Add tool calls to metadata if present
      [:tool_calls] = tool_calls unless tool_calls.empty?
      
      # Create typed metadata
       = ResponseMetadataFactory.create('anthropic', )
      
      Response.new(
        content: content,
        usage: usage_struct,
        metadata: 
      )
    end
  rescue => e
    # Check for specific image-related errors in the message
    error_msg = e.message.to_s
    
    if error_msg.include?('Could not process image')
      raise AdapterError, "Image processing failed: #{error_msg}. Ensure your image is a valid PNG, JPEG, GIF, or WebP format, properly base64-encoded, and under 5MB."
    elsif error_msg.include?('image')
      raise AdapterError, "Image error: #{error_msg}. Anthropic requires base64-encoded images (URLs are not supported)."
    elsif error_msg.include?('rate')
      raise AdapterError, "Anthropic rate limit exceeded: #{error_msg}. Please wait and try again."
    elsif error_msg.include?('authentication') || error_msg.include?('API key')
      raise AdapterError, "Anthropic authentication failed: #{error_msg}. Check your API key."
    else
      # Generic error handling
      raise AdapterError, "Anthropic adapter error: #{e.message}"
    end
  end
end