Class: LLMs::Adapters::AnthropicMessageAdapter

Inherits:
BaseMessageAdapter show all
Defined in:
lib/llms/adapters/anthropic_message_adapter.rb

Class Method Summary collapse

Methods inherited from BaseMessageAdapter

has_message?, message_from_api_format, transform_role, transform_text, transform_tool_calls

Class Method Details

.find_message_id(api_response_format) ⇒ Object



59
60
61
# File 'lib/llms/adapters/anthropic_message_adapter.rb', line 59

def self.find_message_id(api_response_format)
  api_response_format['id']
end

.find_role(api_response_format) ⇒ Object



55
56
57
# File 'lib/llms/adapters/anthropic_message_adapter.rb', line 55

def self.find_role(api_response_format)
  api_response_format['role']
end

.find_text(api_response_format) ⇒ Object



63
64
65
# File 'lib/llms/adapters/anthropic_message_adapter.rb', line 63

def self.find_text(api_response_format)
  api_response_format['content']&.map { |c| c['text'] }&.compact&.join
end

.find_tool_calls(api_response_format) ⇒ Object



67
68
69
# File 'lib/llms/adapters/anthropic_message_adapter.rb', line 67

def self.find_tool_calls(api_response_format)
  api_response_format['content']&.select { |c| c['type'] == 'tool_use' }
end

.to_api_format(message, caching_enabled = false) ⇒ Object



10
11
12
13
14
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
# File 'lib/llms/adapters/anthropic_message_adapter.rb', line 10

def self.to_api_format(message, caching_enabled = false)
  content = []

  message.tool_results&.each do |tool_result|
    tr = {type: 'tool_result', tool_use_id: tool_result.tool_call_id, content: tool_result.results}
    if tool_result.is_error
      tr[:is_error] = true
    end
    content << tr
  end

  message.parts&.each do |part|
    if part[:text]
      content << {type: 'text', text: part[:text]}
    end
    if part[:image]
      content << {
        type: 'image',
        source: {
          type: 'base64',
          media_type: part[:media_type],
          data: part[:image]
        }
      }
    end
  end

  message.tool_calls&.each do |tool_call|
    content << {type: 'tool_use', id: tool_call.tool_call_id, name: tool_call.name, input: tool_call.arguments}
  end

  if caching_enabled
    content.last[:cache_control] = {type: 'ephemeral'}
  end

  {
    role: message.role,
    content: content
  }
end

.transform_tool_call(api_response_format_part, index) ⇒ Object



51
52
53
# File 'lib/llms/adapters/anthropic_message_adapter.rb', line 51

def self.transform_tool_call(api_response_format_part, index)
  LLMs::Adapters::AnthropicToolCallAdapter.from_api_format(api_response_format_part, index)
end