blib/lib/Langertha/Knarr/Handler/Passthrough.pm

filter: Statementstmt 48.7% 113 / 232 Branchbran 15.8% 19 / 120 Conditioncond 15.2% 13 / 85 MC/DCmcdc 2.1% 1 / 47 Subroutinesub 62.5% 20 / 32 Podpod 50.0% 3 / 6 totaltotal 32.3% 169 / 522 CC 98 SCAR 59.9
CC
98
Cov
33%
__ANON__
1332.0
_parse_response
182.0
__ANON__
72.0
CRAP 398.9
« blib/lib/Langertha/Knarr/PSGI.pm ↑ Summary blib/lib/Langertha/Knarr/Handler/A2AClient.pm »
1 package Langertha::Knarr::Handler::Passthrough;
2 # ABSTRACT: Knarr handler that forwards requests verbatim to an upstream HTTP API
3 34 our $VERSION = '1.103';
4 34 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 34 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 34 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 34 ▶use HTTP::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 34 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 34 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 34 ▶use Langertha::Knarr::Stream;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 34 ▶use Langertha::Knarr::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 34 ▶use Langertha::ToolCall;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 34 with 'Langertha::Knarr::Handler', 'Langertha::Knarr::Role::UpstreamHTTP';
15  
16  
17 # Forwards the original wire-format request to a real upstream API. The
18 # protocol's parser already turned the body into a Knarr::Request, so we
19 # rebuild a body from $request->raw and re-POST it. Headers (especially
20 # Authorization) are passed through if the caller registers them with the
21 # session via $request->extra->{forward_headers}.
22  
23 # Per-protocol upstream URLs. Keys are protocol names ("openai", "anthropic",
24 # "ollama"). Each value is the base URL of the upstream provider — e.g.
25 # https://api.openai.com or https://api.anthropic.com. Knarr appends the
26 # original request path to this base URL.
27 34 has upstreams => (
28 is => 'ro',
29 isa => 'HashRef[Str]',
30 required => 1,
31 );
32  
33 # Optional: a default Authorization header value to inject if the client
34 # didn't send one. If undef, the client must supply its own.
35 has default_auth => (
36 is => 'ro',
37 isa => 'Maybe[Str]',
38 9 ▶ default => sub { undef },
Subroutine __ANON__: called CC=1 SCAR=0.0
39 34 );
40  
41 34 has model_id => ( is => 'ro', isa => 'Str', default => 'passthrough' );
42  
43 9 ▶has _json => ( is => 'ro', default => sub { JSON::MaybeXS->new( utf8 => 1, canonical => 1 ) } );
Subroutine __ANON__: called CC=1 SCAR=0.0
44  
45 # Per-protocol path the request should hit upstream. We use the protocol
46 # defaults; this lookup table can be extended.
47 34 my %DEFAULT_PATH = (
48 openai => '/v1/chat/completions',
49 anthropic => '/v1/messages',
50 ollama => '/api/chat',
51 );
52  
53 # Other chat paths a protocol has upstream, reached as the client asked:
54 # Ollama's /api/generate takes a prompt, not messages, and answers in its
55 # own shape, so its bytes must reach the upstream's /api/generate (k46).
56 34 my %OTHER_PATHS = (
57 ollama => { '/api/generate' => 1 },
58 );
59  
60 # $client_path: the path the client asked for; used when it is one of the
61 # protocol's chat paths, else the protocol's default chat path.
62 9 ▶sub _upstream_url {
Subroutine _upstream_url: called CC=5 SCAR=17.8
63 9 my ($self, $protocol_name, $client_path) = @_;
64 9 ▶ my $base = $self->upstreams->{$protocol_name}
Branch: 1 branch
BranchTrueFalseTotal
my $base = $self->upstreams->{$protocol_name} or die "Passthrough: no upstream configured for protocol '${protocol_name}'\n" 9 0 9
65 or die "Passthrough: no upstream configured for protocol '$protocol_name'\n";
66 9 $base =~ s{/+$}{};
67 9 ▶ my $path = $DEFAULT_PATH{$protocol_name}
Branch: 1 branch
BranchTrueFalseTotal
my $path = $DEFAULT_PATH{$protocol_name} or die "Passthrough: no default path for protocol '${protocol_name}'\n" 9 0 9
68 or die "Passthrough: no default path for protocol '$protocol_name'\n";
69 $path = $client_path
70 9 ▶ if defined $client_path && $OTHER_PATHS{$protocol_name}{$client_path};
Branch: 1 branch
BranchTrueFalseTotal
if defined $client_path and $OTHER_PATHS{$protocol_name}{$client_path} 0 9 9
Condition33%1/3
defined $client_path and $OTHER_PATHS{$protocol_name}{$client_path}
!ll&&!rl&&r
900
MC/DC0%0/2
defined $client_path and $OTHER_PATHS{$protocol_name}{$client_path}
defined $client_path $OTHER_PATHS{$protocol_name}{$client_path}
Truth table33%1/3
A and B
A= defined $client_pathB= $OTHER_PATHS{$protocol_name}{$client_path}
ABresult
0X0
100
111
71 9 return "$base$path";
72 }
73  
74 # Whether a request in this protocol has anywhere to go: an upstream URL
75 # and a known chat path -- exactly what _upstream_url needs (k41).
76 0 ▶sub serves_protocol {
Subroutine serves_protocol: not called CC=4 SCAR=30.0
Pod documented
77 0 my ($self, $protocol_name) = @_;
78 0 ▶ return 0 unless defined $protocol_name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $protocol_name 0 0 0
79 0 ▶ return $self->upstreams->{$protocol_name} && $DEFAULT_PATH{$protocol_name} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->upstreams->{$protocol_name} && $DEFAULT_PATH{$protocol_name} ? : 0 0 0
Condition0%0/3
$self->upstreams->{$protocol_name} and $DEFAULT_PATH{$protocol_name}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->upstreams->{$protocol_name} and $DEFAULT_PATH{$protocol_name}
$self->upstreams->{$protocol_name} $DEFAULT_PATH{$protocol_name}
Truth table0%0/3
A and B
A= $self->upstreams->{$protocol_name}B= $DEFAULT_PATH{$protocol_name}
ABresult
0X0
100
111
80 }
81  
82 # Whether $url lives on this protocol's upstream (k47).
83 0 ▶sub is_upstream_for {
Subroutine is_upstream_for: not called CC=4 SCAR=30.0
Pod documented
84 0 my ($self, $protocol_name, $url) = @_;
85 0 ▶ return 0 unless defined $protocol_name && defined $url;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $protocol_name and defined $url 0 0 0
Condition0%0/3
defined $protocol_name and defined $url
!ll&&!rl&&r
000
MC/DC0%0/2
defined $protocol_name and defined $url
defined $protocol_name defined $url
Truth table0%0/3
A and B
A= defined $protocol_nameB= defined $url
ABresult
0X0
100
111
86 0 ▶ my $base = $self->upstreams->{$protocol_name} or return 0;
Branch: 1 branch
BranchTrueFalseTotal
my $base = $self->upstreams->{$protocol_name} or return 0 0 0 0
87 0 return $self->same_upstream( $base, $url );
88 }
89  
90  
91 # Same scheme, host, port and path (k54): a gateway serves several
92 # providers under paths of one host. An engine's base URL carries the API
93 # version the passthrough base leaves out (https://api.openai.com/v1 vs
94 # https://api.openai.com), so a trailing /v1 is not compared. URI's
95 # canonical form takes care of host case and default ports.
96 60 ▶sub same_upstream {
Subroutine same_upstream: called CC=9 SCAR=24.8
Pod documented
97 60 my ($self, $base, $url) = @_;
98 60 ▶ return 0 unless defined $base && defined $url;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $base and defined $url 0 60 60
Condition33%1/3
defined $base and defined $url
!ll&&!rl&&r
0060
MC/DC0%0/2
defined $base and defined $url
defined $base defined $url
Truth table33%1/3
A and B
A= defined $baseB= defined $url
ABresult
0X0
100
111
99 60 my ($upstream, $other) = map { URI->new($_)->canonical } $base, $url;
100 60 ▶ return 0 unless $upstream->can('host') && $other->can('host');
Branch: 1 branch
BranchTrueFalseTotal
unless $upstream->can("host") and $other->can("host") 0 60 60
Condition33%1/3
$upstream->can("host") and $other->can("host")
!ll&&!rl&&r
0060
MC/DC0%0/2
$upstream->can("host") and $other->can("host")
$upstream->can("host") $other->can("host")
Truth table33%1/3
A and B
A= $upstream->can("host")B= $other->can("host")
ABresult
0X0
100
111
101 60 ▶ return $upstream->scheme eq $other->scheme && $upstream->host eq $other->host
Branch: 1 branch
BranchTrueFalseTotal
$upstream->scheme eq $other->scheme && $upstream->host eq $other->host && $upstream->port == $other->port && $self->_upstream_path($upstream) eq $self->_upstream_path($other) ? : 15 45 60
Condition66%6/9
$upstream->scheme eq $other->scheme and $upstream->host eq $other->host and $upstream->port == $other->port and $self->_upstream_path($upstream) eq $self->_upstream_path($other)
!ll&&!rl&&r
45015
$upstream->scheme eq $other->scheme and $upstream->host eq $other->host and $upstream->port == $other->port
!ll&&!rl&&r
45015
$upstream->scheme eq $other->scheme and $upstream->host eq $other->host
!ll&&!rl&&r
04515
MC/DC25%1/4
$upstream->scheme eq $other->scheme and $upstream->host eq $other->host and $upstream->port == $other->port and $self->_upstream_path($upstream) eq $self->_upstream_path($other)
$upstream->scheme eq $other->scheme $upstream->host eq $other->host $upstream->port == $other->port $self->_upstream_path($upstream) eq $self->_upstream_path($other)
Truth table40%2/5
A and B and C and D
A= $upstream->scheme eq $other->schemeB= $upstream->host eq $other->hostC= $upstream->port == $other->portD= $self->_upstream_path($upstream) eq $self->_upstream_path($other)
ABCDresult
0XXX0
10XX0
110X0
11100
11111
102 && $upstream->port == $other->port
103 && $self->_upstream_path($upstream) eq $self->_upstream_path($other) ? 1 : 0;
104 }
105  
106 30 ▶sub _upstream_path {
Subroutine _upstream_path: called CC=1 SCAR=0.0
107 30 my ($self, $uri) = @_;
108 30 ( my $path = $uri->path ) =~ s{/+\z}{};
109 30 $path =~ s{/v1\z}{};
110 30 return $path;
111 }
112  
113  
114  
115 # An Ollama /api/generate request: its upstream answer carries the text on
116 # response, not message.content, and no tool calls (k48).
117 9 ▶sub _is_ollama_generate {
Subroutine _is_ollama_generate: called CC=4 SCAR=15.2
118 9 my ($self, $request) = @_;
119 return $request->protocol eq 'ollama'
120 9 ▶ && ( $request->extra->{path} // '' ) eq '/api/generate' ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$request->protocol eq 'ollama' && ($request->extra->{'path'} // '') eq '/api/generate' ? : 0 9 9
Condition60%3/5
$request->protocol eq "ollama" and ($request->extra->{"path"} // "") eq "/api/generate"
!ll&&!rl&&r
630
$request->extra->{"path"} // ""
l!l
03
MC/DC0%0/2
$request->protocol eq "ollama" and ($request->extra->{"path"} // "") eq "/api/generate"
$request->protocol eq "ollama" $request->extra->{"path"}
Truth table66%2/3
A and B
A= $request->protocol eq "ollama"B= $request->extra->{"path"}
ABresult
0X0
100
111
121 }
122  
123 9 ▶sub _build_upstream_request {
Subroutine _build_upstream_request: called CC=7 SCAR=21.5
124 9 my ($self, $request, $force_stream) = @_;
125 9 ▶ my $body = { %{ $request->raw || {} } };
Condition50%1/2
$request->raw || {}
l!l
90
MC/DC0%0/1
$request->raw || {}
$request->raw
Truth table50%1/2
A
A= $request->raw
Aresult
11
00
126 9 ▶ $body->{stream} = $force_stream ? JSON::MaybeXS::true() : JSON::MaybeXS::false()
Branch: 2 branches
BranchTrueFalseTotal
if defined $force_stream 9 0 9
$force_stream ? : 9 0 9
127 if defined $force_stream;
128 # The client's path, where the protocol's parser recorded it: an Ollama
129 # /api/generate goes to the upstream's /api/generate (k48).
130 9 my $url = $self->_upstream_url( $request->protocol, $request->extra->{path} );
131 9 my $http_req = HTTP::Request->new( POST => $url );
132 9 $http_req->header( 'Content-Type' => 'application/json' );
133 # Forward client auth headers (captured by protocol parsers), each line
134 # added, not set: a header sent twice reaches the upstream twice, in its
135 # order (k60).
136 9 $http_req->push_header(@$_) for $request->forward_header_pairs;
137 9 ▶ if ( my $auth = $self->default_auth ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $auth = $self->default_auth) 0 9 9
138 0 ▶ $http_req->header( Authorization => $auth ) unless $http_req->header('Authorization');
Branch: 1 branch
BranchTrueFalseTotal
unless $http_req->header("Authorization") 0 0 0
139 }
140 9 $http_req->content( $self->_json->encode($body) );
141 9 return $http_req;
142 }
143  
144 # Read an upstream response body for the protocol it came from: the
145 # assistant text, the tool calls as Langertha::ToolCall objects (through
146 # core's canonical inbound door, the same one the streaming path uses) and
147 # the terminal reason verbatim -- the client-side protocol maps it (k21).
148 # $generate: the body is an Ollama /api/generate answer, the text on
149 # response instead of message.content (k48).
150 0 ▶sub _parse_response {
Subroutine _parse_response: not called CC=13 SCAR=52.0
151 0 my ($self, $protocol_name, $resp_body, $generate) = @_;
152 0 my %parsed = ( content => '', tool_calls => [], finish_reason => undef );
153 0 my $data = eval { $self->_json->decode($resp_body) };
154 0 ▶ return %parsed unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 0 0 0
155 0 ▶ if ( $protocol_name eq 'openai' ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($protocol_name eq 'openai') { } 0 0 0
elsif ($protocol_name eq 'anthropic') { } 0 0 0
elsif ($protocol_name eq 'ollama') { } 0 0 0
156 0 ▶ $parsed{content} = $data->{choices}[0]{message}{content} // '';
Condition0%0/2
$data->{"choices"}[0]{"message"}{"content"} // ""
l!l
00
MC/DC0%0/1
$data->{"choices"}[0]{"message"}{"content"} // ""
$data->{"choices"}[0]{"message"}{"content"}
Truth table0%0/2
A
A= $data->{"choices"}[0]{"message"}{"content"}
Aresult
11
00
157 0 $parsed{finish_reason} = $data->{choices}[0]{finish_reason};
158 }
159 elsif ( $protocol_name eq 'anthropic' ) {
160 0 ▶ for my $b ( @{ $data->{content} || [] } ) {
Condition0%0/2
$data->{'content'} || []
l!l
00
MC/DC0%0/1
$data->{'content'} || []
$data->{'content'}
Truth table0%0/2
A
A= $data->{'content'}
Aresult
11
00
161 0 ▶ $parsed{content} .= $b->{text} // '' if ($b->{type} // '') eq 'text';
Branch: 1 branch
BranchTrueFalseTotal
if ($b->{"type"} // "") eq "text" 0 0 0
Condition0%0/4
$b->{"type"} // ""
l!l
00
$b->{"text"} // ""
l!l
00
MC/DC0%0/1
$b->{"type"} // ""
$b->{"type"}
MC/DC0%0/1
$b->{"text"} // ""
$b->{"text"}
Truth table0%0/2
A
A= $b->{"type"}
Aresult
11
00
Truth table0%0/2
A
A= $b->{"text"}
Aresult
11
00
162 }
163 0 $parsed{finish_reason} = $data->{stop_reason};
164 }
165 elsif ( $protocol_name eq 'ollama' ) {
166 0 ▶ $parsed{content} = ( $generate ? $data->{response} : $data->{message}{content} ) // '';
Branch: 1 branch
BranchTrueFalseTotal
$generate ? : 0 0 0
Condition0%0/2
($generate ? $data->{"response"} : $data->{"message"}{"content"}) // ""
l!l
00
MC/DC0%0/1
($generate ? $data->{"response"} : $data->{"message"}{"content"}) // ""
($generate ? $data->{"response"} : $data->{"message"}{"content"})
Truth table0%0/2
A
A= ($generate ? $data->{"response"} : $data->{"message"}{"content"})
Aresult
11
00
167 0 $parsed{finish_reason} = $data->{done_reason};
168 }
169 else {
170 0 return %parsed;
171 }
172 0 $parsed{tool_calls} = [ Langertha::ToolCall->extract( $protocol_name, $data ) ];
173 0 return %parsed;
174 }
175  
176 0 ▶async sub handle_chat_f {
Subroutine handle_chat_f: not called CC=3 SCAR=24.8
Pod undocumented
177 0 my ($self, $session, $request) = @_;
178 0 my $http_req = $self->_build_upstream_request( $request, 0 );
179 0 my $resp = await $self->_upstream_request_f( request => $http_req );
180 0 ▶ die "Passthrough upstream failed: " . $resp->status_line . "\n" unless $resp->is_success;
Branch: 1 branch
BranchTrueFalseTotal
unless $resp->is_success 0 0 0
181 0 ▶ return Langertha::Knarr::Response->new(
Condition0%0/3
$request->model // $self->model_id
l!l&&r!l&&!r
000
MC/DC0%0/2
$request->model // $self->model_id
$request->model $self->model_id
Truth table0%0/3
A // B
A= $request->modelB= $self->model_id
ABresult
1X1
011
000
182 $self->_parse_response( $request->protocol, $resp->decoded_content,
183 $self->_is_ollama_generate($request) ),
184 model => $request->model // $self->model_id,
185 );
186 34 }
187  
188 9 ▶async sub handle_stream_f {
Subroutine handle_stream_f: called CC=1 SCAR=4.0
Pod undocumented
189 9 my ($self, $session, $request) = @_;
190 9 my $http_req = $self->_build_upstream_request( $request, 1 );
191  
192 9 my @queue;
193 my $pending;
194 9 my $finished = 0;
195 9 my @error;
196 9 my $buffer = '';
197  
198 0 ▶ my $deliver = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
199 0 my ($v) = @_;
200 0 ▶ if ( $pending ) { my $p = $pending; $pending = undef; $p->done($v) }
Branch: 1 branch
BranchTrueFalseTotal
if ($pending) { } 0 0 0
201 0 else { push @queue, $v }
202 9 };
203  
204 # Streaming request: hand the body chunks straight back as deltas. The
205 # upstream already speaks the same wire format the client requested, so
206 # we forward bytes 1:1 by extracting just the text content from each
207 # protocol-native chunk. The Knarr core then re-frames them via the
208 # client-side protocol's format_stream_chunk — keeping symmetry even
209 # when client and upstream use the same protocol.
210 my $stream = Langertha::Knarr::Stream->new(
211 9 ▶ source => sub {
Subroutine __ANON__: called CC=4 SCAR=17.9
212 0 ▶ if ( @queue ) { return Future->done( shift @queue ) }
Branch: 1 branch
BranchTrueFalseTotal
if (@queue) 0 9 9
213 0 ▶ if ( $finished ) { return $error[0] ? Future->fail(@error) : Future->done(undef) }
Branch: 2 branches
BranchTrueFalseTotal
if ($finished) 0 9 9
$error[0] ? : 0 0 0
214 9 $pending = Future->new;
215 9 return $pending;
216 },
217 9 );
218  
219 9 my $proto_name = $request->protocol;
220 9 my $generate = $self->_is_ollama_generate($request);
221 # The upstream's terminal reason, verbatim; the client-side protocol maps
222 # it when it closes the stream (k18).
223 0 ▶ my $note_finish = sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
224 0 my ($reason) = @_;
225 0 ▶ $stream->finish_reason($reason) if defined $reason && length $reason;
Branch: 1 branch
BranchTrueFalseTotal
if defined $reason and length $reason 0 0 0
Condition0%0/3
defined $reason and length $reason
!ll&&!rl&&r
000
MC/DC0%0/2
defined $reason and length $reason
defined $reason length $reason
Truth table0%0/3
A and B
A= defined $reasonB= length $reason
ABresult
0X0
100
111
226 9 };
227 # The upstream's tool calls, assembled into complete Langertha::ToolCall
228 # objects: OpenAI delta.tool_calls fragments per index until the stream
229 # ends, Anthropic tool_use blocks with their input_json_delta until
230 # content_block_stop, Ollama message.tool_calls whole. The client-side
231 # protocol frames them when it closes the stream (k19).
232 9 my %openai_calls;
233 my %anthropic_blocks;
234 0 ▶ my $note_calls = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
235 0 my @calls = @_;
236 0 ▶ $stream->tool_calls( [ @{ $stream->tool_calls }, @calls ] ) if @calls;
Branch: 1 branch
BranchTrueFalseTotal
if @calls 0 0 0
237 9 };
238 0 ▶ my $finish_openai_calls = sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
239 0 ▶ return unless %openai_calls;
Branch: 1 branch
BranchTrueFalseTotal
unless %openai_calls 0 0 0
240 0 my @raw = map { $openai_calls{$_} } sort { $a <=> $b } keys %openai_calls;
241 0 %openai_calls = ();
242 0 $note_calls->( Langertha::ToolCall->extract( 'openai',
243 { choices => [ { message => { tool_calls => \@raw } } ] } ) );
244 9 };
245 0 ▶ my $extract_chunk = sub {
Subroutine __ANON__: not called CC=36 SCAR=71.9
246 0 my ($line) = @_;
247 0 ▶ if ( $proto_name eq 'openai' || $proto_name eq 'anthropic' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($proto_name eq "openai" or $proto_name eq "anthropic") 0 0 0
Condition0%0/3
$proto_name eq "openai" or $proto_name eq "anthropic"
l!l&&r!l&&!r
000
MC/DC0%0/2
$proto_name eq "openai" or $proto_name eq "anthropic"
$proto_name eq "openai" $proto_name eq "anthropic"
Truth table0%0/3
A or B
A= $proto_name eq "openai"B= $proto_name eq "anthropic"
ABresult
1X1
011
000
248 0 ▶ return undef unless $line =~ /^data:\s*(.+)$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /^data:\s*(.+)$/ 0 0 0
249 0 my $payload = $1;
250 0 ▶ return undef if $payload eq '[DONE]';
Branch: 1 branch
BranchTrueFalseTotal
if $payload eq "[DONE]" 0 0 0
251 0 my $d = eval { $self->_json->decode($payload) };
252 0 ▶ return undef unless ref $d eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $d eq "HASH" 0 0 0
253 0 ▶ if ( $proto_name eq 'openai' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($proto_name eq 'openai') { } 0 0 0
254 0 $note_finish->( $d->{choices}[0]{finish_reason} );
255 0 my $frags = $d->{choices}[0]{delta}{tool_calls};
256 0 ▶ for my $frag ( ref $frags eq 'ARRAY' ? @$frags : () ) {
Branch: 1 branch
BranchTrueFalseTotal
ref $frags eq 'ARRAY' ? : 0 0 0
257 0 ▶ next unless ref $frag eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $frag eq "HASH" 0 0 0
258 0 ▶ my $call = $openai_calls{ $frag->{index} // 0 } //=
Condition0%0/4
$openai_calls{$frag->{"index"} // 0} //= {"id", "", "type", "function", "function", {"name", "", "arguments", ""}}
l!l
00
$frag->{"index"} // 0
l!l
00
MC/DC0%0/1
$openai_calls{$frag->{"index"} // 0} //= {"id", "", "type", "function", "function", {"name", "", "arguments", ""}}
$openai_calls{$frag->{"index"} // 0}
MC/DC0%0/1
$frag->{"index"} // 0
$frag->{"index"}
Truth table0%0/2
A
A= $openai_calls{$frag->{"index"} // 0}
Aresult
11
00
Truth table0%0/2
A
A= $frag->{"index"}
Aresult
11
00
259 { id => '', type => 'function', function => { name => '', arguments => '' } };
260 0 ▶ $call->{id} = $frag->{id} if defined $frag->{id} && length $frag->{id};
Branch: 1 branch
BranchTrueFalseTotal
if defined $frag->{"id"} and length $frag->{"id"} 0 0 0
Condition0%0/3
defined $frag->{"id"} and length $frag->{"id"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $frag->{"id"} and length $frag->{"id"}
defined $frag->{"id"} length $frag->{"id"}
Truth table0%0/3
A and B
A= defined $frag->{"id"}B= length $frag->{"id"}
ABresult
0X0
100
111
261 0 ▶ my $fn = ref $frag->{function} eq 'HASH' ? $frag->{function} : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $frag->{'function'} eq 'HASH' ? : 0 0 0
262 0 ▶ $call->{function}{name} = $fn->{name} if defined $fn->{name} && length $fn->{name};
Branch: 1 branch
BranchTrueFalseTotal
if defined $fn->{"name"} and length $fn->{"name"} 0 0 0
Condition0%0/3
defined $fn->{"name"} and length $fn->{"name"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $fn->{"name"} and length $fn->{"name"}
defined $fn->{"name"} length $fn->{"name"}
Truth table0%0/3
A and B
A= defined $fn->{"name"}B= length $fn->{"name"}
ABresult
0X0
100
111
263 0 ▶ $call->{function}{arguments} .= $fn->{arguments} // '';
Condition0%0/2
$fn->{"arguments"} // ""
l!l
00
MC/DC0%0/1
$fn->{"arguments"} // ""
$fn->{"arguments"}
Truth table0%0/2
A
A= $fn->{"arguments"}
Aresult
11
00
264 }
265 0 return $d->{choices}[0]{delta}{content};
266 } else {
267 0 ▶ my $type = $d->{type} // '';
Condition0%0/2
$d->{"type"} // ""
l!l
00
MC/DC0%0/1
$d->{"type"} // ""
$d->{"type"}
Truth table0%0/2
A
A= $d->{"type"}
Aresult
11
00
268 0 ▶ $note_finish->( $d->{delta}{stop_reason} ) if $type eq 'message_delta';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "message_delta" 0 0 0
269 0 ▶ my $index = $d->{index} // 0;
Condition0%0/2
$d->{"index"} // 0
l!l
00
MC/DC0%0/1
$d->{"index"} // 0
$d->{"index"}
Truth table0%0/2
A
A= $d->{"index"}
Aresult
11
00
270 0 ▶ if ( $type eq 'content_block_start'
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "content_block_start" and ref $d->{"content_block"} eq "HASH" and ($d->{"content_block"}{"type"} // "") eq "tool_use") 0 0 0
Condition0%0/8
$type eq "content_block_start" and ref $d->{"content_block"} eq "HASH" and ($d->{"content_block"}{"type"} // "") eq "tool_use"
!ll&&!rl&&r
000
$type eq "content_block_start" and ref $d->{"content_block"} eq "HASH"
!ll&&!rl&&r
000
$d->{"content_block"}{"type"} // ""
l!l
00
MC/DC0%0/3
$type eq "content_block_start" and ref $d->{"content_block"} eq "HASH" and ($d->{"content_block"}{"type"} // "") eq "tool_use"
$type eq "content_block_start" ref $d->{"content_block"} eq "HASH" $d->{"content_block"}{"type"}
Truth table0%0/4
A and B and C
A= $type eq "content_block_start"B= ref $d->{"content_block"} eq "HASH"C= $d->{"content_block"}{"type"}
ABCresult
0XX0
10X0
1100
1111
271 && ref $d->{content_block} eq 'HASH'
272 && ( $d->{content_block}{type} // '' ) eq 'tool_use' ) {
273 0 $anthropic_blocks{$index} = { %{ $d->{content_block} }, json => '' };
274 0 return undef;
275 }
276 0 ▶ if ( $type eq 'content_block_delta' && $anthropic_blocks{$index} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "content_block_delta" and $anthropic_blocks{$index}) 0 0 0
Condition0%0/3
$type eq "content_block_delta" and $anthropic_blocks{$index}
!ll&&!rl&&r
000
MC/DC0%0/2
$type eq "content_block_delta" and $anthropic_blocks{$index}
$type eq "content_block_delta" $anthropic_blocks{$index}
Truth table0%0/3
A and B
A= $type eq "content_block_delta"B= $anthropic_blocks{$index}
ABresult
0X0
100
111
277 0 ▶ $anthropic_blocks{$index}{json} .= $d->{delta}{partial_json} // '';
Condition0%0/2
$d->{"delta"}{"partial_json"} // ""
l!l
00
MC/DC0%0/1
$d->{"delta"}{"partial_json"} // ""
$d->{"delta"}{"partial_json"}
Truth table0%0/2
A
A= $d->{"delta"}{"partial_json"}
Aresult
11
00
278 0 return undef;
279 }
280 0 ▶ if ( $type eq 'content_block_stop' && ( my $block = delete $anthropic_blocks{$index} ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "content_block_stop" and my $block = delete $anthropic_blocks{$index}) 0 0 0
Condition0%0/3
$type eq "content_block_stop" and my $block = delete $anthropic_blocks{$index}
!ll&&!rl&&r
000
MC/DC0%0/2
$type eq "content_block_stop" and my $block = delete $anthropic_blocks{$index}
$type eq "content_block_stop" my $block = delete $anthropic_blocks{$index}
Truth table0%0/3
A and B
A= $type eq "content_block_stop"B= my $block = delete $anthropic_blocks{$index}
ABresult
0X0
100
111
281 0 my $json = delete $block->{json};
282 0 ▶ $block->{input} = $json if length $json;
Branch: 1 branch
BranchTrueFalseTotal
if length $json 0 0 0
283 0 $note_calls->( grep { defined } Langertha::ToolCall->from_anthropic($block) );
284 0 return undef;
285 }
286 0 ▶ return $d->{delta}{text} if $type eq 'content_block_delta';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "content_block_delta" 0 0 0
287 0 return undef;
288 }
289 }
290 0 ▶ if ( $proto_name eq 'ollama' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($proto_name eq "ollama") 0 0 0
291 0 my $d = eval { $self->_json->decode($line) };
292 0 ▶ return undef unless ref $d eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $d eq "HASH" 0 0 0
293 0 ▶ $note_finish->( $d->{done_reason} ) if $d->{done};
Branch: 1 branch
BranchTrueFalseTotal
if $d->{"done"} 0 0 0
294 0 ▶ return $d->{response} if $generate;
Branch: 1 branch
BranchTrueFalseTotal
if $generate 0 0 0
295 0 $note_calls->( Langertha::ToolCall->extract( 'ollama', $d ) );
296 0 return $d->{message}{content};
297 }
298 0 return undef;
299 9 };
300  
301 my $f = $self->_upstream_request_f(
302 request => $http_req,
303 9 ▶ on_header => sub {
Subroutine __ANON__: called CC=2 SCAR=10.0
304 9 my ($r) = @_;
305 # A non-2xx answer is an error body, not a stream: collect it and
306 # fail the stream like handle_chat_f does (k74).
307 9 ▶ unless ( $r->is_success ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($r->is_success) 9 0 9
308 9 my $err = '';
309 9 my $status = $r->status_line;
310 18 ▶ return sub {
Subroutine __ANON__: called CC=5 SCAR=16.2
311 18 my ($data) = @_;
312 18 ▶ if ( defined $data ) { $err .= $data if length $err < 1024; return }
Branch: 2 branches
BranchTrueFalseTotal
if (defined $data) 9 9 18
if length $err < 1024 9 0 9
313 9 $err = substr( $err, 0, 500 );
314 9 $err =~ s/\s+/ /g;
315 9 $err =~ s/^ | $//g;
316 9 ▶ @error = ( "Passthrough upstream failed: $status" . ( length $err ? ": $err" : '' ) . "\n" );
Branch: 1 branch
BranchTrueFalseTotal
length $err ? : 9 0 9
317 9 $finished = 1;
318 9 ▶ if ( $pending ) { my $p = $pending; $pending = undef; $p->fail(@error) }
Branch: 1 branch
BranchTrueFalseTotal
if ($pending) 9 0 9
319 9 return;
320 9 };
321 }
322 0 ▶ return sub {
Subroutine __ANON__: not called CC=8 SCAR=42.8
323 0 my ($data) = @_;
324 0 ▶ if ( !defined $data ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $data) 0 0 0
325 0 $finish_openai_calls->();
326 0 $finished = 1;
327 0 $deliver->(undef);
328 0 return;
329 }
330 0 $buffer .= $data;
331 # Frame separator: blank line for SSE, single \n for NDJSON.
332 0 ▶ my $sep = $proto_name eq 'ollama' ? qr/\n/ : qr/\n\n/;
Branch: 1 branch
BranchTrueFalseTotal
$proto_name eq 'ollama' ? : 0 0 0
333 0 ▶ while ( $buffer =~ s/^(.*?)$sep//s ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($buffer =~ s/^(.*?)$sep//s) 0 0 0
334 0 my $frame = $1;
335 0 for my $line ( split /\n/, $frame ) {
336 0 ▶ next unless length $line;
Branch: 1 branch
BranchTrueFalseTotal
unless length $line 0 0 0
337 0 my $delta = $extract_chunk->($line);
338 0 ▶ $deliver->($delta) if defined $delta && length $delta;
Branch: 1 branch
BranchTrueFalseTotal
if defined $delta and length $delta 0 0 0
Condition0%0/3
defined $delta and length $delta
!ll&&!rl&&r
000
MC/DC0%0/2
defined $delta and length $delta
defined $delta length $delta
Truth table0%0/3
A and B
A= defined $deltaB= length $delta
ABresult
0X0
100
111
339 }
340 }
341 0 };
342 },
343 9 );
344 # A read already waiting gets the failure itself (a timeout included,
345 # k35), not an undef that would end the stream as if it were complete.
346 # The whole failure, so a timeout keeps its category (k36).
347 0 ▶ $f->on_fail( sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
348 0 @error = @_;
349 0 $finished = 1;
350 0 ▶ if ( $pending ) { my $p = $pending; $pending = undef; $p->fail(@error) }
Branch: 1 branch
BranchTrueFalseTotal
if ($pending) 0 0 0
351 9 } );
352 9 $f->retain;
353  
354 9 return $stream;
355 34 }
356  
357 0 ▶sub list_models {
Subroutine list_models: not called CC=1 SCAR=6.9
Pod undocumented
358 0 my ($self) = @_;
359 0 return [ { id => $self->model_id, object => 'model' } ];
360 }
361  
362 34 __PACKAGE__->meta->make_immutable;
363 34 1;
364  
365 __END__
« blib/lib/Langertha/Knarr/PSGI.pm ↑ Summary blib/lib/Langertha/Knarr/Handler/A2AClient.pm »