Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions lib/ruby_llm/providers/anthropic/chat.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,21 +55,21 @@ def parse_completion_response(response)
content_blocks = data['content'] || []

text_content = extract_text_content(content_blocks)
tool_use = Tools.find_tool_use(content_blocks)
tool_use_blocks = Tools.find_tool_uses(content_blocks)

build_message(data, text_content, tool_use)
build_message(data, text_content, tool_use_blocks)
end

def extract_text_content(blocks)
text_blocks = blocks.select { |c| c['type'] == 'text' }
text_blocks.map { |c| c['text'] }.join
end

def build_message(data, content, tool_use)
def build_message(data, content, tool_use_blocks)
Message.new(
role: :assistant,
content: content,
tool_calls: Tools.parse_tool_calls(tool_use),
tool_calls: Tools.parse_tool_calls(tool_use_blocks),
input_tokens: data.dig('usage', 'input_tokens'),
output_tokens: data.dig('usage', 'output_tokens'),
model_id: data['model']
Expand Down
36 changes: 23 additions & 13 deletions lib/ruby_llm/providers/anthropic/tools.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,18 @@ module Anthropic
module Tools
module_function

def find_tool_use(blocks)
blocks.find { |c| c['type'] == 'tool_use' }
def find_tool_uses(blocks)
blocks.select { |c| c['type'] == 'tool_use' }
end

def format_tool_call(msg)
tool_call = msg.tool_calls.values.first

content = []

content << Media.format_text(msg.content) unless msg.content.nil? || msg.content.empty?
content << format_tool_use_block(tool_call)

msg.tool_calls.each_value do |tool_call|
content << format_tool_use_block(tool_call)
end

{
role: 'assistant',
Expand Down Expand Up @@ -68,16 +70,24 @@ def extract_tool_calls(data)
end
end

def parse_tool_calls(content_block)
return nil unless content_block && content_block['type'] == 'tool_use'
def parse_tool_calls(content_blocks)
return nil if content_blocks.nil?

{
content_block['id'] => ToolCall.new(
id: content_block['id'],
name: content_block['name'],
arguments: content_block['input']
# Handle single content block (backward compatibility)
content_blocks = [content_blocks] unless content_blocks.is_a?(Array)

tool_calls = {}
content_blocks.each do |block|
next unless block && block['type'] == 'tool_use'

tool_calls[block['id']] = ToolCall.new(
id: block['id'],
name: block['name'],
arguments: block['input']
)
}
end

tool_calls.empty? ? nil : tool_calls
end

def clean_parameters(parameters)
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading