Class: Gemini::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/gemini/response.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(response_data) ⇒ Response

Returns a new instance of Response.



6
7
8
# File 'lib/gemini/response.rb', line 6

def initialize(response_data)
  @raw_data = response_data
end

Instance Attribute Details

#raw_dataObject (readonly)

Raw response data from API



4
5
6
# File 'lib/gemini/response.rb', line 4

def raw_data
  @raw_data
end

Instance Method Details

#as_json_array(model_class) ⇒ Object



421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
# File 'lib/gemini/response.rb', line 421

def as_json_array(model_class)
  json_data = json
  return [] unless json_data && json_data.is_a?(Array)
  
  begin
    json_data.map do |item|
      if model_class.respond_to?(:from_json)
        model_class.from_json(item)
      elsif defined?(ActiveModel::Model) && model_class.ancestors.include?(ActiveModel::Model)
        model_class.new(item)
      else
        instance = model_class.new
        
        item.each do |key, value|
          setter_method = "#{key}="
          if instance.respond_to?(setter_method)
            instance.send(setter_method, value)
          end
        end
        
        instance
      end
    end
  rescue => e
    []
  end
end

#as_json_object(model_class) ⇒ Object



395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'lib/gemini/response.rb', line 395

def as_json_object(model_class)
  json_data = json
  return nil unless json_data
  
  begin
    if model_class.respond_to?(:from_json)
      model_class.from_json(json_data)
    elsif defined?(ActiveModel::Model) && model_class.ancestors.include?(ActiveModel::Model)
      model_class.new(json_data)
    else
      instance = model_class.new
      
      json_data.each do |key, value|
        setter_method = "#{key}="
        if instance.respond_to?(setter_method)
          instance.send(setter_method, value)
        end
      end
      
      instance
    end
  rescue => e
    nil
  end
end

#as_json_with_keys(*keys) ⇒ Object



449
450
451
452
453
454
455
456
457
458
# File 'lib/gemini/response.rb', line 449

def as_json_with_keys(*keys)
  json_data = json
  return [] unless json_data && json_data.is_a?(Array)
  
  json_data.map do |item|
    keys.each_with_object({}) do |key, result|
      result[key.to_s] = item[key.to_s] if item.key?(key.to_s)
    end
  end
end

#candidatesObject

Get all candidates (if multiple candidates are present)



67
68
69
# File 'lib/gemini/response.rb', line 67

def candidates
  @raw_data&.dig("candidates") || []
end

#completion_tokensObject

Get number of tokens used for completion



186
187
188
# File 'lib/gemini/response.rb', line 186

def completion_tokens
  usage&.dig("candidateTokens") || 0
end

#errorObject

Get error message if any



79
80
81
82
83
84
85
86
# File 'lib/gemini/response.rb', line 79

def error
  return nil if valid?
  
  # Return nil for empty responses (to display "Empty response" in to_s method)
  return nil if @raw_data.nil? || @raw_data.empty?
  
  @raw_data&.dig("error", "message") || "Unknown error"
end

#finish_reasonObject

Get finish reason (STOP, SAFETY, etc.)



94
95
96
# File 'lib/gemini/response.rb', line 94

def finish_reason
  first_candidate&.dig("finishReason")
end

#first_candidateObject

Get the first candidate



62
63
64
# File 'lib/gemini/response.rb', line 62

def first_candidate
  @raw_data&.dig("candidates", 0)
end

#formatted_textObject

Get formatted text (HTML/markdown, etc.)



21
22
23
24
25
# File 'lib/gemini/response.rb', line 21

def formatted_text
  return nil unless valid?
  
  text # Currently returns plain text, but could add formatting in the future
end

#full_contentObject

Get all content with string representation



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/gemini/response.rb', line 49

def full_content
  parts.map do |part|
    if part.key?("text")
      part["text"]
    elsif part.key?("inline_data") && part["inline_data"]["mime_type"].start_with?("image/")
      "[IMAGE: #{part["inline_data"]["mime_type"]}]"
    else
      "[UNKNOWN CONTENT]"
    end
  end.join("\n")
end

#function_callsObject

Get function call information



212
213
214
215
# File 'lib/gemini/response.rb', line 212

def function_calls
  parts = first_candidate.dig("content", "parts") || []
  parts.map { |part| part["functionCall"] }.compact
end

#grounded?Boolean

Check if response has grounding metadata

Returns:

  • (Boolean)


109
110
111
# File 'lib/gemini/response.rb', line 109

def grounded?
  !.nil? && !.empty?
end

#grounding_chunksObject

Get grounding chunks (source references)



114
115
116
# File 'lib/gemini/response.rb', line 114

def grounding_chunks
  &.dig("groundingChunks") || []
end

#grounding_metadataObject

Get grounding metadata (for Google Search grounding)



104
105
106
# File 'lib/gemini/response.rb', line 104

def 
  first_candidate&.dig("groundingMetadata")
end

#grounding_sourcesObject

Get formatted grounding sources (simplified access)



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/gemini/response.rb', line 124

def grounding_sources
  return [] unless grounded?

  grounding_chunks.map do |chunk|
    if chunk["web"]
      {
        url: chunk["web"]["uri"],
        title: chunk["web"]["title"],
        type: "web"
      }
    else
      # Handle other potential chunk types
      {
        type: "unknown",
        data: chunk
      }
    end
  end
end

#imageObject

画像生成結果から最初の画像を取得(Base64エンコード形式)



228
229
230
# File 'lib/gemini/response.rb', line 228

def image
  images.first
end

#image_mime_typesObject

画像のMIMEタイプを取得



289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/gemini/response.rb', line 289

def image_mime_types
  return [] unless valid?
  
  if first_candidate&.dig("content", "parts")
    first_candidate["content"]["parts"]
      .select { |part| part.key?("inline_data") && part["inline_data"]["mime_type"].start_with?("image/") }
      .map { |part| part["inline_data"]["mime_type"] }
  else
    # Imagen 3のデフォルトはPNG
    Array.new(images.size, "image/png")
  end
end

#image_partsObject

Get image parts (if any)



42
43
44
45
46
# File 'lib/gemini/response.rb', line 42

def image_parts
  return [] unless valid?
  
  parts.select { |part| part.key?("inline_data") && part["inline_data"]["mime_type"].start_with?("image/") }
end

#image_urlsObject

Get image URLs from multimodal responses (if any)



203
204
205
206
207
208
209
# File 'lib/gemini/response.rb', line 203

def image_urls
  return [] unless valid?
  
  first_candidate&.dig("content", "parts")
    &.select { |part| part.key?("image_url") }
    &.map { |part| part.dig("image_url", "url") } || []
end

#imagesObject

画像生成結果からすべての画像を取得(Base64エンコード形式の配列)



233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/gemini/response.rb', line 233

def images
  image_array = []
  return image_array unless @raw_data
  
  # Gemini 2.0スタイルレスポンスを正確に解析
  # キーはcamelCase形式で使用されているので注意(inlineDataなど)
  if @raw_data.key?('candidates') && !@raw_data['candidates'].empty?
    candidate = @raw_data['candidates'][0]
    if candidate.key?('content') && candidate['content'].key?('parts')
      parts = candidate['content']['parts']
      
      parts.each do |part|
        # キャメルケースでアクセス(inlineData)
        if part.key?('inlineData')
          inline_data = part['inlineData']
          if inline_data.key?('mimeType') && 
             inline_data['mimeType'].to_s.start_with?('image/') &&
             inline_data.key?('data')
            
            # 画像データを追加
            image_array << inline_data['data']
            puts "画像データを検出しました: #{inline_data['mimeType']}" if ENV["DEBUG"]
          end
        end
      end
    end
  # Imagen 3スタイルレスポンスのチェック
  elsif @raw_data.key?('predictions')
    @raw_data['predictions'].each do |pred|
      if pred.key?('bytesBase64Encoded')
        image_array << pred['bytesBase64Encoded']
        puts "Imagen 3形式の画像データを検出しました" if ENV["DEBUG"]
      end
    end
  end
  
  # フォールバック:直接JSONから抽出
  if image_array.empty?
    puts "標準的な方法で画像データが見つかりませんでした。正規表現による抽出を試みます..." if ENV["DEBUG"]
    raw_json = @raw_data.to_json
    
    # "data"キーで長いBase64文字列を検索
    base64_matches = raw_json.scan(/"data":"([A-Za-z0-9+\/=]{100,})"/)
    if !base64_matches.empty?
      puts "検出したBase64データ: #{base64_matches.size}" if ENV["DEBUG"]
      base64_matches.each do |match|
        image_array << match[0]
      end
    end
  end
  
  puts "検出した画像データ数: #{image_array.size}" if ENV["DEBUG"]
  image_array
end

#inspectObject

Inspection method for debugging



370
371
372
# File 'lib/gemini/response.rb', line 370

def inspect
  "#<Gemini::Response text=#{text ? text[0..30] + (text.length > 30 ? '...' : '') : 'nil'} success=#{success?}>"
end

#jsonObject



374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
# File 'lib/gemini/response.rb', line 374

def json
  return nil unless valid?
  
  text_content = text
  return nil unless text_content
  
  begin
    if text_content.strip.start_with?('{') || text_content.strip.start_with?('[')
      JSON.parse(text_content)
    else
      nil
    end
  rescue JSON::ParserError => e
    nil
  end
end

#json?Boolean

Returns:

  • (Boolean)


391
392
393
# File 'lib/gemini/response.rb', line 391

def json?
  !json.nil?
end

#partsObject

Get all content parts



28
29
30
31
32
# File 'lib/gemini/response.rb', line 28

def parts
  return [] unless valid?
  
  first_candidate&.dig("content", "parts") || []
end

#prompt_tokensObject

Get number of prompt tokens used



181
182
183
# File 'lib/gemini/response.rb', line 181

def prompt_tokens
  usage&.dig("promptTokens") || 0
end

#retrieved_urlsObject

Get retrieved URLs from URL context



155
156
157
158
159
# File 'lib/gemini/response.rb', line 155

def retrieved_urls
  return [] unless url_context?

  &.dig("urlMetadata") || []
end

#roleObject

Get response role (usually “model”)



218
219
220
# File 'lib/gemini/response.rb', line 218

def role
  first_candidate&.dig("content", "role")
end

#safety_blocked?Boolean

Check if response was blocked for safety reasons

Returns:

  • (Boolean)


99
100
101
# File 'lib/gemini/response.rb', line 99

def safety_blocked?
  finish_reason == "SAFETY"
end

#safety_ratingsObject

Get safety ratings



223
224
225
# File 'lib/gemini/response.rb', line 223

def safety_ratings
  first_candidate&.dig("safetyRatings") || []
end

#save_image(filepath) ⇒ Object

最初の画像をファイルに保存



303
304
305
# File 'lib/gemini/response.rb', line 303

def save_image(filepath)
  save_images([filepath]).first
end

#save_images(filepaths) ⇒ Object

複数の画像をファイルに保存



308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
# File 'lib/gemini/response.rb', line 308

def save_images(filepaths)
  require 'base64'
  
  result = []
  image_data = images
  
  puts "保存する画像データ数: #{image_data.size}" if ENV["DEBUG"]
  
  # ファイルパスと画像データの数が一致しない場合
  if filepaths.size < image_data.size
    puts "警告: ファイルパスの数(#{filepaths.size})が画像データの数(#{image_data.size})より少ないです" if ENV["DEBUG"]
    # ファイルパスの数に合わせて画像データを切り詰める
    image_data = image_data[0...filepaths.size]
  elsif filepaths.size > image_data.size
    puts "警告: ファイルパスの数(#{filepaths.size})が画像データの数(#{image_data.size})より多いです" if ENV["DEBUG"]
    # 画像データの数に合わせてファイルパスを切り詰める
    filepaths = filepaths[0...image_data.size]
  end
  
  image_data.each_with_index do |data, i|
    begin
      if !data || data.empty?
        puts "警告: インデックス #{i} の画像データが空です" if ENV["DEBUG"]
        result << nil
        next
      end
      
      # データがBase64エンコードされていることを確認
      if data.match?(/^[A-Za-z0-9+\/=]+$/)
        # 一般的なBase64データ
        decoded_data = Base64.strict_decode64(data)
      else
        # データプレフィックスがある場合など(例: data:image/png;base64,xxxxx)
        if data.include?('base64,')
          base64_part = data.split('base64,').last
          decoded_data = Base64.strict_decode64(base64_part)
        else
          puts "警告: インデックス #{i} のデータはBase64形式ではありません" if ENV["DEBUG"]
          decoded_data = data # 既にバイナリかもしれない
        end
      end
      
      File.open(filepaths[i], 'wb') do |f|
        f.write(decoded_data)
      end
      result << filepaths[i]
    rescue => e
      puts "エラー: 画像 #{i} の保存中にエラーが発生しました: #{e.message}" if ENV["DEBUG"]
      puts e.backtrace.join("\n") if ENV["DEBUG"]
      result << nil
    end
  end
  
  result
end

#search_entry_pointObject

Get search entry point URL (if available)



119
120
121
# File 'lib/gemini/response.rb', line 119

def search_entry_point
  &.dig("searchEntryPoint", "renderedContent")
end

#stream_chunksObject

Process chunks for streaming responses



196
197
198
199
200
# File 'lib/gemini/response.rb', line 196

def stream_chunks
  return [] unless @raw_data.is_a?(Array)
  
  @raw_data
end

#success?Boolean

Check if response was successful

Returns:

  • (Boolean)


89
90
91
# File 'lib/gemini/response.rb', line 89

def success?
  valid? && !@raw_data.key?("error")
end

#textObject

Get simple text response (combines multiple parts if present)



11
12
13
14
15
16
17
18
# File 'lib/gemini/response.rb', line 11

def text
  return nil unless valid?
  
  first_candidate&.dig("content", "parts")
    &.select { |part| part.key?("text") }
    &.map { |part| part["text"] }
    &.join("\n") || ""
end

#text_partsObject

Get all text parts as an array



35
36
37
38
39
# File 'lib/gemini/response.rb', line 35

def text_parts
  return [] unless valid?
  
  parts.select { |part| part.key?("text") }.map { |part| part["text"] }
end

#to_formatted_json(pretty: false) ⇒ Object



460
461
462
463
464
465
466
467
468
469
# File 'lib/gemini/response.rb', line 460

def to_formatted_json(pretty: false)
  json_data = json
  return nil unless json_data
  
  if pretty
    JSON.pretty_generate(json_data)
  else
    JSON.generate(json_data)
  end
end

#to_sObject

Override to_s method to return text



365
366
367
# File 'lib/gemini/response.rb', line 365

def to_s
  text || error || "Empty response"
end

#total_tokensObject

Get total tokens used



191
192
193
# File 'lib/gemini/response.rb', line 191

def total_tokens
  usage&.dig("totalTokens") || 0
end

#url_context?Boolean

Check if response has URL context metadata

Returns:

  • (Boolean)


150
151
152
# File 'lib/gemini/response.rb', line 150

def url_context?
  !.nil? && !.empty?
end

#url_context_metadataObject

Get URL context metadata (for URL Context tool)



145
146
147
# File 'lib/gemini/response.rb', line 145

def 
  first_candidate&.dig("urlContextMetadata")
end

#url_retrieval_statusesObject

Get URL retrieval statuses



162
163
164
165
166
167
168
169
170
171
172
# File 'lib/gemini/response.rb', line 162

def url_retrieval_statuses
  return [] unless url_context?

  retrieved_urls.map do |url_info|
    {
      url: url_info["retrievedUrl"],
      status: url_info["urlRetrievalStatus"],
      title: url_info["title"]
    }
  end
end

#usageObject

Get token usage information



176
177
178
# File 'lib/gemini/response.rb', line 176

def usage
  @raw_data&.dig("usage") || {}
end

#valid?Boolean

Check if response is valid

Returns:

  • (Boolean)


72
73
74
75
76
# File 'lib/gemini/response.rb', line 72

def valid?
  !@raw_data.nil? && 
  ((@raw_data.key?("candidates") && !@raw_data["candidates"].empty?) || 
   (@raw_data.key?("predictions") && !@raw_data["predictions"].empty?))
end