Module: RubyLLM::Providers::Gemini::Tools

Included in:
RubyLLM::Providers::Gemini
Defined in:
lib/ruby_llm/providers/gemini/tools.rb

Overview

Tools methods for the Gemini API implementation

Instance Method Summary collapse

Instance Method Details

#extract_tool_calls(data) ⇒ Object

rubocop:disable Metrics/PerceivedComplexity



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/ruby_llm/providers/gemini/tools.rb', line 50

def extract_tool_calls(data) # rubocop:disable Metrics/PerceivedComplexity
  return nil unless data

  candidate = data.is_a?(Hash) ? data.dig('candidates', 0) : nil
  return nil unless candidate

  parts = candidate.dig('content', 'parts')
  return nil unless parts.is_a?(Array)

  tool_calls = parts.each_with_object({}) do |part, result|
    function_data = part['functionCall']
    next unless function_data

    id = SecureRandom.uuid

    result[id] = ToolCall.new(
      id:,
      name: function_data['name'],
      arguments: function_data['args'] || {}
    )
  end

  tool_calls.empty? ? nil : tool_calls
end

#format_tool_call(msg) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/ruby_llm/providers/gemini/tools.rb', line 16

def format_tool_call(msg)
  parts = []

  if msg.content && !(msg.content.respond_to?(:empty?) && msg.content.empty?)
    formatted_content = Media.format_content(msg.content)
    parts.concat(formatted_content.is_a?(Array) ? formatted_content : [formatted_content])
  end

  msg.tool_calls.each_value do |tool_call|
    parts << {
      functionCall: {
        name: tool_call.name,
        args: tool_call.arguments
      }
    }
  end

  parts
end

#format_tool_result(msg, function_name = nil) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/ruby_llm/providers/gemini/tools.rb', line 36

def format_tool_result(msg, function_name = nil)
  function_name ||= msg.tool_call_id

  [{
    functionResponse: {
      name: function_name,
      response: {
        name: function_name,
        content: Media.format_content(msg.content)
      }
    }
  }]
end

#format_tools(tools) ⇒ Object



8
9
10
11
12
13
14
# File 'lib/ruby_llm/providers/gemini/tools.rb', line 8

def format_tools(tools)
  return [] if tools.empty?

  [{
    functionDeclarations: tools.values.map { |tool| function_declaration_for(tool) }
  }]
end