Class: OxAiWorkers::Models::GeminiPro

Inherits:
LLMBase
  • Object
show all
Defined in:
lib/oxaiworkers/models/gemini_pro.rb

Instance Attribute Summary

Attributes inherited from LLMBase

#api_key, #frequency_penalty, #max_tokens, #model, #temperature, #uri_base

Instance Method Summary collapse

Methods inherited from LLMBase

#_parse_tool_calls

Constructor Details

#initialize(uri_base: nil, api_key: nil, model: nil, max_tokens: nil, temperature: nil, frequency_penalty: nil) ⇒ GeminiPro

Returns a new instance of GeminiPro.



6
7
8
9
10
11
# File 'lib/oxaiworkers/models/gemini_pro.rb', line 6

def initialize(uri_base: nil, api_key: nil, model: nil, max_tokens: nil, temperature: nil, frequency_penalty: nil)
  @model = model || 'gemini-pro'
  @uri_base = uri_base # || 'https://api.anthropic.com/v1/'
  @api_key = api_key || OxAiWorkers.configuration.access_token_gemini
  super(uri_base: @uri_base, api_key: @api_key, model: @model, max_tokens:, temperature:, frequency_penalty:)
end

Instance Method Details

#add_base64(binary:, filename:, text:, mime_type:) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/oxaiworkers/models/gemini_pro.rb', line 74

def add_base64(binary:, filename:, text:, mime_type:)
  content = []
  content << { type: 'text', text: } if text.present?
  content << {
                type: mime_type.include?('image') ? 'image' : 'document',
                source: {
                  type: 'base64',
                  media_type: mime_type,
                  data: Base64.strict_encode64(binary)
                }
              }
  content
end

#add_url(url:, text:, mime_type:) ⇒ Object



88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/oxaiworkers/models/gemini_pro.rb', line 88

def add_url(url:, text:, mime_type:)
  content = []
  content << { type: 'text', text: } if text.present?
  content << {
                type: mime_type.include?('image') ? 'image' : 'document',
                source: {
                  type: 'url',
                  url: url
                }
              }
  content
end

#build_parameters(messages:, tools: [], filtered_functions: [], tool_choice: nil) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/oxaiworkers/models/gemini_pro.rb', line 27

def build_parameters(messages:, tools: [], filtered_functions: [], tool_choice: nil)
  parameters = {
    model: @model,
    system: messages.select { |m| m[:role] == :system }.map { |m| m[:content] }.join("\n\n"),
    messages: messages.reject { |m| m[:role] == :system },
    temperature: @temperature,
    max_tokens: @max_tokens
  }
  if tools.present?
    functions = tools.map(&:to_anthropic_format).flatten

    @names = functions.map { |f| f[:name] }

    parameters[:tools] = functions.reject { |f| filtered_functions.include?(f[:name]) }

    parameters[:tool_choice] =
      tool_choice.nil? ? { type: 'any' } : { type: 'tool', name: tool_choice }
  end
  parameters
end

#clientObject



13
14
15
16
17
18
19
20
21
# File 'lib/oxaiworkers/models/gemini_pro.rb', line 13

def client
  Gemini.new(
    credentials: {
      service: 'generative-language-api',
      api_key: ENV['GOOGLE_API_KEY']
    },
    options: { model: 'gemini-pro', server_sent_events: true }
  )
end

#parse_one_choice(choice) ⇒ Object



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
141
142
143
144
145
146
147
148
# File 'lib/oxaiworkers/models/gemini_pro.rb', line 112

def parse_one_choice(choice)
  return unless choice # Skip if there's no choice

  # Initialize result variables
  @result = nil
  @tool_calls = []

  # Process content item
  if choice['type'] == 'tool_use'
    # Handle tool use
    begin
      # Attempt to parse arguments, handle potential JSON errors
      args = JSON.parse(choice['input'].to_json, symbolize_names: true)
    rescue JSON::ParserError => e
      OxAiWorkers.logger.error("Failed to parse tool call arguments: #{e.message}", for: self.class)
      OxAiWorkers.logger.debug("Raw arguments: #{choice['input']}", for: self.class)
    end

    fname = @names.find { |n| n.end_with?(choice['name']) }
    if fname != choice['name']
      OxAiWorkers.logger.error("Tool call name #{choice['name']} not found. Using #{fname} instead.",
                               for: self.class)
    end

    tool_call = {
      class: fname.split('__').first,
      name: fname.split('__').last,
      args:
    }
    @tool_calls << tool_call
  elsif choice['type'] == 'text'
    # Handle text content
    @result = choice['text']
  end

  [@result, @tool_calls]
end

#parse_response(response) ⇒ Object



101
102
103
104
105
106
107
108
109
110
# File 'lib/oxaiworkers/models/gemini_pro.rb', line 101

def parse_response(response, &)
  choices = response['content']
  @is_truncated = (response['stop_reason'] == 'max_tokens')
  return if choices.nil? || choices.empty?

  choices.each do |choice|
    result, tool_calls = parse_one_choice(choice)
    yield(result, @is_truncated, tool_calls)
  end
end

#request(parameters) ⇒ Object



23
24
25
# File 'lib/oxaiworkers/models/gemini_pro.rb', line 23

def request(parameters)
  client.messages(parameters:)
end

#tool_call(name:, args:, call_id:, out:) ⇒ Object



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
# File 'lib/oxaiworkers/models/gemini_pro.rb', line 48

def tool_call(name:, args:, call_id:, out:)
  [
    {
      role: :assistant,
      content: [
        {
          type: 'tool_use',
          id: "call_#{call_id}",
          name:,
          input: args
        }
      ]
    },
    {
      role: :user,
      content: [
        {
          type: 'tool_result',
          tool_use_id: "call_#{call_id}",
          content: out.present? ? out : "Tool call #{name} successful."
        }
      ]
    }
  ]
end