Class: Llm::AnthropicAdapter

Inherits:
Object
  • Object
show all
Defined in:
app/services/llm/anthropic_adapter.rb

Instance Method Summary collapse

Constructor Details

#initialize(credential) ⇒ AnthropicAdapter

Returns a new instance of AnthropicAdapter.



3
4
5
# File 'app/services/llm/anthropic_adapter.rb', line 3

def initialize(credential)
  @credential = credential
end

Instance Method Details

#call_tool(system:, tool:, max_tokens:, content_blocks: nil, messages: nil) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'app/services/llm/anthropic_adapter.rb', line 7

def call_tool(system:, tool:, max_tokens:, content_blocks: nil, messages: nil)
  wire_messages = messages || [ { role: "user", content: content_blocks.map { |block| to_wire_block(block) } } ]
  client = Anthropic::Client.new(api_key: @credential.api_key)
  response = client.messages.create(
    model: @credential.model,
    max_tokens: max_tokens,
    system: system,
    messages: wire_messages,
    tools: [ { name: tool[:name], description: tool[:description], input_schema: tool[:input_schema] } ],
    tool_choice: { type: "tool", name: tool[:name] }
  )
  tool_use = response.content.find { |block| block.type == :tool_use }
  raise "Llm::AnthropicAdapter: no #{tool[:name]} tool call in response" unless tool_use

  # The anthropic gem parses response JSON with symbolize_names: true, so
  # tool_use.input has symbol keys — stringify to match
  # Llm::OpenAiCompatibleAdapter#call_tool's return shape, which callers
  # rely on via string-key access.
  CallResult.new(
    data: tool_use.input.deep_stringify_keys,
    input_tokens: response.usage.input_tokens,
    output_tokens: response.usage.output_tokens
  )
end