|
2 | 2 |
|
3 | 3 | module RubyLLM |
4 | 4 | module Providers |
5 | | - class Gemini |
| 5 | + class Gemini # rubocop:disable Style/Documentation |
6 | 6 | # Media handling methods for the Gemini API integration |
7 | 7 | module Media |
8 | 8 | module_function |
@@ -50,6 +50,63 @@ def format_text(text) |
50 | 50 | } |
51 | 51 | end |
52 | 52 | end |
| 53 | + |
| 54 | + def build_response_content(parts) # rubocop:disable Metrics/PerceivedComplexity |
| 55 | + text = [] |
| 56 | + attachments = [] |
| 57 | + |
| 58 | + parts.each_with_index do |part, index| |
| 59 | + if part['text'] |
| 60 | + text << part['text'] |
| 61 | + elsif part['inlineData'] |
| 62 | + attachment = build_inline_attachment(part['inlineData'], index) |
| 63 | + attachments << attachment if attachment |
| 64 | + elsif part['fileData'] |
| 65 | + attachment = build_file_attachment(part['fileData'], index) |
| 66 | + attachments << attachment if attachment |
| 67 | + end |
| 68 | + end |
| 69 | + |
| 70 | + text = text.join |
| 71 | + text = nil if text.empty? |
| 72 | + return text if attachments.empty? |
| 73 | + |
| 74 | + Content.new(text:, attachments:) |
| 75 | + end |
| 76 | + |
| 77 | + def build_inline_attachment(inline_data, index) |
| 78 | + encoded = inline_data['data'] |
| 79 | + return unless encoded |
| 80 | + |
| 81 | + mime_type = inline_data['mimeType'] |
| 82 | + decoded = Base64.decode64(encoded) |
| 83 | + io = StringIO.new(decoded) |
| 84 | + io.set_encoding(Encoding::BINARY) if io.respond_to?(:set_encoding) |
| 85 | + |
| 86 | + filename = attachment_filename(mime_type, index) |
| 87 | + RubyLLM::Attachment.new(io, filename:) |
| 88 | + rescue ArgumentError => e |
| 89 | + RubyLLM.logger.warn "Failed to decode Gemini inline data attachment: #{e.message}" |
| 90 | + nil |
| 91 | + end |
| 92 | + |
| 93 | + def build_file_attachment(file_data, index) |
| 94 | + uri = file_data['fileUri'] |
| 95 | + return unless uri |
| 96 | + |
| 97 | + filename = file_data['filename'] || attachment_filename(file_data['mimeType'], index) |
| 98 | + RubyLLM::Attachment.new(uri, filename:) |
| 99 | + end |
| 100 | + |
| 101 | + def attachment_filename(mime_type, index) |
| 102 | + return "gemini_attachment_#{index + 1}" unless mime_type |
| 103 | + |
| 104 | + extension = mime_type.split('/').last.to_s |
| 105 | + extension = 'jpg' if extension == 'jpeg' |
| 106 | + extension = 'txt' if extension == 'plain' |
| 107 | + extension = extension.tr('+', '.') |
| 108 | + "gemini_attachment_#{index + 1}.#{extension}" |
| 109 | + end |
53 | 110 | end |
54 | 111 | end |
55 | 112 | end |
0 commit comments