| 1 | package Praxo::Adapters::Gemini; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use HTTP::Tiny (); | ||
| 6 | use Praxo::Errors qw(praxo_error); | ||
| 7 | use Praxo::Json (); | ||
| 8 | use Praxo::Models (); | ||
| 9 | |||
| 10 | sub new { | ||
| 11 | my ($class, %args) = @_; | ||
| 12 | my $base_url = $args{base_url} // 'https://generativelanguage.googleapis.com'; | ||
| 13 | $base_url =~ s{/$}{}; | ||
| 14 | return bless { | ||
| 15 | base_url => $base_url, | ||
| 16 | model => $args{model} // '', | ||
| 17 | api_key => $args{api_key}, | ||
| 18 | max_output_tokens => $args{max_output_tokens} // 0, | ||
| 19 | transport => $args{transport}, | ||
| 20 | stream_transport => $args{stream_transport}, | ||
| 21 | timeout => $args{timeout} // 60, | ||
| 22 | }, $class; | ||
| 23 | } | ||
| 24 | |||
| 25 | sub generate { | ||
| 26 | my ($self, $request) = @_; | ||
| 27 | praxo_error('MODEL_CONFIG', 'gemini: API key is required') | ||
| 28 | unless defined $self->{api_key} && $self->{api_key} ne ''; | ||
| 29 | praxo_error('MODEL_CONFIG', 'gemini: model is required') | ||
| 30 | unless $self->{model} ne ''; | ||
| 31 | my $payload = _payload($self, $request); | ||
| 32 | my $path = '/v1beta/models/' . _escape($self->{model}) | ||
| 33 | . ':generateContent'; | ||
| 34 | my $data = $self->{transport} | ||
| 35 | ? $self->{transport}->($path, $payload) | ||
| 36 | : $self->_post($path, $payload); | ||
| 37 | return _parse_response($data); | ||
| 38 | } | ||
| 39 | |||
| 40 | sub generate_stream { | ||
| 41 | my ($self, $request, $on_delta) = @_; | ||
| 42 | praxo_error('MODEL_CONFIG', 'gemini: API key is required') | ||
| 43 | unless defined $self->{api_key} && $self->{api_key} ne ''; | ||
| 44 | praxo_error('MODEL_CONFIG', 'gemini: model is required') | ||
| 45 | unless $self->{model} ne ''; | ||
| 46 | my $payload = _payload($self, $request); | ||
| 47 | my $path = '/v1beta/models/' . _escape($self->{model}) | ||
| 48 | . ':streamGenerateContent?alt=sse'; | ||
| 49 | my $text = $self->{stream_transport} | ||
| 50 | ? $self->{stream_transport}->($path, $payload) | ||
| 51 | : $self->_post_stream($path, $payload); | ||
| 52 | praxo_error('PROVIDER_HTTP', 'gemini: stream transport must return SSE text') | ||
| 53 | if ref($text) || !defined $text; | ||
| 54 | return _parse_sse($text, $on_delta); | ||
| 55 | } | ||
| 56 | |||
| 57 | sub _parse_sse { | ||
| 58 | my ($text, $on_delta) = @_; | ||
| 59 | my $content = ''; | ||
| 60 | my @calls; | ||
| 61 | my $input_tokens = 0; | ||
| 62 | my $output_tokens = 0; | ||
| 63 | my $cached_tokens = 0; | ||
| 64 | my $finish_reason; | ||
| 65 | for my $raw (split /\n/, $text) { | ||
| 66 | my $line = $raw; | ||
| 67 | $line =~ s/^\s+//; | ||
| 68 | $line =~ s/\s+$//; | ||
| 69 | next unless $line =~ /^data:(.*)$/; | ||
| 70 | my $chunk_text = $1; | ||
| 71 | $chunk_text =~ s/^\s+//; | ||
| 72 | $chunk_text =~ s/\s+$//; | ||
| 73 | next if $chunk_text eq '' || $chunk_text eq '[DONE]'; | ||
| 74 | my $chunk = eval { Praxo::Json::parse($chunk_text) }; | ||
| 75 | praxo_error('MODEL_STREAM', 'gemini: invalid stream chunk') | ||
| 76 | unless ref($chunk) eq 'HASH'; | ||
| 77 | praxo_error('MODEL_STREAM', 'gemini: ' . ($chunk->{error}{message} // 'stream error')) | ||
| 78 | if ref($chunk->{error}) eq 'HASH'; | ||
| 79 | my $usage = ref($chunk->{usageMetadata}) eq 'HASH' ? $chunk->{usageMetadata} : {}; | ||
| 80 | $input_tokens = $usage->{promptTokenCount} | ||
| 81 | if defined $usage->{promptTokenCount}; | ||
| 82 | $output_tokens = $usage->{candidatesTokenCount} | ||
| 83 | if defined $usage->{candidatesTokenCount}; | ||
| 84 | $cached_tokens = $usage->{cachedContentTokenCount} | ||
| 85 | if defined $usage->{cachedContentTokenCount}; | ||
| 86 | my $candidate = ref($chunk->{candidates}) eq 'ARRAY' | ||
| 87 | ? $chunk->{candidates}[0] : undef; | ||
| 88 | next unless ref($candidate) eq 'HASH'; | ||
| 89 | $finish_reason = $candidate->{finishReason} | ||
| 90 | if defined $candidate->{finishReason}; | ||
| 91 | for my $part (@{ $candidate->{content}{parts} // [] }) { | ||
| 92 | my $piece = $part->{text} // ''; | ||
| 93 | if ($piece ne '') { | ||
| 94 | $content .= $piece; | ||
| 95 | $on_delta->($piece); | ||
| 96 | } | ||
| 97 | if (ref($part->{functionCall}) eq 'HASH') { | ||
| 98 | push @calls, Praxo::Models::tool_call( | ||
| 99 | id => 'call-' . (scalar(@calls) + 1), | ||
| 100 | name => $part->{functionCall}{name} // '', | ||
| 101 | arguments => $part->{functionCall}{args} // {}, | ||
| 102 | ); | ||
| 103 | } | ||
| 104 | } | ||
| 105 | } | ||
| 106 | return Praxo::Models::response( | ||
| 107 | message => Praxo::Models::message_assistant($content, \@calls), | ||
| 108 | usage => Praxo::Models::usage( | ||
| 109 | input_tokens => $input_tokens, | ||
| 110 | output_tokens => $output_tokens, | ||
| 111 | cached_tokens => $cached_tokens, | ||
| 112 | ), | ||
| 113 | finish_reason => $finish_reason, | ||
| 114 | ); | ||
| 115 | } | ||
| 116 | |||
| 117 | sub _post_stream { | ||
| 118 | my ($self, $path, $payload) = @_; | ||
| 119 | my %headers = ( | ||
| 120 | 'content-type' => 'application/json', | ||
| 121 | 'accept' => 'text/event-stream', | ||
| 122 | 'x-goog-api-key' => $self->{api_key}, | ||
| 123 | ); | ||
| 124 | my $http = HTTP::Tiny->new(timeout => $self->{timeout}); | ||
| 125 | my $response = $http->post( | ||
| 126 | $self->{base_url} . $path, | ||
| 127 | { headers => \%headers, content => Praxo::Json::stringify($payload) }, | ||
| 128 | ); | ||
| 129 | praxo_error( | ||
| 130 | 'PROVIDER_HTTP', | ||
| 131 | 'provider returned HTTP ' . ($response->{status} // 0) . ': ' . ($response->{content} // ''), | ||
| 132 | ) unless $response->{success}; | ||
| 133 | return $response->{content}; | ||
| 134 | } | ||
| 135 | |||
| 136 | sub _payload { | ||
| 137 | my ($self, $request) = @_; | ||
| 138 | my ($system, $contents) = _build_contents($request->{messages}); | ||
| 139 | my %payload = (contents => $contents); | ||
| 140 | $payload{system_instruction} = { parts => $system } if @$system; | ||
| 141 | my @declarations = map { | ||
| 142 | { | ||
| 143 | name => $_->{name}, | ||
| 144 | description => $_->{description} // '', | ||
| 145 | parameters => $_->{parameters} // { type => 'object', properties => {} }, | ||
| 146 | } | ||
| 147 | } @{ $request->{tools} // [] }; | ||
| 148 | if (@declarations) { | ||
| 149 | $payload{tools} = [{ functionDeclarations => \@declarations }]; | ||
| 150 | $payload{toolConfig} = { | ||
| 151 | functionCallingConfig => { | ||
| 152 | mode => _tool_mode($request->{toolChoice}), | ||
| 153 | }, | ||
| 154 | }; | ||
| 155 | } | ||
| 156 | if ((defined $request->{temperature} && $request->{temperature} != 0) | ||
| 157 | || $self->{max_output_tokens} > 0) { | ||
| 158 | $payload{generationConfig} = { | ||
| 159 | temperature => $request->{temperature} // 0, | ||
| 160 | maxOutputTokens => $self->{max_output_tokens}, | ||
| 161 | }; | ||
| 162 | } | ||
| 163 | return \%payload; | ||
| 164 | } | ||
| 165 | |||
| 166 | sub _build_contents { | ||
| 167 | my ($messages) = @_; | ||
| 168 | my @system; | ||
| 169 | my @out; | ||
| 170 | my @pending; | ||
| 171 | my %names; | ||
| 172 | my $flush = sub { | ||
| 173 | return unless @pending; | ||
| 174 | push @out, { role => 'user', parts => [@pending] }; | ||
| 175 | @pending = (); | ||
| 176 | }; | ||
| 177 | for my $message (@{ $messages // [] }) { | ||
| 178 | if ($message->{role} eq Praxo::Models::SYSTEM()) { | ||
| 179 | push @system, { text => $message->{content} } | ||
| 180 | if defined $message->{content} && $message->{content} ne ''; | ||
| 181 | next; | ||
| 182 | } | ||
| 183 | if ($message->{role} eq Praxo::Models::TOOL()) { | ||
| 184 | my $name = $names{$message->{toolId} // ''} // $message->{toolId} // 'tool'; | ||
| 185 | push @pending, { | ||
| 186 | functionResponse => { | ||
| 187 | name => $name, | ||
| 188 | response => { result => $message->{content} // '' }, | ||
| 189 | }, | ||
| 190 | }; | ||
| 191 | next; | ||
| 192 | } | ||
| 193 | $flush->(); | ||
| 194 | my $parts = _message_parts($message); | ||
| 195 | if (@$parts) { | ||
| 196 | push @out, { | ||
| 197 | role => $message->{role} eq Praxo::Models::ASSISTANT() ? 'model' : 'user', | ||
| 198 | parts => $parts, | ||
| 199 | }; | ||
| 200 | } | ||
| 201 | for my $call (@{ $message->{toolCalls} // [] }) { | ||
| 202 | $names{$call->{id}} = $call->{name} | ||
| 203 | if defined $call->{id} && $call->{id} ne '' | ||
| 204 | && defined $call->{name} && $call->{name} ne ''; | ||
| 205 | } | ||
| 206 | } | ||
| 207 | $flush->(); | ||
| 208 | return (\@system, \@out); | ||
| 209 | } | ||
| 210 | |||
| 211 | sub _message_parts { | ||
| 212 | my ($message) = @_; | ||
| 213 | my @parts; | ||
| 214 | push @parts, { text => $message->{content} } | ||
| 215 | if defined $message->{content} && $message->{content} ne ''; | ||
| 216 | for my $block (@{ $message->{contentBlocks} // [] }) { | ||
| 217 | push @parts, { text => $block->{text} } | ||
| 218 | if ($block->{type} // '') eq 'text' | ||
| 219 | && defined $block->{text} && $block->{text} ne ''; | ||
| 220 | } | ||
| 221 | for my $call (@{ $message->{toolCalls} // [] }) { | ||
| 222 | push @parts, { | ||
| 223 | functionCall => { | ||
| 224 | name => $call->{name} // '', | ||
| 225 | args => $call->{arguments} // {}, | ||
| 226 | }, | ||
| 227 | }; | ||
| 228 | } | ||
| 229 | return \@parts; | ||
| 230 | } | ||
| 231 | |||
| 232 | sub _escape { | ||
| 233 | my ($value) = @_; | ||
| 234 | $value =~ s/([^A-Za-z0-9._~-])/sprintf("%%%02X", ord($1))/ge; | ||
| 235 | return $value; | ||
| 236 | } | ||
| 237 | |||
| 238 | sub _tool_mode { | ||
| 239 | my ($choice) = @_; | ||
| 240 | return 'ANY' if defined $choice && $choice eq 'required'; | ||
| 241 | return 'NONE' if defined $choice && $choice eq 'none'; | ||
| 242 | return 'AUTO'; | ||
| 243 | } | ||
| 244 | |||
| 245 | sub _parse_response { | ||
| 246 | my ($data) = @_; | ||
| 247 | praxo_error('MODEL_HTTP', 'gemini: ' . ($data->{error}{message} // 'error')) | ||
| 248 | if ref($data->{error}) eq 'HASH'; | ||
| 249 | my $candidate = ref($data->{candidates}) eq 'ARRAY' | ||
| 250 | ? $data->{candidates}[0] : undef; | ||
| 251 | praxo_error('MODEL_HTTP', 'gemini: empty response') | ||
| 252 | unless ref($candidate) eq 'HASH'; | ||
| 253 | my $text = ''; | ||
| 254 | my @calls; | ||
| 255 | for my $part (@{ $candidate->{content}{parts} // [] }) { | ||
| 256 | $text .= $part->{text} // '' if defined $part->{text}; | ||
| 257 | if (ref($part->{functionCall}) eq 'HASH') { | ||
| 258 | push @calls, Praxo::Models::tool_call( | ||
| 259 | id => 'call-' . (scalar(@calls) + 1), | ||
| 260 | name => $part->{functionCall}{name} // '', | ||
| 261 | arguments => $part->{functionCall}{args} // {}, | ||
| 262 | ); | ||
| 263 | } | ||
| 264 | } | ||
| 265 | my $usage = ref($data->{usageMetadata}) eq 'HASH' ? $data->{usageMetadata} : {}; | ||
| 266 | return Praxo::Models::response( | ||
| 267 | message => Praxo::Models::message_assistant($text, \@calls), | ||
| 268 | usage => Praxo::Models::usage( | ||
| 269 | input_tokens => $usage->{promptTokenCount} // 0, | ||
| 270 | output_tokens => $usage->{candidatesTokenCount} // 0, | ||
| 271 | cached_tokens => $usage->{cachedContentTokenCount} // 0, | ||
| 272 | ), | ||
| 273 | finish_reason => $candidate->{finishReason}, | ||
| 274 | ); | ||
| 275 | } | ||
| 276 | |||
| 277 | sub _post { | ||
| 278 | my ($self, $path, $payload) = @_; | ||
| 279 | my %headers = ( | ||
| 280 | 'content-type' => 'application/json', | ||
| 281 | 'x-goog-api-key' => $self->{api_key}, | ||
| 282 | ); | ||
| 283 | my $http = HTTP::Tiny->new(timeout => $self->{timeout}); | ||
| 284 | my $response = $http->post( | ||
| 285 | $self->{base_url} . $path, | ||
| 286 | { headers => \%headers, content => Praxo::Json::stringify($payload) }, | ||
| 287 | ); | ||
| 288 | praxo_error( | ||
| 289 | 'PROVIDER_HTTP', | ||
| 290 | 'provider returned HTTP ' . ($response->{status} // 0) . ': ' . ($response->{content} // ''), | ||
| 291 | ) unless $response->{success}; | ||
| 292 | return Praxo::Json::parse($response->{content}); | ||
| 293 | } | ||
| 294 | |||
| 295 | 1; |