Class: Ask::Providers::Google

Inherits:
Ask::Provider
  • Object
show all
Includes:
LLM::ProviderConfig, LLM::SSEBuffer
Defined in:
lib/ask/provider/google.rb

Overview

Google Gemini API provider. Also supports Vertex AI via GCP service account auth.

Class Method Summary collapse

Instance Method Summary collapse

Methods included from LLM::SSEBuffer

#each_sse_event, #init_sse_buffer

Constructor Details

#initialize(config = {}) ⇒ Google

Returns a new instance of Google.



10
11
12
13
14
15
# File 'lib/ask/provider/google.rb', line 10

def initialize(config = {})
  config = normalize_config(config)
  super(config)
  @http = build_http
  @project_id = config.project_id
end

Class Method Details

.capabilitiesObject



72
73
74
75
76
77
# File 'lib/ask/provider/google.rb', line 72

def capabilities
  {
    chat: true, streaming: true, tool_calls: true, vision: true,
    structured_output: true, embed: true, file_upload: true
  }
end

.configuration_optionsObject



79
# File 'lib/ask/provider/google.rb', line 79

def configuration_options; %i[api_key access_token vertex_token project_id api_base]; end

.configuration_requirementsObject



80
# File 'lib/ask/provider/google.rb', line 80

def configuration_requirements; %i[api_key]; end

.slugObject



70
# File 'lib/ask/provider/google.rb', line 70

def slug; "gemini"; end

Instance Method Details

#api_baseObject



17
18
19
# File 'lib/ask/provider/google.rb', line 17

def api_base
  @config.api_base || "https://generativelanguage.googleapis.com/v1beta"
end

#build_request(messages, model:, tools: nil, temperature: nil, stream: nil, schema: nil, **params) ⇒ Object

--- Config transformation contract ---



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/ask/provider/google.rb', line 85

def build_request(messages, model:, tools: nil, temperature: nil, stream: nil, schema: nil, **params)
  payload = { contents: format_contents(messages), systemInstruction: format_system(messages) }

  if tools&.any?
    payload[:tools] = [{ functionDeclarations: tools.map { |t| format_tool(t) } }]
  end
  if schema
    payload[:generationConfig] ||= {}
    payload[:generationConfig][:response_mime_type] = "application/json"
    payload[:generationConfig][:response_schema] = schema
  end
  payload[:generationConfig] ||= {}
  payload[:generationConfig][:temperature] = temperature if temperature
  payload.merge(params)
end

#chat(messages, model:, tools: nil, temperature: nil, stream: nil, schema: nil, **params, &block) ⇒ Object



33
34
35
36
37
38
39
40
41
42
# File 'lib/ask/provider/google.rb', line 33

def chat(messages, model:, tools: nil, temperature: nil, stream: nil, schema: nil, **params, &block)
  msgs = messages.is_a?(Ask::Conversation) ? messages.to_a : messages
  payload = build_request(msgs, model:, tools:, temperature:, stream:, schema:, **params)
  path = chat_path(model)
  if stream
    chat_stream(path, payload, model, &block)
  else
    chat_nonstream(path, payload, model)
  end
end

#embed(texts, model:) ⇒ Object



44
45
46
47
48
49
50
51
52
53
# File 'lib/ask/provider/google.rb', line 44

def embed(texts, model:)
  texts = Array(texts)
  response = @http.post("models/#{model}:batchEmbedContents") { |r|
    r.body = { requests: texts.map { |t| { model: "models/#{model}", content: { parts: [{ text: t }] } } } }
  }
  raise LLM::HTTP.map_error(response.status, response.body, provider: "Google") unless response.success?

  embeddings = response.body.dig("embeddings") || []
  Ask::Result.success(embeddings.map { |e| e["values"] })
end

#format_google_content_block(block) ⇒ Object

Gemini content block → flat parts array. Media/file blocks become inlineData (base64) or fileData (uri/file_id); text-like files are inlined as text with a filename marker; unsupported blocks are skipped rather than mangled.



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/ask/provider/google.rb', line 181

def format_google_content_block(block)
  block = block.transform_keys(&:to_sym) if block.respond_to?(:transform_keys)
  type = block[:type] || block["type"]

  case type
  when "text"
    [{ text: block[:text] || block["text"] }]
  when "image", "audio", "video"
    mime = block[:mime_type] || block["mime_type"]
    file_id = block[:file_id] || block["file_id"]
    url = block[:url] || block["url"]
    base64 = block[:base64] || block["base64"]

    if file_id
      [{ fileData: { mimeType: mime, fileUri: file_id } }]
    elsif url
      [{ fileData: { mimeType: mime, fileUri: url } }]
    elsif base64
      [{ inlineData: { mimeType: (mime || "application/octet-stream"), data: base64 } }]
    else
      []
    end
  when "file"
    mime = block[:mime_type] || block["mime_type"]
    file_id = block[:file_id] || block["file_id"]
    url = block[:url] || block["url"]
    data = block[:data] || block["data"]

    if file_id
      [{ fileData: { mimeType: mime, fileUri: file_id } }]
    elsif url
      [{ fileData: { mimeType: mime, fileUri: url } }]
    elsif data
      if mime.to_s.start_with?("text/")
        filename = block[:filename] ? "[#{block[:filename]}] " : ""
        [{ text: "#{filename}#{data}" }]
      else
        [{ inlineData: { mimeType: (mime || "application/octet-stream"), data: Base64.strict_encode64(data) } }]
      end
    else
      []
    end
  else
    []
  end
end

#format_message(msg) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/ask/provider/google.rb', line 140

def format_message(msg)
  role = (msg[:role] || msg["role"]).to_s
  content = msg[:content] || msg["content"]
  google_role = role == "assistant" ? "model" : role

  parts = []
  if content.is_a?(Array)
    # Content blocks → Gemini parts (flat parts array). Previously
    # arrays were passed through as a broken { text: [hash, …] } part.
    content.each { |block| parts.concat(format_google_content_block(block)) }
  elsif content
    parts << { text: content }
  end

  if msg[:tool_calls] || msg["tool_calls"]
    (msg[:tool_calls] || msg["tool_calls"]).each do |tc|
      parts << {
        functionCall: {
          name: tc.dig(:function, :name) || tc.dig("function", "name") || tc[:name],
          args: parse_json(tc.dig(:function, :arguments) || tc.dig("function", "arguments") || tc[:arguments] || "{}")
        }
      }
    end
  end

  if msg[:tool_call_id] || msg["tool_call_id"]
    parts << {
      functionResponse: {
        name: msg[:name] || msg["name"] || "function",
        response: { content: content || "" }
      }
    }
  end

  { role: google_role, parts: }
end

#format_tools(tools) ⇒ Object



228
229
230
231
232
233
234
235
236
# File 'lib/ask/provider/google.rb', line 228

def format_tools(tools)
  tools.map { |t|
    {
      name: t.respond_to?(:name) ? t.name : t[:name],
      description: t.respond_to?(:description) ? t.description : t[:description],
      parameters: t.respond_to?(:parameters) ? t.parameters : (t[:parameters] || {})
    }
  }
end

#headersObject



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/ask/provider/google.rb', line 21

def headers
  h = { "Content-Type" => "application/json" }
  if @config.api_key
    # Gemini uses query param auth by default
  elsif @config.access_token
    h["Authorization"] = "Bearer #{@config.access_token}"
  elsif @config.vertex_token
    h["Authorization"] = "Bearer #{@config.vertex_token}"
  end
  h
end

#list_modelsObject



55
56
57
58
59
60
61
62
# File 'lib/ask/provider/google.rb', line 55

def list_models
  response = @http.get("models") { |r| r.params["key"] = @config.api_key if @config.api_key }
  return [] unless response.success?

  (response.body["models"] || []).map { |m|
    Ask::ModelInfo.new(id: m["name"].sub("models/", ""), provider: slug)
  }
end

#parse_error(response) ⇒ Object



64
65
66
67
# File 'lib/ask/provider/google.rb', line 64

def parse_error(response)
  body = response.body rescue nil
  body&.dig("error", "message")
end

#parse_response(body, model) ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/ask/provider/google.rb', line 101

def parse_response(body, model)
  candidate = body.dig("candidates", 0)
  return Ask::Message.new(role: :assistant, content: nil) unless candidate

  content = candidate.dig("content", "parts")&.map { |p| p["text"] }&.compact&.join
  fc = candidate.dig("content", "parts")&.select { |p| p["functionCall"] } || []
  tool_calls = fc.map do |p|
    f = p["functionCall"]
    { id: SecureRandom.hex(8), type: "function", name: f["name"], arguments: JSON.generate(f["args"] || {}) }
  end

  usage = body["usageMetadata"] || {}
  Ask::Message.new(
    role: :assistant,
    content:,
    tool_calls: tool_calls.empty? ? nil : tool_calls,
    metadata: {
      model:,
      finish_reason: candidate["finishReason"],
      input_tokens: usage["promptTokenCount"],
      output_tokens: usage["candidatesTokenCount"],
      raw: body
    }
  )
end

#parse_stream(raw, stream, model, &block) ⇒ Object



127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/ask/provider/google.rb', line 127

def parse_stream(raw, stream, model, &block)
  each_sse_event(raw) do |data|
    parsed = JSON.parse(data) rescue next
    candidate = parsed.dig("candidates", 0) or next
    part = candidate.dig("content", "parts", 0)
    next unless part

    chunk = Ask::Chunk.new(content: part["text"])
    stream.add(chunk)
    yield chunk if block_given?
  end
end