| 1 | package Praxo::Adapters::Anthropic; | ||
| 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://api.anthropic.com'; | ||
| 13 | $base_url =~ s{/$}{}; | ||
| 14 | return bless { | ||
| 15 | base_url => $base_url, | ||
| 16 | model => $args{model} // '', | ||
| 17 | api_key => $args{api_key}, | ||
| 18 | version => $args{version} // '2023-06-01', | ||
| 19 | max_tokens => $args{max_tokens} // 1024, | ||
| 20 | transport => $args{transport}, | ||
| 21 | stream_transport => $args{stream_transport}, | ||
| 22 | timeout => $args{timeout} // 60, | ||
| 23 | }, $class; | ||
| 24 | } | ||
| 25 | |||
| 26 | sub generate { | ||
| 27 | my ($self, $request) = @_; | ||
| 28 | praxo_error('MODEL_CONFIG', 'anthropic: API key is required') | ||
| 29 | unless defined $self->{api_key} && $self->{api_key} ne ''; | ||
| 30 | praxo_error('MODEL_CONFIG', 'anthropic: model is required') | ||
| 31 | unless $self->{model} ne ''; | ||
| 32 | my $payload = _payload($self, $request); | ||
| 33 | my $data = $self->{transport} | ||
| 34 | ? $self->{transport}->('/v1/messages', $payload) | ||
| 35 | : $self->_post('/v1/messages', $payload); | ||
| 36 | return _parse_response($data); | ||
| 37 | } | ||
| 38 | |||
| 39 | sub generate_stream { | ||
| 40 | my ($self, $request, $on_delta) = @_; | ||
| 41 | praxo_error('MODEL_CONFIG', 'anthropic: API key is required') | ||
| 42 | unless defined $self->{api_key} && $self->{api_key} ne ''; | ||
| 43 | praxo_error('MODEL_CONFIG', 'anthropic: model is required') | ||
| 44 | unless $self->{model} ne ''; | ||
| 45 | my $payload = _payload($self, $request, 1); | ||
| 46 | my $text = $self->{stream_transport} | ||
| 47 | ? $self->{stream_transport}->('/v1/messages', $payload) | ||
| 48 | : $self->_post_stream('/v1/messages', $payload); | ||
| 49 | praxo_error('PROVIDER_HTTP', 'stream transport must return SSE text') | ||
| 50 | if ref($text) || !defined $text; | ||
| 51 | return _parse_sse($text, $on_delta); | ||
| 52 | } | ||
| 53 | |||
| 54 | sub _payload { | ||
| 55 | my ($self, $request, $stream) = @_; | ||
| 56 | my ($system, $messages) = _build_messages($request->{messages}); | ||
| 57 | my %payload = ( | ||
| 58 | model => $self->{model}, | ||
| 59 | max_tokens => $self->{max_tokens}, | ||
| 60 | messages => $messages, | ||
| 61 | ); | ||
| 62 | $payload{system} = $system if $system ne ''; | ||
| 63 | my @tools = map { | ||
| 64 | { | ||
| 65 | name => $_->{name}, | ||
| 66 | description => $_->{description} // '', | ||
| 67 | input_schema => $_->{parameters} // { type => 'object', properties => {} }, | ||
| 68 | } | ||
| 69 | } @{ $request->{tools} // [] }; | ||
| 70 | if (@tools) { | ||
| 71 | $payload{tools} = \@tools; | ||
| 72 | my $choice = _tool_choice($request->{toolChoice}); | ||
| 73 | $payload{tool_choice} = $choice if $choice; | ||
| 74 | } | ||
| 75 | $payload{temperature} = $request->{temperature} | ||
| 76 | if defined $request->{temperature} && $request->{temperature} != 0; | ||
| 77 | $payload{stream} = Praxo::Json::true_value() if $stream; | ||
| 78 | return \%payload; | ||
| 79 | } | ||
| 80 | |||
| 81 | sub _build_messages { | ||
| 82 | my ($messages) = @_; | ||
| 83 | my @system; | ||
| 84 | my @out; | ||
| 85 | my @pending; | ||
| 86 | my $flush = sub { | ||
| 87 | return unless @pending; | ||
| 88 | push @out, { role => 'user', content => [@pending] }; | ||
| 89 | @pending = (); | ||
| 90 | }; | ||
| 91 | for my $message (@{ $messages // [] }) { | ||
| 92 | if ($message->{role} eq Praxo::Models::SYSTEM()) { | ||
| 93 | push @system, $message->{content} | ||
| 94 | if defined $message->{content} && $message->{content} ne ''; | ||
| 95 | next; | ||
| 96 | } | ||
| 97 | if ($message->{role} eq Praxo::Models::TOOL()) { | ||
| 98 | push @pending, { | ||
| 99 | type => 'tool_result', | ||
| 100 | tool_use_id => $message->{toolId} // '', | ||
| 101 | content => $message->{content} // '', | ||
| 102 | }; | ||
| 103 | next; | ||
| 104 | } | ||
| 105 | $flush->(); | ||
| 106 | my $content = _message_content($message); | ||
| 107 | push @out, { role => $message->{role}, content => $content } if @$content; | ||
| 108 | } | ||
| 109 | $flush->(); | ||
| 110 | return (join("\n\n", @system), \@out); | ||
| 111 | } | ||
| 112 | |||
| 113 | sub _message_content { | ||
| 114 | my ($message) = @_; | ||
| 115 | my @content; | ||
| 116 | push @content, { type => 'text', text => $message->{content} } | ||
| 117 | if defined $message->{content} && $message->{content} ne ''; | ||
| 118 | for my $block (@{ $message->{contentBlocks} // [] }) { | ||
| 119 | push @content, { type => 'text', text => $block->{text} } | ||
| 120 | if ($block->{type} // '') eq 'text' | ||
| 121 | && defined $block->{text} && $block->{text} ne ''; | ||
| 122 | } | ||
| 123 | for my $call (@{ $message->{toolCalls} // [] }) { | ||
| 124 | push @content, { | ||
| 125 | type => 'tool_use', | ||
| 126 | id => $call->{id} // '', | ||
| 127 | name => $call->{name} // '', | ||
| 128 | input => $call->{arguments} // {}, | ||
| 129 | }; | ||
| 130 | } | ||
| 131 | return \@content; | ||
| 132 | } | ||
| 133 | |||
| 134 | sub _tool_choice { | ||
| 135 | my ($choice) = @_; | ||
| 136 | return { type => 'auto' } if defined $choice && $choice eq 'auto'; | ||
| 137 | return { type => 'any' } if defined $choice && $choice eq 'required'; | ||
| 138 | return { type => 'none' } if defined $choice && $choice eq 'none'; | ||
| 139 | return undef; | ||
| 140 | } | ||
| 141 | |||
| 142 | sub _parse_sse { | ||
| 143 | my ($text, $on_delta) = @_; | ||
| 144 | my $content = ''; | ||
| 145 | my %calls; | ||
| 146 | my ($input_tokens, $output_tokens, $cached_tokens, $stop_reason, $stopped) = | ||
| 147 | (0, 0, 0, undef, 0); | ||
| 148 | for my $raw (split /\n/, $text) { | ||
| 149 | my $line = $raw; | ||
| 150 | $line =~ s/^\s+|\s+$//g; | ||
| 151 | next unless $line =~ /^data:\s*(.*)$/; | ||
| 152 | my $chunk = $1; | ||
| 153 | $chunk =~ s/^\s+|\s+$//g; | ||
| 154 | next if $chunk eq ''; | ||
| 155 | my $event = eval { Praxo::Json::parse($chunk) }; | ||
| 156 | praxo_error('MODEL_STREAM', 'anthropic: invalid stream chunk') | ||
| 157 | unless ref($event) eq 'HASH'; | ||
| 158 | my $type = $event->{type} // ''; | ||
| 159 | if ($type eq 'message_start') { | ||
| 160 | my $usage = $event->{message}{usage} // {}; | ||
| 161 | $input_tokens = $usage->{input_tokens} // 0; | ||
| 162 | $cached_tokens = $usage->{cache_read_input_tokens} // 0; | ||
| 163 | } elsif ($type eq 'content_block_start') { | ||
| 164 | my $index = $event->{index} // 0; | ||
| 165 | my $block = $event->{content_block} // {}; | ||
| 166 | if (($block->{type} // '') eq 'tool_use') { | ||
| 167 | $calls{$index} = { | ||
| 168 | id => $block->{id} // '', | ||
| 169 | name => $block->{name} // '', | ||
| 170 | arguments => '', | ||
| 171 | }; | ||
| 172 | } | ||
| 173 | } elsif ($type eq 'content_block_delta') { | ||
| 174 | my $index = $event->{index} // 0; | ||
| 175 | my $delta = $event->{delta} // {}; | ||
| 176 | my $delta_type = $delta->{type} // ''; | ||
| 177 | if ($delta_type eq 'text_delta') { | ||
| 178 | my $piece = $delta->{text} // ''; | ||
| 179 | if ($piece ne '') { | ||
| 180 | $content .= $piece; | ||
| 181 | $on_delta->($piece); | ||
| 182 | } | ||
| 183 | } elsif ($delta_type eq 'input_json_delta' && exists $calls{$index}) { | ||
| 184 | $calls{$index}{arguments} .= $delta->{partial_json} // ''; | ||
| 185 | } | ||
| 186 | } elsif ($type eq 'message_delta') { | ||
| 187 | $stop_reason = $event->{delta}{stop_reason} // $stop_reason; | ||
| 188 | $output_tokens = $event->{usage}{output_tokens} // $output_tokens; | ||
| 189 | } elsif ($type eq 'message_stop') { | ||
| 190 | $stopped = 1; | ||
| 191 | } elsif ($type eq 'error') { | ||
| 192 | praxo_error('MODEL_STREAM', 'anthropic: stream error'); | ||
| 193 | } | ||
| 194 | } | ||
| 195 | praxo_error('MODEL_STREAM', 'anthropic: stream ended before completion') | ||
| 196 | unless $stopped || defined $stop_reason; | ||
| 197 | my @tool_calls; | ||
| 198 | for my $index (sort { $a <=> $b } keys %calls) { | ||
| 199 | my $call = $calls{$index}; | ||
| 200 | next if $call->{name} eq ''; | ||
| 201 | my $arguments = {}; | ||
| 202 | if ($call->{arguments} ne '') { | ||
| 203 | my $parsed = eval { Praxo::Json::parse($call->{arguments}) }; | ||
| 204 | praxo_error('PROVIDER_JSON', 'anthropic: invalid tool arguments') | ||
| 205 | unless ref($parsed) eq 'HASH'; | ||
| 206 | $arguments = $parsed; | ||
| 207 | } | ||
| 208 | push @tool_calls, Praxo::Models::tool_call( | ||
| 209 | id => $call->{id}, | ||
| 210 | name => $call->{name}, | ||
| 211 | arguments => $arguments, | ||
| 212 | ); | ||
| 213 | } | ||
| 214 | return Praxo::Models::response( | ||
| 215 | message => Praxo::Models::message_assistant($content, \@tool_calls), | ||
| 216 | usage => Praxo::Models::usage( | ||
| 217 | input_tokens => $input_tokens, | ||
| 218 | output_tokens => $output_tokens, | ||
| 219 | cached_tokens => $cached_tokens, | ||
| 220 | ), | ||
| 221 | finish_reason => $stop_reason, | ||
| 222 | ); | ||
| 223 | } | ||
| 224 | |||
| 225 | sub _post_stream { | ||
| 226 | my ($self, $path, $payload) = @_; | ||
| 227 | my %headers = ( | ||
| 228 | 'content-type' => 'application/json', | ||
| 229 | 'accept' => 'text/event-stream', | ||
| 230 | 'x-api-key' => $self->{api_key}, | ||
| 231 | 'anthropic-version' => $self->{version}, | ||
| 232 | ); | ||
| 233 | my $http = HTTP::Tiny->new(timeout => $self->{timeout}); | ||
| 234 | my $response = $http->post( | ||
| 235 | $self->{base_url} . $path, | ||
| 236 | { | ||
| 237 | headers => \%headers, | ||
| 238 | content => Praxo::Json::stringify($payload), | ||
| 239 | }, | ||
| 240 | ); | ||
| 241 | praxo_error( | ||
| 242 | 'PROVIDER_HTTP', | ||
| 243 | 'provider returned HTTP ' . ($response->{status} // 0) . ': ' . ($response->{content} // ''), | ||
| 244 | ) unless $response->{success}; | ||
| 245 | return $response->{content}; | ||
| 246 | } | ||
| 247 | |||
| 248 | sub _parse_response { | ||
| 249 | my ($data) = @_; | ||
| 250 | praxo_error('MODEL_HTTP', 'anthropic: ' . ($data->{error}{message} // 'error')) | ||
| 251 | if ref($data->{error}) eq 'HASH'; | ||
| 252 | my $text = ''; | ||
| 253 | my @calls; | ||
| 254 | for my $block (@{ $data->{content} // [] }) { | ||
| 255 | if (($block->{type} // '') eq 'text') { | ||
| 256 | $text .= $block->{text} // ''; | ||
| 257 | } elsif (($block->{type} // '') eq 'tool_use') { | ||
| 258 | push @calls, Praxo::Models::tool_call( | ||
| 259 | id => $block->{id} // '', | ||
| 260 | name => $block->{name} // '', | ||
| 261 | arguments => $block->{input} // {}, | ||
| 262 | ); | ||
| 263 | } | ||
| 264 | } | ||
| 265 | my $usage = ref($data->{usage}) eq 'HASH' ? $data->{usage} : {}; | ||
| 266 | my $response = Praxo::Models::response( | ||
| 267 | message => Praxo::Models::message_assistant($text, \@calls), | ||
| 268 | usage => Praxo::Models::usage( | ||
| 269 | input_tokens => $usage->{input_tokens} // 0, | ||
| 270 | output_tokens => $usage->{output_tokens} // 0, | ||
| 271 | cached_tokens => $usage->{cache_read_input_tokens} // 0, | ||
| 272 | ), | ||
| 273 | finish_reason => $data->{stop_reason}, | ||
| 274 | ); | ||
| 275 | return $response; | ||
| 276 | } | ||
| 277 | |||
| 278 | sub _post { | ||
| 279 | my ($self, $path, $payload) = @_; | ||
| 280 | my %headers = ( | ||
| 281 | 'content-type' => 'application/json', | ||
| 282 | 'x-api-key' => $self->{api_key}, | ||
| 283 | 'anthropic-version' => $self->{version}, | ||
| 284 | ); | ||
| 285 | my $http = HTTP::Tiny->new(timeout => $self->{timeout}); | ||
| 286 | my $response = $http->post( | ||
| 287 | $self->{base_url} . $path, | ||
| 288 | { headers => \%headers, content => Praxo::Json::stringify($payload) }, | ||
| 289 | ); | ||
| 290 | praxo_error( | ||
| 291 | 'PROVIDER_HTTP', | ||
| 292 | 'provider returned HTTP ' . ($response->{status} // 0) . ': ' . ($response->{content} // ''), | ||
| 293 | ) unless $response->{success}; | ||
| 294 | return Praxo::Json::parse($response->{content}); | ||
| 295 | } | ||
| 296 | |||
| 297 | 1; |