| 1 | package Praxo::Adapters::OpenAICompatible; | ||
| 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} // ''; | ||
| 13 | $base_url =~ s{/$}{}; | ||
| 14 | return bless { | ||
| 15 | base_url => $base_url, | ||
| 16 | model => $args{model} // '', | ||
| 17 | api_key => $args{api_key}, | ||
| 18 | transport => $args{transport}, | ||
| 19 | stream_transport => $args{stream_transport}, | ||
| 20 | timeout => $args{timeout} // 60, | ||
| 21 | }, $class; | ||
| 22 | } | ||
| 23 | |||
| 24 | sub generate { | ||
| 25 | my ($self, $request) = @_; | ||
| 26 | my $payload = _payload($self->{model}, $request); | ||
| 27 | my $data = $self->{transport} | ||
| 28 | ? $self->{transport}->('/chat/completions', $payload) | ||
| 29 | : $self->_post('/chat/completions', $payload); | ||
| 30 | return _parse_response($data); | ||
| 31 | } | ||
| 32 | |||
| 33 | sub generate_stream { | ||
| 34 | my ($self, $request, $on_delta) = @_; | ||
| 35 | my $payload = _payload($self->{model}, $request); | ||
| 36 | $payload->{stream} = Praxo::Json::true_value(); | ||
| 37 | my $text = $self->{stream_transport} | ||
| 38 | ? $self->{stream_transport}->('/chat/completions', $payload) | ||
| 39 | : $self->_post_stream('/chat/completions', $payload); | ||
| 40 | praxo_error('PROVIDER_HTTP', 'stream transport must return SSE text') | ||
| 41 | if ref($text) || !defined $text; | ||
| 42 | return _parse_sse($text, $on_delta); | ||
| 43 | } | ||
| 44 | |||
| 45 | sub _payload { | ||
| 46 | my ($model, $request) = @_; | ||
| 47 | my @messages = map { _message_payload($_) } @{ $request->{messages} // [] }; | ||
| 48 | my @tools = map { | ||
| 49 | { | ||
| 50 | type => 'function', | ||
| 51 | function => { | ||
| 52 | name => $_->{name}, | ||
| 53 | description => $_->{description} // '', | ||
| 54 | parameters => $_->{parameters} // { type => 'object' }, | ||
| 55 | }, | ||
| 56 | } | ||
| 57 | } @{ $request->{tools} // [] }; | ||
| 58 | my %payload = ( | ||
| 59 | model => $model, | ||
| 60 | messages => \@messages, | ||
| 61 | ); | ||
| 62 | $payload{tools} = \@tools if @tools; | ||
| 63 | $payload{tool_choice} = $request->{toolChoice} if defined $request->{toolChoice}; | ||
| 64 | $payload{response_format} = $request->{responseFormat} if defined $request->{responseFormat}; | ||
| 65 | $payload{temperature} = $request->{temperature} if defined $request->{temperature}; | ||
| 66 | return \%payload; | ||
| 67 | } | ||
| 68 | |||
| 69 | sub _message_payload { | ||
| 70 | my ($message) = @_; | ||
| 71 | my $content = $message->{content}; | ||
| 72 | if ((!defined $content || $content eq '') && ref($message->{contentBlocks}) eq 'ARRAY') { | ||
| 73 | $content = join '', map { $_->{text} // '' } | ||
| 74 | grep { ($_->{type} // '') eq 'text' } @{ $message->{contentBlocks} }; | ||
| 75 | } | ||
| 76 | my %out = (role => $message->{role}, content => $content); | ||
| 77 | if ($message->{role} eq Praxo::Models::ASSISTANT() | ||
| 78 | && ref($message->{toolCalls}) eq 'ARRAY' && @{ $message->{toolCalls} }) { | ||
| 79 | $out{tool_calls} = [ | ||
| 80 | map { | ||
| 81 | { | ||
| 82 | id => $_->{id}, | ||
| 83 | type => 'function', | ||
| 84 | function => { | ||
| 85 | name => $_->{name}, | ||
| 86 | arguments => Praxo::Json::stringify($_->{arguments} // {}), | ||
| 87 | }, | ||
| 88 | } | ||
| 89 | } @{ $message->{toolCalls} } | ||
| 90 | ]; | ||
| 91 | } | ||
| 92 | if ($message->{role} eq Praxo::Models::TOOL() | ||
| 93 | && defined $message->{toolId} && $message->{toolId} ne '') { | ||
| 94 | $out{tool_call_id} = $message->{toolId}; | ||
| 95 | } | ||
| 96 | return \%out; | ||
| 97 | } | ||
| 98 | |||
| 99 | sub _parse_response { | ||
| 100 | my ($data) = @_; | ||
| 101 | my $choice = ref($data->{choices}) eq 'ARRAY' ? $data->{choices}[0] : undef; | ||
| 102 | $choice = {} unless ref($choice) eq 'HASH'; | ||
| 103 | my $message = ref($choice->{message}) eq 'HASH' ? $choice->{message} : {}; | ||
| 104 | my @tool_calls = map { | ||
| 105 | my $function = ref($_->{function}) eq 'HASH' ? $_->{function} : {}; | ||
| 106 | my $arguments = $function->{arguments}; | ||
| 107 | if (defined $arguments && !ref($arguments) && $arguments ne '') { | ||
| 108 | $arguments = Praxo::Json::parse($arguments); | ||
| 109 | } | ||
| 110 | Praxo::Models::tool_call( | ||
| 111 | id => $_->{id} // '', | ||
| 112 | name => $function->{name} // '', | ||
| 113 | arguments => ref($arguments) eq 'HASH' ? $arguments : {}, | ||
| 114 | ) | ||
| 115 | } grep { ref($_) eq 'HASH' } @{ ref($message->{tool_calls}) eq 'ARRAY' ? $message->{tool_calls} : [] }; | ||
| 116 | my $usage = ref($data->{usage}) eq 'HASH' ? $data->{usage} : {}; | ||
| 117 | return Praxo::Models::response( | ||
| 118 | message => Praxo::Models::message_assistant($message->{content}, \@tool_calls), | ||
| 119 | usage => Praxo::Models::usage( | ||
| 120 | input_tokens => $usage->{prompt_tokens} // 0, | ||
| 121 | output_tokens => $usage->{completion_tokens} // 0, | ||
| 122 | ), | ||
| 123 | finish_reason => $choice->{finish_reason}, | ||
| 124 | ); | ||
| 125 | } | ||
| 126 | |||
| 127 | sub _parse_sse { | ||
| 128 | my ($text, $on_delta) = @_; | ||
| 129 | my $content = ''; | ||
| 130 | my %calls; | ||
| 131 | my ($input_tokens, $output_tokens, $finish_reason, $done) = (0, 0, undef, 0); | ||
| 132 | for my $raw (split /\n/, $text) { | ||
| 133 | my $line = $raw; | ||
| 134 | $line =~ s/^\s+|\s+$//g; | ||
| 135 | next unless $line =~ /^data:\s*(.*)$/; | ||
| 136 | my $chunk = $1; | ||
| 137 | $chunk =~ s/^\s+|\s+$//g; | ||
| 138 | next if $chunk eq ''; | ||
| 139 | if ($chunk eq '[DONE]') { | ||
| 140 | $done = 1; | ||
| 141 | last; | ||
| 142 | } | ||
| 143 | my $event = eval { Praxo::Json::parse($chunk) }; | ||
| 144 | praxo_error('MODEL_STREAM', 'invalid SSE packet') | ||
| 145 | unless ref($event) eq 'HASH'; | ||
| 146 | if (ref($event->{usage}) eq 'HASH') { | ||
| 147 | $input_tokens = $event->{usage}{prompt_tokens} // 0; | ||
| 148 | $output_tokens = $event->{usage}{completion_tokens} // 0; | ||
| 149 | } | ||
| 150 | my $choices = ref($event->{choices}) eq 'ARRAY' ? $event->{choices} : []; | ||
| 151 | for my $choice (@$choices) { | ||
| 152 | next unless ref($choice) eq 'HASH'; | ||
| 153 | my $delta = ref($choice->{delta}) eq 'HASH' ? $choice->{delta} : {}; | ||
| 154 | my $piece = $delta->{content}; | ||
| 155 | if (defined $piece && !ref($piece) && $piece ne '') { | ||
| 156 | $content .= $piece; | ||
| 157 | $on_delta->($piece); | ||
| 158 | } | ||
| 159 | my $items = ref($delta->{tool_calls}) eq 'ARRAY' ? $delta->{tool_calls} : []; | ||
| 160 | for my $item (@$items) { | ||
| 161 | next unless ref($item) eq 'HASH'; | ||
| 162 | my $index = defined $item->{index} ? $item->{index} : scalar(keys %calls); | ||
| 163 | my $slot = $calls{$index} //= { id => '', name => '', arguments => '' }; | ||
| 164 | $slot->{id} .= $item->{id} | ||
| 165 | if defined $item->{id} && !ref($item->{id}); | ||
| 166 | my $function = ref($item->{function}) eq 'HASH' ? $item->{function} : {}; | ||
| 167 | $slot->{name} .= $function->{name} | ||
| 168 | if defined $function->{name} && !ref($function->{name}); | ||
| 169 | $slot->{arguments} .= $function->{arguments} | ||
| 170 | if defined $function->{arguments} && !ref($function->{arguments}); | ||
| 171 | } | ||
| 172 | if (exists $choice->{finish_reason} && defined $choice->{finish_reason}) { | ||
| 173 | $finish_reason = $choice->{finish_reason}; | ||
| 174 | $done = 1; | ||
| 175 | } | ||
| 176 | } | ||
| 177 | } | ||
| 178 | praxo_error('MODEL_STREAM', 'stream ended before completion') unless $done; | ||
| 179 | my @tool_calls; | ||
| 180 | for my $index (sort { $a <=> $b } keys %calls) { | ||
| 181 | my $slot = $calls{$index}; | ||
| 182 | next if $slot->{name} eq ''; | ||
| 183 | my $arguments = {}; | ||
| 184 | if ($slot->{arguments} ne '') { | ||
| 185 | my $parsed = eval { Praxo::Json::parse($slot->{arguments}) }; | ||
| 186 | praxo_error('PROVIDER_JSON', 'provider returned invalid tool arguments') | ||
| 187 | unless ref($parsed) eq 'HASH'; | ||
| 188 | $arguments = $parsed; | ||
| 189 | } | ||
| 190 | push @tool_calls, Praxo::Models::tool_call( | ||
| 191 | id => $slot->{id}, | ||
| 192 | name => $slot->{name}, | ||
| 193 | arguments => $arguments, | ||
| 194 | ); | ||
| 195 | } | ||
| 196 | return Praxo::Models::response( | ||
| 197 | message => Praxo::Models::message_assistant($content, \@tool_calls), | ||
| 198 | usage => Praxo::Models::usage( | ||
| 199 | input_tokens => $input_tokens, | ||
| 200 | output_tokens => $output_tokens, | ||
| 201 | ), | ||
| 202 | finish_reason => $finish_reason, | ||
| 203 | ); | ||
| 204 | } | ||
| 205 | |||
| 206 | sub _post_stream { | ||
| 207 | my ($self, $path, $payload) = @_; | ||
| 208 | praxo_error('PROVIDER_HTTP', 'provider base URL is required') | ||
| 209 | unless $self->{base_url} ne ''; | ||
| 210 | my %headers = ( | ||
| 211 | 'content-type' => 'application/json', | ||
| 212 | 'accept' => 'text/event-stream', | ||
| 213 | ); | ||
| 214 | $headers{authorization} = 'Bearer ' . $self->{api_key} | ||
| 215 | if defined $self->{api_key} && $self->{api_key} ne ''; | ||
| 216 | my $http = HTTP::Tiny->new(timeout => $self->{timeout}); | ||
| 217 | my $response = $http->post( | ||
| 218 | $self->{base_url} . $path, | ||
| 219 | { | ||
| 220 | headers => \%headers, | ||
| 221 | content => Praxo::Json::stringify($payload), | ||
| 222 | }, | ||
| 223 | ); | ||
| 224 | praxo_error( | ||
| 225 | 'PROVIDER_HTTP', | ||
| 226 | 'provider returned HTTP ' . ($response->{status} // 0) . ': ' . ($response->{content} // ''), | ||
| 227 | ) unless $response->{success}; | ||
| 228 | return $response->{content}; | ||
| 229 | } | ||
| 230 | |||
| 231 | sub _post { | ||
| 232 | my ($self, $path, $payload) = @_; | ||
| 233 | praxo_error('PROVIDER_HTTP', 'provider base URL is required') | ||
| 234 | unless $self->{base_url} ne ''; | ||
| 235 | my %headers = ('content-type' => 'application/json'); | ||
| 236 | $headers{authorization} = 'Bearer ' . $self->{api_key} | ||
| 237 | if defined $self->{api_key} && $self->{api_key} ne ''; | ||
| 238 | my $http = HTTP::Tiny->new(timeout => $self->{timeout}); | ||
| 239 | my $response = $http->post( | ||
| 240 | $self->{base_url} . $path, | ||
| 241 | { | ||
| 242 | headers => \%headers, | ||
| 243 | content => Praxo::Json::stringify($payload), | ||
| 244 | }, | ||
| 245 | ); | ||
| 246 | praxo_error( | ||
| 247 | 'PROVIDER_HTTP', | ||
| 248 | 'provider returned HTTP ' . ($response->{status} // 0) . ': ' . ($response->{content} // ''), | ||
| 249 | ) unless $response->{success}; | ||
| 250 | return Praxo::Json::parse($response->{content}); | ||
| 251 | } | ||
| 252 | |||
| 253 | 1; |