blib/lib/Langertha/Role/ResponsesCompatible.pm

filter: Statementstmt 99.5% 243 / 244 Branchbran 87.1% 216 / 248 Conditioncond 69.5% 121 / 174 MC/DCmcdc 45.7% 43 / 94 Subroutinesub 97.7% 43 / 44 Podpod 71.4% 5 / 7 totaltotal 82.7% 671 / 811 CC 201 SCAR 29.2
CC
201
Cov
87%
_responses_walk_output
39.2
parse_stream_chunk
35.1
chat_response
19.1
CRAP 18.6
« blib/lib/Langertha/ServerTool.pm ↑ Summary blib/lib/Langertha/Role/HTTP.pm »
1 package Langertha::Role::ResponsesCompatible;
2 # ABSTRACT: Role for the Open-Responses wire envelope (input/instructions/output[])
3 37 our $VERSION = '0.505';
4 37 ▶use Moose::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 37 ▶use Carp qw( croak carp );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 37 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 37 ▶use Langertha::Tool;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 37 ▶use Langertha::ToolCall;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 37 ▶use Langertha::ToolChoice;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 37 ▶use Langertha::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 37 ▶use Langertha::ServerTool;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 37 ▶use Langertha::ServerToolCall;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 37 ▶use Langertha::Usage;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 37 ▶use Scalar::Util qw( blessed );
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16  
17 # The Responses envelope carries flat tools and nested reasoning:{effort}.
18 # These override the openai defaults inherited from Role::Tools /
19 # Role::ReasoningEffort; on a lean consumer (parent = Remote) they are supplied
20 # with -excludes on those roles (ADR 0015), the same way AnthropicBase wires
21 # Role::AnthropicCompatible.
22 269 ▶sub _build_tool_wire_format { 'responses' }
Subroutine _build_tool_wire_format: called CC=1 SCAR=0.0
23 73 ▶sub _build_reasoning_wire_format { 'responses' }
Subroutine _build_reasoning_wire_format: called CC=1 SCAR=0.0
24  
25 # Content parts in input[] are typed input_text / input_image (output_text on an
26 # assistant turn); the chat-style text / image_url parts are a 400 (karr k267).
27 # Role::Chat::content_format defaults to 'openai'; a consumer composing both in
28 # one `with` excludes it from Role::Chat (Perplexity).
29 43 ▶sub content_format { 'responses' }
Subroutine content_format: called CC=1 SCAR=0.0
Pod undocumented
30  
31 # Default endpoint is the OpenAI Responses operation; Perplexity's Agent engine
32 # overrides _responses_dispatch to POST /v1/agent directly.
33 201 ▶sub chat_operation_id { 'createResponse' }
Subroutine chat_operation_id: called CC=1 SCAR=0.0
Pod undocumented
34  
35 # OpenAI reasoning models 400 on a non-default temperature whenever reasoning is
36 # active -- only the wire default (1) is accepted (karr k155). Identical gate to
37 # Role::OpenAICompatible::_temperature_kwargs, on the Responses wire: the
38 # supports('temperature') check + control-beats-attribute resolution mirror
39 # AnthropicCompatible::_temperature_kwargs, and the EFFORT-AWARE drop delegates to
40 # the per-model, resolved-effort predicate on the engine
41 # (Engine::OpenAI::_temperature_rejected_by_reasoning, inherited by
42 # OpenAIResponses via the 'responses' reasoning wire). Perplexity, the other
43 # Responses consumer, never defines that predicate, so the can() guard leaves its
44 # temperature untouched. temperature=1 passes through silently.
45 #
46 # A model that does not take temperature at all (supports('temperature') false)
47 # never gets the field, not even 1; a caller-set non-default value is dropped
48 # with the same carp as the OpenAI and Anthropic wire roles, 1 quietly (ADR 0025
49 # k214 Update; parity since karr k220).
50 317 ▶sub _temperature_kwargs {
Subroutine _temperature_kwargs: called CC=15 SCAR=27.1
51 317 my ( $self, $controls ) = @_;
52 my $temp = exists $controls->{temperature} ? $controls->{temperature}
53 317 ▶ : $self->has_temperature ? $self->temperature
Branch: 2 branches
BranchTrueFalseTotal
exists $$controls{'temperature'} ? : 8 309 317
$self->has_temperature ? : 19 290 309
54 : undef;
55 317 ▶ return () unless defined $temp;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $temp 290 27 317
56 # An engine attribute is the same on every request: warn once per engine
57 # instance (karr k247); a per-request control warns every time.
58 my $once = exists $controls->{temperature} ? undef
59 27 ▶ : 'temperature=' . $temp . ' model=' . ( $self->can('chat_model') ? $self->chat_model // '' : '' );
Branch: 2 branches
BranchTrueFalseTotal
exists $$controls{'temperature'} ? : 8 19 27
$self->can('chat_model') ? : 19 0 19
Condition50%1/2
$self->chat_model // ""
l!l
190
MC/DC0%0/1
$self->chat_model // ""
$self->chat_model
Truth table50%1/2
A
A= $self->chat_model
Aresult
11
00
60 27 ▶ unless ( $self->supports('temperature') ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->supports("temperature")) 18 9 27
61 18 ▶ $self->_langertha_carp( "".( ref $self ).": dropping temperature=$temp -- model '"
Branch: 2 branches
BranchTrueFalseTotal
if $temp != 1 15 3 18
defined $once ? : 8 7 15
Condition50%1/2
$self->chat_model // ""
l!l
150
MC/DC0%0/1
$self->chat_model // ""
$self->chat_model
Truth table50%1/2
A
A= $self->chat_model
Aresult
11
00
62 . ( $self->chat_model // '' )
63 . "' does not take a temperature (rejected or fixed server-side); "
64 . "unset temperature to silence this",
65 defined $once ? "$once unsupported" : undef )
66 if $temp != 1;
67 18 return ();
68 }
69 9 ▶ if ( $temp != 1
Branch: 1 branch
BranchTrueFalseTotal
if ($temp != 1 and $self->can("_temperature_rejected_by_reasoning") and $self->_temperature_rejected_by_reasoning($controls)) 4 5 9
Condition100%6/6
$temp != 1 and $self->can("_temperature_rejected_by_reasoning") and $self->_temperature_rejected_by_reasoning($controls)
!ll&&!rl&&r
234
$temp != 1 and $self->can("_temperature_rejected_by_reasoning")
!ll&&!rl&&r
117
MC/DC100%3/3
$temp != 1 and $self->can("_temperature_rejected_by_reasoning") and $self->_temperature_rejected_by_reasoning($controls)
$temp != 1 $self->can("_temperature_rejected_by_reasoning") $self->_temperature_rejected_by_reasoning($controls)
Truth table100%4/4
A and B and C
A= $temp != 1B= $self->can("_temperature_rejected_by_reasoning")C= $self->_temperature_rejected_by_reasoning($controls)
ABCresult
0XX0
10X0
1100
1111
70 && $self->can('_temperature_rejected_by_reasoning')
71 && $self->_temperature_rejected_by_reasoning($controls) ) {
72 4 ▶ $self->_langertha_carp( "".( ref $self ).": dropping temperature=$temp -- this reasoning "
Branch: 1 branch
BranchTrueFalseTotal
defined $once ? : 3 1 4
73 . "model rejects a non-default temperature while reasoning is active "
74 . "(only the wire default 1 is accepted); pass reasoning_effort => "
75 . "'none' to keep it",
76 defined $once ? "$once reasoning" : undef );
77 4 return ();
78 }
79 5 return ( temperature => $temp );
80 }
81  
82 # True for an item the Responses wire takes as-is (spec k206 section 3.4,
83 # karr k210, ADR 0001): a flat {type=>'function', name, ...}, a Responses
84 # server-side tool, or any other typed item Langertha does not recognise
85 # (custom, namespace, hosted shell, future server types -- values open, the
86 # provider judges). Everything else goes to format_tools: a function-tool form
87 # is formatted there, and a known client-executed built-in (local_shell,
88 # computer, apply_patch, local shell, client tool_search, ...), another wire's
89 # built-in, or an untyped nameless hash croaks there.
90 227 ▶sub _is_native_responses_tool {
Subroutine _is_native_responses_tool: called CC=9 SCAR=22.0
91 227 my ($item) = @_;
92 227 ▶ return 0 unless ref $item eq 'HASH' && length( $item->{type} // '' );
Branch: 1 branch
BranchTrueFalseTotal
unless ref $item eq "HASH" and length($$item{"type"} // "") 140 87 227
Condition100%5/5
ref $item eq "HASH" and length($$item{"type"} // "")
!ll&&!rl&&r
313787
$$item{"type"} // ""
l!l
87137
MC/DC100%2/2
ref $item eq "HASH" and length($$item{"type"} // "")
ref $item eq "HASH" $$item{"type"}
Truth table100%3/3
A and B
A= ref $item eq "HASH"B= $$item{"type"}
ABresult
0X0
100
111
93 87 my $category = Langertha::Tool->classify( $item, 'responses' );
94 87 ▶ return 1 if $category eq 'server' || $category eq 'unknown';
Branch: 1 branch
BranchTrueFalseTotal
if $category eq "server" or $category eq "unknown" 10 77 87
Condition100%3/3
$category eq "server" or $category eq "unknown"
l!l&&r!l&&!r
2877
MC/DC100%2/2
$category eq "server" or $category eq "unknown"
$category eq "server" $category eq "unknown"
Truth table100%3/3
A or B
A= $category eq "server"B= $category eq "unknown"
ABresult
1X1
011
000
95 return ( $category eq 'function' && $item->{type} eq 'function'
96 77 ▶ && ref $item->{function} ne 'HASH' ) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$category eq 'function' && $$item{'type'} eq 'function' && ref $$item{'function'} ne 'HASH' ? : 41 36 77
Condition100%6/6
$category eq "function" and $$item{"type"} eq "function" and ref $$item{"function"} ne "HASH"
!ll&&!rl&&r
35141
$category eq "function" and $$item{"type"} eq "function"
!ll&&!rl&&r
34142
MC/DC100%3/3
$category eq "function" and $$item{"type"} eq "function" and ref $$item{"function"} ne "HASH"
$category eq "function" $$item{"type"} eq "function" ref $$item{"function"} ne "HASH"
Truth table100%4/4
A and B and C
A= $category eq "function"B= $$item{"type"} eq "function"C= ref $$item{"function"} ne "HASH"
ABCresult
0XX0
10X0
1100
1111
97 }
98  
99 # Shapes the `tools` kwarg in place, for both request builders. The engine's
100 # default server_tools (Role::ServerTools) are appended to the request's own
101 # tools, then every item is decided on its own, so a mixed list keeps every
102 # tool in both orders (karr k210):
103 # - a server-side tool (a Langertha::ServerTool, or a hash ServerTool
104 # recognises for 'responses') goes out as its native hash after the
105 # engine's _server_tool_wire_check hook -- only on an engine that
106 # supports('server_tools'); a ServerTool object croaks anywhere else
107 # (k206, ADR 0030);
108 # - a native Responses item goes out verbatim (see _is_native_responses_tool);
109 # - every other function-tool form (MCP inputSchema, canonical input_schema,
110 # OpenAI chat's nested function, a Langertha::Tool) is formatted to the
111 # flat shape, and anything that is neither croaks in Langertha::Tool.
112 # Guarded by can(): a consumer that composes no Role::Tools has no
113 # format_tools, and its tools go out as given.
114 386 ▶sub _responses_tools_kwarg {
Subroutine _responses_tools_kwarg: called CC=13 SCAR=26.0
115 386 my ( $self, $extra ) = @_;
116 386 ▶ my @server = $self->can('server_tools') ? $self->_responses_default_server_tools($extra->{tools}) : ();
Branch: 1 branch
BranchTrueFalseTotal
$self->can('server_tools') ? : 280 106 386
117 383 ▶ $extra->{tools} = [ ( ref $extra->{tools} eq 'ARRAY' ? @{ $extra->{tools} } : () ), @server ]
Branch: 2 branches
BranchTrueFalseTotal
if @server 12 371 383
ref $$extra{'tools'} eq 'ARRAY' ? : 7 5 12
118 if @server;
119 383 ▶ return unless exists $extra->{tools} && ref $extra->{tools} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$extra{"tools"} and ref $$extra{"tools"} eq "ARRAY" 188 195 383
Condition66%2/3
exists $$extra{"tools"} and ref $$extra{"tools"} eq "ARRAY"
!ll&&!rl&&r
1880195
MC/DC50%1/2
exists $$extra{"tools"} and ref $$extra{"tools"} eq "ARRAY"
exists $$extra{"tools"} ref $$extra{"tools"} eq "ARRAY"
Truth table66%2/3
A and B
A= exists $$extra{"tools"}B= ref $$extra{"tools"} eq "ARRAY"
ABresult
0X0
100
111
120 195 my $server_ok = $self->supports('server_tools');
121 $extra->{tools} = [ map {
122 280 my $item = $_;
123 280 ▶ croak "".( ref $self ).": '" . $item->type . "' is a Langertha::ServerTool, "
Branch: 1 branch
BranchTrueFalseTotal
if not $server_ok and builtin::blessed($item) and $item->isa("Langertha::ServerTool") 0 280 280
Condition50%3/6
not $server_ok and builtin::blessed($item) and $item->isa("Langertha::ServerTool")
!ll&&!rl&&r
28000
not $server_ok and builtin::blessed($item)
!ll&&!rl&&r
235450
MC/DC0%0/3
not $server_ok and builtin::blessed($item) and $item->isa("Langertha::ServerTool")
not $server_ok builtin::blessed($item) $item->isa("Langertha::ServerTool")
Truth table50%2/4
not(A) and B and C
A= not $server_okB= builtin::blessed($item)C= $item->isa("Langertha::ServerTool")
ABCresult
0XX0
10X0
1100
1111
124 . "and this engine does not supports('server_tools')"
125 if !$server_ok && blessed $item && $item->isa('Langertha::ServerTool');
126 280 ▶ my $st = $server_ok ? Langertha::ServerTool->from_hash( responses => $item ) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$server_ok ? : 235 45 280
127 $st ? $self->_responses_server_tool_spec($st)
128 : !$self->can('format_tools') ? $item
129 : _is_native_responses_tool($item) ? $item
130 280 ▶ : @{ $self->format_tools([$item]) };
Branch: 3 branches
BranchTrueFalseTotal
$st ? : 53 227 280
!$self->can('format_tools') ? : 0 227 227
_is_native_responses_tool($item) ? : 51 176 227
131 195 } @{ $extra->{tools} } ];
132 129 return;
133 }
134  
135 # Shapes the `tool_choice` kwarg in place, for both request builders; runs
136 # after _responses_tools_kwarg, since it may withhold the shaped tools.
137 # Normalized to the Responses (flat function) format, pinned to the literal
138 # 'responses' rather than $self->tool_wire_format: the envelope is always
139 # Responses-shaped (mirrors OpenAICompatible pinning 'openai'). A choice whose
140 # kind the engine does not support (tool_choice_auto / _any / _none / _named)
141 # is not sent: Perplexity's Agent API has no tool_choice field at all (karr
142 # k213). The decision is Role::Chat::_gate_tool_choice, this role's k233 rule
143 # generalized to every envelope in k239: dropping 'auto' is silent, any other
144 # drop carps; an unsendable 'none' also withholds every tool of the request --
145 # function tools, native built-ins and server-tool defaults alike, since they
146 # are all on the tools list by now -- so the caller's "call no tool" holds
147 # without the field. A value ToolChoice cannot read (a provider-native choice)
148 # passes through as given where the wire has a tool_choice field, and is
149 # dropped with a carp where it has none.
150 317 ▶sub _responses_tool_choice_kwarg {
Subroutine _responses_tool_choice_kwarg: called CC=2 SCAR=6.9
151 317 my ( $self, $extra ) = @_;
152 317 ▶ my $tc = $self->_gate_tool_choice($extra) or return;
Branch: 1 branch
BranchTrueFalseTotal
my $tc = $self->_gate_tool_choice($extra) or return 11 306 317
153 11 $extra->{tool_choice} = $tc->to('responses');
154 11 return;
155 }
156  
157 # parallel_tool_use -> parallel_tool_calls, in place, for both request builders
158 # (the streaming one too, karr k240): only when tools are present, and only
159 # where the wire has the field (Perplexity's Agent API does not, k213); a value
160 # the caller set that this drops carps (k241). See
161 # Role::Chat::_parallel_tool_calls_kwarg.
162 317 ▶sub _responses_parallel_tool_calls_kwarg {
Subroutine _responses_parallel_tool_calls_kwarg: called CC=1 SCAR=0.0
163 317 my ( $self, $extra, $controls ) = @_;
164 317 return $self->_parallel_tool_calls_kwarg( $extra, $controls );
165 }
166  
167 # The engine's server_tools defaults, as ServerTool objects, minus every one
168 # the request already carries (k206 review I1/M6). Unlike a request's own
169 # tools (values open, the provider judges), a default must be a server tool:
170 # a bare string, a function tool or an unlisted type croaks here instead of
171 # being dropped by format_tools or sent on every request. The request wins:
172 # a default is skipped when a request tool is a server tool of the same kind
173 # -- same type, and for mcp the same server_label.
174 55 ▶sub _server_tool_kind {
Subroutine _server_tool_kind: called CC=3 SCAR=11.1
175 55 my ($st) = @_;
176 55 my $spec = $st->spec;
177 55 ▶ return $st->type eq 'mcp' ? 'mcp:' . ( $spec->{server_label} // '' ) : $st->type;
Branch: 1 branch
BranchTrueFalseTotal
$st->type eq 'mcp' ? : 12 43 55
Condition50%1/2
$$spec{"server_label"} // ""
l!l
120
MC/DC0%0/1
$$spec{"server_label"} // ""
$$spec{"server_label"}
Truth table50%1/2
A
A= $$spec{"server_label"}
Aresult
11
00
178 }
179  
180 280 ▶sub _responses_default_server_tools {
Subroutine _responses_default_server_tools: called CC=11 SCAR=24.1
181 280 my ( $self, $request_tools ) = @_;
182 my %requested = map {
183 280 my $st = Langertha::ServerTool->from_hash( responses => $_ );
184 253 ▶ $st ? ( _server_tool_kind($st) => 1 ) : ();
Branch: 2 branches
BranchTrueFalseTotal
$st ? : 41 212 253
ref $request_tools eq 'ARRAY' ? : 147 133 280
185 } ( ref $request_tools eq 'ARRAY' ? @$request_tools : () );
186 280 my @defaults;
187 280 for my $entry ( @{ $self->server_tools } ) {
188 17 my $st = Langertha::ServerTool->from_hash( responses => $entry );
189 17 ▶ unless ($st) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($st) 3 14 17
190 my $label = !ref $entry ? "'" . ( $entry // 'undef' ) . "'"
191 3 ▶ : ref $entry eq 'HASH' ? '{' . join( ',', map { "$_=" . ( ref $entry->{$_} ? '...' : $entry->{$_} // '' ) } sort keys %$entry ) . '}'
Branch: 3 branches
BranchTrueFalseTotal
!ref($entry) ? : 1 2 3
ref $entry eq 'HASH' ? : 2 0 2
ref $$entry{$_} ? : 1 2 3
Condition50%2/4
$entry // "undef"
l!l
10
$$entry{$_} // ""
l!l
20
MC/DC0%0/1
$entry // "undef"
$entry
MC/DC0%0/1
$$entry{$_} // ""
$$entry{$_}
Truth table50%1/2
A
A= $entry
Aresult
11
00
Truth table50%1/2
A
A= $$entry{$_}
Aresult
11
00
192 : ref $entry;
193 3 croak "".( ref $self ).": server_tools entry $label is not a server tool of the "
194 . "responses wire; pass a Langertha::ServerTool (unlisted => 1 for a type "
195 . "Langertha does not list yet) or a provider-native server tool hash";
196 }
197 14 ▶ push @defaults, $st unless $requested{ _server_tool_kind($st) };
Branch: 1 branch
BranchTrueFalseTotal
unless $requested{_server_tool_kind($st)} 12 2 14
198 }
199 277 return @defaults;
200 }
201  
202 53 ▶sub _responses_server_tool_spec {
Subroutine _responses_server_tool_spec: called CC=1 SCAR=0.0
203 53 my ( $self, $st ) = @_;
204 53 $st->to('responses'); # croaks for a server tool of another wire
205 47 return $self->_server_tool_wire_check($st);
206 }
207  
208 # max_output_tokens only where the wire takes it: a per-request max_tokens
209 # control beats the engine's response_size. Gated on supports('response_size')
210 # so an engine or a model whose wire rejects the field (a layer-2/3
211 # correction, ADR 0002/0019) never sends it (spec k206 section 4, Q2 ruling).
212 317 ▶sub _responses_max_tokens_kwargs {
Subroutine _responses_max_tokens_kwargs: called CC=4 SCAR=13.9
213 317 my ( $self, $controls ) = @_;
214 317 ▶ return () unless $self->supports('response_size');
Branch: 1 branch
BranchTrueFalseTotal
unless $self->supports("response_size") 3 314 317
215 314 ▶ return ( max_output_tokens => $controls->{max_tokens} ) if exists $controls->{max_tokens};
Branch: 1 branch
BranchTrueFalseTotal
if exists $$controls{"max_tokens"} 1 313 314
216 313 ▶ return $self->get_response_size ? ( max_output_tokens => $self->get_response_size ) : ();
Branch: 1 branch
BranchTrueFalseTotal
$self->get_response_size ? : 23 290 313
217 }
218  
219 296 ▶sub chat_request {
Subroutine chat_request: called CC=13 SCAR=25.8
Pod documented
220 296 my ( $self, $messages, %extra ) = @_;
221  
222 # Canonical per-request controls (chat_f, karr #46) beat the engine
223 # attributes on a per-key basis; the rest of %extra passes straight through.
224 296 ▶ my $controls = delete $extra{controls} // {};
Condition100%2/2
delete $extra{"controls"} // {}
l!l
90206
MC/DC100%1/1
delete $extra{"controls"} // {}
delete $extra{"controls"}
Truth table100%2/2
A
A= delete $extra{"controls"}
Aresult
11
00
225  
226 296 $self->_responses_tools_kwarg(\%extra);
227 227 $self->_responses_tool_choice_kwarg(\%extra);
228 227 $self->_responses_parallel_tool_calls_kwarg(\%extra, $controls);
229  
230 # Build input array: strip system messages (they go to instructions).
231 227 my @input;
232 227 for my $msg (@$messages) {
233 262 ▶ next if ( $msg->{role} // '' ) eq 'system';
Branch: 1 branch
BranchTrueFalseTotal
if ($$msg{"role"} // "") eq "system" 4 258 262
Condition100%2/2
$$msg{"role"} // ""
l!l
24022
MC/DC100%1/1
$$msg{"role"} // ""
$$msg{"role"}
Truth table100%2/2
A
A= $$msg{"role"}
Aresult
11
00
234 258 push @input, $self->_normalize_input_item($msg);
235 }
236  
237 # Structured output. Per-request control beats the engine attribute; the
238 # wire slot is chosen by the consumer via _responses_format_kwargs.
239 my $response_format =
240 exists $controls->{response_format} ? $controls->{response_format}
241 227 ▶ : ( $self->can('has_response_format') && $self->has_response_format )
Branch: 2 branches
BranchTrueFalseTotal
exists $$controls{'response_format'} ? : 9 218 227
$self->can('has_response_format') && $self->has_response_format ? : 3 215 218
Condition66%2/3
$self->can("has_response_format") and $self->has_response_format
!ll&&!rl&&r
02153
MC/DC50%1/2
$self->can("has_response_format") and $self->has_response_format
$self->can("has_response_format") $self->has_response_format
Truth table66%2/3
A and B
A= $self->can("has_response_format")B= $self->has_response_format
ABresult
0X0
100
111
242 ? $self->response_format
243 : undef;
244  
245 my @request_args = (
246 $self->_responses_model_kwargs,
247 $self->has_system_prompt ? ( instructions => $self->system_prompt ) : (),
248 scalar(@input) ? ( input => \@input ) : (),
249 $self->_responses_max_tokens_kwargs($controls),
250 defined $response_format
251 ? $self->_responses_format_kwargs($response_format)
252 : (),
253 $self->_temperature_kwargs($controls),
254 227 ▶ exists $controls->{seed} ? ( seed => $controls->{seed} ) : (),
Branch: 5 branches
BranchTrueFalseTotal
$self->has_system_prompt ? : 4 223 227
scalar @input ? : 227 0 227
defined $response_format ? : 12 215 227
exists $$controls{'seed'} ? : 0 227 227
$self->can('reasoning_kwargs_for') ? : 227 0 227
255 ( $self->can('reasoning_kwargs_for') ? $self->reasoning_kwargs_for(%$controls) : () ),
256 stream => JSON->false,
257 %extra,
258 );
259  
260 return $self->_responses_dispatch(
261 17 ▶ sub { $self->chat_response(shift) },
Subroutine __ANON__: called CC=1 SCAR=0.0
262 219 @request_args,
263 );
264 }
265  
266  
267 # --- Divergence hooks (OpenAI-Responses defaults) ------------------------
268  
269 211 ▶sub _responses_model_kwargs {
Subroutine _responses_model_kwargs: called CC=2 SCAR=7.2
270 211 my ( $self ) = @_;
271 211 ▶ return defined $self->chat_model ? ( model => $self->chat_model ) : ();
Branch: 1 branch
BranchTrueFalseTotal
defined $self->chat_model ? : 211 0 211
272 }
273  
274  
275 3 ▶sub _responses_format_kwargs {
Subroutine _responses_format_kwargs: called CC=1 SCAR=0.0
276 3 my ( $self, $rf ) = @_;
277 3 return ( text => { format => $self->_responses_text_format($rf) } );
278 }
279  
280  
281 199 ▶sub _responses_dispatch {
Subroutine _responses_dispatch: called CC=1 SCAR=0.0
282 199 my ( $self, $response_call, @request_args ) = @_;
283 199 return $self->generate_request(
284 $self->chat_operation_id,
285 $response_call,
286 @request_args,
287 );
288 }
289  
290  
291 226 ▶sub _normalize_input_item {
Subroutine _normalize_input_item: called CC=1 SCAR=0.0
292 226 my ( $self, $msg ) = @_;
293 # Pass through for the OpenAI Responses wire; consumers that require a typed
294 # {type:message,...} item (Perplexity) override this.
295 226 return $msg;
296 }
297  
298  
299 48 ▶sub _responses_extra_fields {
Subroutine _responses_extra_fields: called CC=1 SCAR=0.0
300 48 my ( $self, $data ) = @_;
301 48 return ();
302 }
303  
304  
305 18 ▶sub _responses_echo_item {
Subroutine _responses_echo_item: called CC=1 SCAR=0.0
306 18 my ( $self, $item ) = @_;
307 18 return $item;
308 }
309  
310  
311 # Translate an OpenAI Chat-Completions response_format hash into the value the
312 # Responses API wants under text.format. On the Chat wire the schema is nested
313 # (`{ type => 'json_schema', json_schema => { name, schema, strict } }`); the
314 # Responses wire pulls that inner object up one level (flat json_schema). A
315 # json_object stays a bare type; anything unrecognized (or already flat) passes
316 # through unchanged so we never mangle a shape we do not model.
317 3 ▶sub _responses_text_format {
Subroutine _responses_text_format: called CC=6 SCAR=18.8
318 3 my ( $self, $rf ) = @_;
319 3 ▶ return $rf unless ref $rf eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rf eq "HASH" 0 3 3
320 3 ▶ my $type = $rf->{type} // '';
Condition50%1/2
$$rf{"type"} // ""
l!l
30
MC/DC0%0/1
$$rf{"type"} // ""
$$rf{"type"}
Truth table50%1/2
A
A= $$rf{"type"}
Aresult
11
00
321 3 ▶ if ( $type eq 'json_schema' && ref $rf->{json_schema} eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "json_schema" and ref $$rf{"json_schema"} eq "HASH") 1 2 3
Condition66%2/3
$type eq "json_schema" and ref $$rf{"json_schema"} eq "HASH"
!ll&&!rl&&r
201
MC/DC50%1/2
$type eq "json_schema" and ref $$rf{"json_schema"} eq "HASH"
$type eq "json_schema" ref $$rf{"json_schema"} eq "HASH"
Truth table66%2/3
A and B
A= $type eq "json_schema"B= ref $$rf{"json_schema"} eq "HASH"
ABresult
0X0
100
111
322 1 return { %{ $rf->{json_schema} }, type => 'json_schema' };
323 }
324 2 ▶ if ( $type eq 'json_object' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "json_object") 2 0 2
325 2 return { type => 'json_object' };
326 }
327 0 return $rf;
328 }
329  
330 # --- Response parsing ----------------------------------------------------
331  
332 92 ▶sub chat_response {
Subroutine chat_response: called CC=19 SCAR=29.5
Pod documented
333 92 my ( $self, $response ) = @_;
334 92 my $data = $self->parse_response($response);
335  
336 # A 200 body with an `error` object and no output (a failed response) is
337 # no answer; it parsed to an empty Response. Croak like the k301
338 # OpenAI-compatible parser. -- karr k311
339 92 ▶ if ( ref $data eq 'HASH' && defined $data->{error}
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data eq "HASH" and defined $$data{"error"} and not ref $$data{"output"} eq "ARRAY" && @{$$data{"output"};}) 6 86 92
Condition66%6/9
ref $data eq "HASH" and defined $$data{"error"} and not ref $$data{"output"} eq "ARRAY" && @{$$data{"output"};}
!ll&&!rl&&r
8606
ref $data eq "HASH" and defined $$data{"error"}
!ll&&!rl&&r
0866
ref $$data{'output'} eq 'ARRAY' && @{$$data{'output'};}
!ll&&!rl&&r
150
MC/DC25%1/4
ref $data eq "HASH" and defined $$data{"error"} and not ref $$data{"output"} eq "ARRAY" && @{$$data{"output"};}
ref $data eq "HASH" defined $$data{"error"} ref $$data{'output'} eq 'ARRAY' @{$$data{'output'};}
Truth table60%3/5
A and B and not(C && D)
A= ref $data eq "HASH"B= defined $$data{"error"}C= ref $$data{'output'} eq 'ARRAY'D= @{$$data{'output'};}
ABCDresult
0XXX0
10XX0
11110
110X1
11101
340 5 && !( ref $data->{output} eq 'ARRAY' && @{ $data->{output} } ) ) {
341 6 croak "".( ref $self )." response carried an error: ".$self->_body_error_text( $data->{error} );
342 }
343  
344 86 my %out = $self->_responses_walk_output($data);
345 79 my %extra = $self->_responses_extra_fields($data);
346 79 my $citations = $self->_responses_merge_citations( delete $extra{citations}, $out{citations} );
347  
348 # Normalize usage to chat-style keys (Langertha::Usage / consumers read
349 # prompt_tokens/completion_tokens off the %{} overload), while carrying the
350 # Responses-native detail blocks through verbatim: input_tokens_details holds
351 # the automatic prompt-cache read/write counts, and Langertha::Usage->from_hash
352 # parses them onto cached_tokens / cache_write_tokens the same way it does the
353 # chat wire (karr #159). The per-call cost block rides along under usage.cost.
354 # The chat-spelled aliases stay so the overload keeps returning
355 # prompt_tokens/completion_tokens for existing callers (t/60, t/91).
356 79 ▶ my $usage = $data->{usage} // {};
Condition100%2/2
$$data{"usage"} // {}
l!l
5128
MC/DC100%1/1
$$data{"usage"} // {}
$$data{"usage"}
Truth table100%2/2
A
A= $$data{"usage"}
Aresult
11
00
357 my $normalized_usage = {
358 prompt_tokens => $usage->{input_tokens},
359 completion_tokens => $usage->{output_tokens},
360 total_tokens => $usage->{total_tokens},
361 ( ref $usage->{input_tokens_details} eq 'HASH'
362 ? ( input_tokens_details => $usage->{input_tokens_details} ) : () ),
363 ( ref $usage->{cost} eq 'HASH'
364 79 ▶ ? ( cost => $usage->{cost} ) : () ),
Branch: 2 branches
BranchTrueFalseTotal
ref $$usage{'input_tokens_details'} eq 'HASH' ? : 32 47 79
ref $$usage{'cost'} eq 'HASH' ? : 15 64 79
365 };
366 # Read output_tokens_details into a lexical and ref-check before deref: the
367 # chained rvalue $usage->{output_tokens_details}{reasoning_tokens} would
368 # autovivify output_tokens_details => {} into $data->{usage} (the same ref as
369 # raw => $data) when the provider omits the block, polluting the trace. -- k168
370 79 my $otd = $usage->{output_tokens_details};
371 79 ▶ if ( ref($otd) eq 'HASH' && $otd->{reasoning_tokens} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $otd eq "HASH" and $$otd{"reasoning_tokens"}) 16 63 79
Condition100%3/3
ref $otd eq "HASH" and $$otd{"reasoning_tokens"}
!ll&&!rl&&r
471616
MC/DC100%2/2
ref $otd eq "HASH" and $$otd{"reasoning_tokens"}
ref $otd eq "HASH" $$otd{"reasoning_tokens"}
Truth table100%3/3
A and B
A= ref $otd eq "HASH"B= $$otd{"reasoning_tokens"}
ABresult
0X0
100
111
372 $normalized_usage->{completion_tokens_details}
373 16 = { reasoning_tokens => $otd->{reasoning_tokens} };
374 }
375  
376 return Langertha::Response->new(
377 content => $out{content},
378 raw => $data,
379 $data->{id} ? ( id => $data->{id} ) : (),
380 $data->{model} ? ( model => $data->{model} ) : (),
381 defined $out{finish_reason} ? ( finish_reason => $out{finish_reason} ) : (),
382 usage => $normalized_usage,
383 # created_at is the Responses envelope's epoch stamp; Response.BUILDARGS
384 # runs it through Langertha::Moment->from_wire (ADR 0017), which drops it
385 # if unreadable rather than failing the whole reply.
386 defined $data->{created_at} ? ( created => $data->{created_at} ) : (),
387 $out{tool_calls} ? ( tool_calls => $out{tool_calls} ) : (),
388 $out{server_tool_calls} ? ( server_tool_calls => $out{server_tool_calls} ) : (),
389 defined $out{thinking} ? ( thinking => $out{thinking} ) : (),
390 79 ▶ defined $out{refusal} ? ( refusal => $out{refusal} ) : (),
Branch: 9 branches
BranchTrueFalseTotal
$$data{'id'} ? : 67 12 79
$$data{'model'} ? : 64 15 79
defined $out{'finish_reason'} ? : 78 1 79
defined $$data{'created_at'} ? : 34 45 79
$out{'tool_calls'} ? : 30 49 79
$out{'server_tool_calls'} ? : 6 73 79
defined $out{'thinking'} ? : 7 72 79
defined $out{'refusal'} ? : 1 78 79
$citations ? : 14 65 79
391 $citations ? ( citations => $citations ) : (),
392 %extra,
393 );
394 }
395  
396  
397 # The one output[] walker (karr k212). chat_response reads a whole response
398 # with it, and parse_stream_chunk reads the response object that the terminal
399 # response.completed / response.incomplete event carries, so a streamed and a
400 # non-streamed reply of the same response can never disagree about its tool
401 # calls, thinking or finish_reason (karr k222). Returns a hash: content (concatenated
402 # output_text, '' when none), and -- only when present -- thinking, refusal,
403 # finish_reason, and tool_calls (ArrayRef of Langertha::ToolCall).
404 105 ▶sub _responses_walk_output {
Subroutine _responses_walk_output: called CC=37 SCAR=36.7
405 105 my ( $self, $data ) = @_;
406  
407 105 my ( $text, @tc_data, $finish_reason, $thinking, @citations, $refusal );
408  
409 105 ▶ for my $item ( @{ $data->{output} // [] } ) {
Condition100%2/2
$$data{"output"} // []
l!l
1023
MC/DC100%1/1
$$data{"output"} // []
$$data{"output"}
Truth table100%2/2
A
A= $$data{"output"}
Aresult
11
00
410 149 ▶ next unless ref($item) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $item eq "HASH" 0 149 149
411 # A client-actionable item Langertha does not map croaks (k206).
412 149 Langertha::Tool->_croak_on_client_item($item);
413 142 ▶ my $type = $item->{type} // '';
Condition50%1/2
$$item{"type"} // ""
l!l
1420
MC/DC0%0/1
$$item{"type"} // ""
$$item{"type"}
Truth table50%1/2
A
A= $$item{"type"}
Aresult
11
00
414  
415 142 ▶ if ( $type eq 'reasoning' ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($type eq 'reasoning') { } 14 128 142
elsif ($type eq 'message') { } 67 61 128
elsif ($type eq 'function_call') { } 36 25 61
416 # Ref-check each level before deref: the chained rvalue
417 # $item->{summary}[0]{text} autovivified summary => [{}] into the
418 # item (the same ref as raw => $data) when a reasoning item carries
419 # no summary -- OpenAI's summary => [], xAI's encrypted-only
420 # reasoning with the field omitted. -- k211, the k168 bug class
421 14 ▶ my $first = ref $item->{summary} eq 'ARRAY' ? $item->{summary}[0] : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $$item{'summary'} eq 'ARRAY' ? : 13 1 14
422 14 ▶ my $summary = ref $first eq 'HASH' ? ( $first->{text} // '' ) : '';
Branch: 1 branch
BranchTrueFalseTotal
ref $first eq 'HASH' ? : 7 7 14
Condition50%1/2
$$first{"text"} // ""
l!l
70
MC/DC0%0/1
$$first{"text"} // ""
$$first{"text"}
Truth table50%1/2
A
A= $$first{"text"}
Aresult
11
00
423 14 ▶ $thinking //= $summary if length $summary;
Branch: 1 branch
BranchTrueFalseTotal
if length $summary 7 7 14
Condition33%1/3
$thinking //= $summary
l!l&&r!l&&!r
070
MC/DC0%0/2
$thinking //= $summary
$thinking $summary
Truth table33%1/3
A //= B
A= $thinkingB= $summary
ABresult
1X1
011
000
424 }
425 elsif ( $type eq 'message' ) {
426 67 ▶ $finish_reason = ( $item->{status} // '' ) eq 'completed' ? 'stop' : ( $item->{status} // '' );
Branch: 1 branch
BranchTrueFalseTotal
($$item{'status'} // '') eq 'completed' ? : 58 9 67
Condition100%4/4
$$item{"status"} // ""
l!l
607
$$item{"status"} // ""
l!l
27
MC/DC100%1/1
$$item{"status"} // ""
$$item{"status"}
MC/DC100%1/1
$$item{"status"} // ""
$$item{"status"}
Truth table100%2/2
A
A= $$item{"status"}
Aresult
11
00
Truth table100%2/2
A
A= $$item{"status"}
Aresult
11
00
427  
428 67 ▶ for my $block ( @{ $item->{content} // [] } ) {
Condition50%1/2
$$item{"content"} // []
l!l
670
MC/DC0%0/1
$$item{"content"} // []
$$item{"content"}
Truth table50%1/2
A
A= $$item{"content"}
Aresult
11
00
429 67 ▶ my $block_type = $block->{type} // '';
Condition50%1/2
$$block{"type"} // ""
l!l
670
MC/DC0%0/1
$$block{"type"} // ""
$$block{"type"}
Truth table50%1/2
A
A= $$block{"type"}
Aresult
11
00
430 67 ▶ if ( $block_type eq 'output_text' ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($block_type eq 'output_text') { } 65 2 67
elsif ($block_type eq 'function_call') { } 1 1 2
elsif ($block_type eq 'refusal') { } 1 0 1
431 65 ▶ $text .= ( $block->{text} // '' );
Condition50%1/2
$$block{"text"} // ""
l!l
650
MC/DC0%0/1
$$block{"text"} // ""
$$block{"text"}
Truth table50%1/2
A
A= $$block{"text"}
Aresult
11
00
432 65 push @citations, _url_citations( $block->{annotations} );
433 }
434 elsif ( $block_type eq 'function_call' ) {
435 1 push @tc_data, $block;
436 }
437 elsif ( $block_type eq 'refusal' ) {
438 # A declined request answers a refusal part instead of
439 # output_text (ADR 0004: Response.refusal). -- k301
440 $refusal .= $block->{refusal}
441 1 ▶ if defined $block->{refusal} && !ref $block->{refusal};
Branch: 1 branch
BranchTrueFalseTotal
if defined $$block{"refusal"} and not ref $$block{"refusal"} 1 0 1
Condition33%1/3
defined $$block{"refusal"} and not ref $$block{"refusal"}
!ll&&!rl&&r
001
MC/DC0%0/2
defined $$block{"refusal"} and not ref $$block{"refusal"}
defined $$block{"refusal"} not ref $$block{"refusal"}
Truth table33%1/3
A and not(B)
A= defined $$block{"refusal"}B= not ref $$block{"refusal"}
ABresult
0X0
100
111
442 }
443 }
444 }
445 elsif ( $type eq 'function_call' ) {
446 # Real Responses API emits function_call as a top-level output[]
447 # item carrying name/arguments/call_id directly on the item.
448 36 push @tc_data, $item;
449 }
450 }
451  
452 # A response that carries tool calls reports finish_reason 'tool_calls',
453 # matching the OpenAI Chat-Completions convention -- regardless of where the
454 # calls sit in output[] (a top-level function_call, or one nested in a
455 # message) and regardless of a coexisting assistant text message. A completed
456 # message sets finish_reason 'stop' in the loop above; a tool call present
457 # alongside it must win, so resolve it here rather than let output[] ordering
458 # decide (a message preamble may precede or follow the call). A genuinely
459 # non-completed message status (e.g. truncation) is left intact. -- k171
460 #
461 # A reply that hit max_output_tokens before any message item says so only
462 # on the envelope: status incomplete, incomplete_details.reason
463 # max_output_tokens (max_tokens in the reference's response.incomplete
464 # example; both are read). With no message item to carry a status --
465 # nothing but function calls in output[], or an empty output[] because
466 # reasoning consumed the whole budget -- that is finish_reason 'length'. The
467 # tool loops then treat a call whose arguments were cut off as truncated,
468 # and chat_f reports the token-limit cut on a reply with no content -- karr
469 # k349, k350, k345. A truncated *message* keeps its own status (set above).
470 98 ▶ if ( !defined $finish_reason && _cut_by_token_limit($data) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $finish_reason and _cut_by_token_limit($data)) 11 87 98
Condition100%3/3
not defined $finish_reason and _cut_by_token_limit($data)
!ll&&!rl&&r
612611
MC/DC100%2/2
not defined $finish_reason and _cut_by_token_limit($data)
not defined $finish_reason _cut_by_token_limit($data)
Truth table100%3/3
not(A) and B
A= not defined $finish_reasonB= _cut_by_token_limit($data)
ABresult
0X0
100
111
471 11 $finish_reason = 'length';
472 }
473 98 ▶ if ( @tc_data && ( !defined $finish_reason || $finish_reason eq 'stop' ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@tc_data and !defined($finish_reason) || $finish_reason eq "stop") 28 70 98
Condition100%6/6
@tc_data and !defined($finish_reason) || $finish_reason eq "stop"
!ll&&!rl&&r
61928
not defined $finish_reason or $finish_reason eq "stop"
l!l&&r!l&&!r
2269
MC/DC100%3/3
@tc_data and !defined($finish_reason) || $finish_reason eq "stop"
@tc_data not defined $finish_reason $finish_reason eq "stop"
Truth table100%4/4
A and not(B) or C
A= @tc_dataB= not defined $finish_reasonC= $finish_reason eq "stop"
ABCresult
0XX0
1000
11X1
1011
474 28 $finish_reason = 'tool_calls';
475 }
476  
477 98 my @server_calls = Langertha::ServerToolCall->extract( responses => $data );
478  
479 return (
480 content => $text // '',
481 defined $thinking ? ( thinking => $thinking ) : (),
482 defined $refusal ? ( refusal => $refusal ) : (),
483 defined $finish_reason ? ( finish_reason => $finish_reason ) : (),
484 98 ▶ @tc_data ? ( tool_calls => [ grep { defined } map { $self->_parse_function_call($_) } @tc_data ] ) : (),
Branch: 6 branches
BranchTrueFalseTotal
defined $thinking ? : 7 91 98
defined $refusal ? : 1 97 98
defined $finish_reason ? : 94 4 98
@tc_data ? : 37 61 98
@server_calls ? : 11 87 98
@citations ? : 4 94 98
Condition100%2/2
$text // ""
l!l
5939
MC/DC100%1/1
$text // ""
$text
Truth table100%2/2
A
A= $text
Aresult
11
00
485 @server_calls ? ( server_tool_calls => \@server_calls ) : (),
486 @citations ? ( citations => \@citations ) : (),
487 );
488 }
489  
490 # True when a Responses envelope reports it stopped on its output token limit.
491 37 ▶sub _cut_by_token_limit {
Subroutine _cut_by_token_limit: called CC=7 SCAR=19.7
492 37 my ($data) = @_;
493 37 ▶ return 0 unless ref $data eq 'HASH' && ( $data->{status} // '' ) eq 'incomplete';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" and ($$data{"status"} // "") eq "incomplete" 24 13 37
Condition80%4/5
ref $data eq "HASH" and ($$data{"status"} // "") eq "incomplete"
!ll&&!rl&&r
02413
$$data{"status"} // ""
l!l
334
MC/DC50%1/2
ref $data eq "HASH" and ($$data{"status"} // "") eq "incomplete"
ref $data eq "HASH" $$data{"status"}
Truth table66%2/3
A and B
A= ref $data eq "HASH"B= $$data{"status"}
ABresult
0X0
100
111
494 13 my $details = $data->{incomplete_details};
495 13 ▶ my $reason = ref $details eq 'HASH' ? ( $details->{reason} // '' ) : '';
Branch: 1 branch
BranchTrueFalseTotal
ref $details eq 'HASH' ? : 12 1 13
Condition50%1/2
$$details{"reason"} // ""
l!l
120
MC/DC0%0/1
$$details{"reason"} // ""
$$details{"reason"}
Truth table50%1/2
A
A= $$details{"reason"}
Aresult
11
00
496 13 ▶ return $reason eq 'max_output_tokens' || $reason eq 'max_tokens';
Condition66%2/3
$reason eq 'max_output_tokens' || $reason eq 'max_tokens'
l!l&&r!l&&!r
1102
MC/DC50%1/2
$reason eq 'max_output_tokens' || $reason eq 'max_tokens'
$reason eq 'max_output_tokens' $reason eq 'max_tokens'
Truth table66%2/3
A || B
A= $reason eq 'max_output_tokens'B= $reason eq 'max_tokens'
ABresult
1X1
011
000
497 }
498  
499 # The url_citation annotations of one output_text block, normalized to
500 # { url, title?, start_index?, end_index? } (spec k206 section 3.6); other
501 # annotation types (file_citation, ...) are left on raw. The url is kept
502 # verbatim -- OpenAI appends ?utm_source=openai -- and only the dedup key in
503 # _responses_merge_citations ignores it.
504 65 ▶sub _url_citations {
Subroutine _url_citations: called CC=11 SCAR=25.7
505 65 my ($annotations) = @_;
506 65 ▶ return () unless ref $annotations eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $annotations eq "ARRAY" 37 28 65
507 28 my @out;
508 28 for my $ann (@$annotations) {
509 7 ▶ next unless ref $ann eq 'HASH' && ( $ann->{type} // '' ) eq 'url_citation';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $ann eq "HASH" and ($$ann{"type"} // "") eq "url_citation" 1 6 7
Condition60%3/5
ref $ann eq "HASH" and ($$ann{"type"} // "") eq "url_citation"
!ll&&!rl&&r
016
$$ann{"type"} // ""
l!l
70
MC/DC0%0/2
ref $ann eq "HASH" and ($$ann{"type"} // "") eq "url_citation"
ref $ann eq "HASH" $$ann{"type"}
Truth table33%1/3
A and B
A= ref $ann eq "HASH"B= $$ann{"type"}
ABresult
0X0
100
111
510 6 ▶ next unless defined $ann->{url} && !ref $ann->{url} && length $ann->{url};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$ann{"url"} and not ref $$ann{"url"} and length $$ann{"url"} 0 6 6
Condition33%2/6
defined $$ann{"url"} and not ref $$ann{"url"} and length $$ann{"url"}
!ll&&!rl&&r
006
defined $$ann{"url"} and not ref $$ann{"url"}
!ll&&!rl&&r
006
MC/DC0%0/3
defined $$ann{"url"} and not ref $$ann{"url"} and length $$ann{"url"}
defined $$ann{"url"} not ref $$ann{"url"} length $$ann{"url"}
Truth table25%1/4
A and not(B) and C
A= defined $$ann{"url"}B= not ref $$ann{"url"}C= length $$ann{"url"}
ABCresult
0XX0
10X0
1100
1111
511 6 ▶ push @out, { map { defined $ann->{$_} && !ref $ann->{$_} ? ( $_ => $ann->{$_} ) : () }
Branch: 1 branch
BranchTrueFalseTotal
defined $$ann{$_} && !ref($$ann{$_}) ? : 22 2 24
Condition66%2/3
defined $$ann{$_} and not ref $$ann{$_}
!ll&&!rl&&r
2022
MC/DC50%1/2
defined $$ann{$_} and not ref $$ann{$_}
defined $$ann{$_} not ref $$ann{$_}
Truth table66%2/3
A and not(B)
A= defined $$ann{$_}B= not ref $$ann{$_}
ABresult
0X0
100
111
512 qw( url title start_index end_index ) };
513 }
514 28 return @out;
515 }
516  
517 # The dedup key of a citation url: the url without utm_* query parameters.
518 # OpenAI's url_citation carries ?utm_source=openai while its search sources
519 # list the same page with and without it, so the tracking parameter must not
520 # make one page two citations. Every other query parameter still counts --
521 # ?page=2 is another page. The stored url is never rewritten.
522 8 ▶sub _citation_key {
Subroutine _citation_key: called CC=6 SCAR=18.2
523 8 my ($url) = @_;
524 8 my ( $base, $query, $fragment ) = $url =~ /\A([^?#]*)(?:\?([^#]*))?(#.*)?\z/s;
525 8 ▶ return $url unless defined $base;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $base 0 8 8
526 8 ▶ my @keep = grep { length && !/\Autm_[^=]*(?:=|\z)/i } split /&/, ( $query // '' );
Condition80%4/5
length $_ && !/\Autm_[^=]*(?:=|\z)/i
!ll&&!rl&&r
061
$query // ""
l!l
62
MC/DC50%1/2
length $_ && !/\Autm_[^=]*(?:=|\z)/i
length $_ !/\Autm_[^=]*(?:=|\z)/i
MC/DC100%1/1
$query // ""
$query
Truth table66%2/3
A && not(B)
A= length $_B= !/\Autm_[^=]*(?:=|\z)/i
ABresult
0X0
100
111
Truth table100%2/2
A
A= $query
Aresult
11
00
527 8 ▶ return $base . ( @keep ? '?' . join( '&', @keep ) : '' ) . ( $fragment // '' );
Branch: 1 branch
BranchTrueFalseTotal
@keep ? : 1 7 8
Condition50%1/2
$fragment // ""
l!l
08
MC/DC0%0/1
$fragment // ""
$fragment
Truth table50%1/2
A
A= $fragment
Aresult
11
00
528 }
529  
530 98 ▶sub _responses_merge_citations {
Subroutine _responses_merge_citations: called CC=16 SCAR=29.1
531 98 my ( $self, $hook, $annotations ) = @_;
532 # No annotations: the hook's list goes out exactly as it came, so a
533 # consumer whose payload has none (Perplexity) is unchanged.
534 98 ▶ return ( ref $hook eq 'ARRAY' && @$hook ? $hook : undef )
Branch: 2 branches
BranchTrueFalseTotal
unless ref $annotations eq "ARRAY" and @$annotations 94 4 98
ref $hook eq 'ARRAY' && @$hook ? : 11 83 94
Condition66%4/6
ref $annotations eq "ARRAY" and @$annotations
!ll&&!rl&&r
9404
ref $hook eq "ARRAY" and @$hook
!ll&&!rl&&r
83011
MC/DC50%1/2
ref $annotations eq "ARRAY" and @$annotations
ref $annotations eq "ARRAY" @$annotations
MC/DC50%1/2
ref $hook eq "ARRAY" and @$hook
ref $hook eq "ARRAY" @$hook
Truth table66%2/3
A and B
A= ref $annotations eq "ARRAY"B= @$annotations
ABresult
0X0
100
111
Truth table66%2/3
A and B
A= ref $hook eq "ARRAY"B= @$hook
ABresult
0X0
100
111
535 unless ref $annotations eq 'ARRAY' && @$annotations;
536 4 my ( @out, %at );
537 4 ▶ for my $entry ( ( ref $hook eq 'ARRAY' ? @$hook : () ), @$annotations ) {
Branch: 1 branch
BranchTrueFalseTotal
ref $hook eq 'ARRAY' ? : 1 3 4
538 8 ▶ my $url = ref $entry eq 'HASH' ? $entry->{url} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $entry eq 'HASH' ? : 8 0 8
539 8 ▶ my $key = defined $url && !ref $url ? _citation_key($url) : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $url && !ref($url) ? : 8 0 8
Condition33%1/3
defined $url and not ref $url
!ll&&!rl&&r
008
MC/DC0%0/2
defined $url and not ref $url
defined $url not ref $url
Truth table33%1/3
A and not(B)
A= defined $urlB= not ref $url
ABresult
0X0
100
111
540 8 ▶ if ( defined $key && exists $at{$key} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $key and exists $at{$key}) 2 6 8
Condition66%2/3
defined $key and exists $at{$key}
!ll&&!rl&&r
062
MC/DC50%1/2
defined $key and exists $at{$key}
defined $key exists $at{$key}
Truth table66%2/3
A and B
A= defined $keyB= exists $at{$key}
ABresult
0X0
100
111
541 2 my $seen = $out[ $at{$key} ];
542 2 ▶ exists $seen->{$_} or $seen->{$_} = $entry->{$_} for keys %$entry;
Branch: 1 branch
BranchTrueFalseTotal
exists $$seen{$_} or $$seen{$_} = $$entry{$_} 5 3 8
543 2 next;
544 }
545 6 ▶ push @out, ref $entry eq 'HASH' ? { %$entry } : $entry;
Branch: 1 branch
BranchTrueFalseTotal
ref $entry eq 'HASH' ? : 6 0 6
546 6 ▶ $at{$key} = $#out if defined $key;
Branch: 1 branch
BranchTrueFalseTotal
if defined $key 6 0 6
547 }
548 4 return \@out;
549 }
550  
551  
552 # One function_call block through the value-object door: arguments that do not
553 # decode (a string cut off by max_output_tokens) become {} with
554 # arguments_undecodable set, where decoding them here died with a raw JSON
555 # error -- karr k349, the k324 flag. A block without a name is no call.
556 37 ▶sub _parse_function_call {
Subroutine _parse_function_call: called CC=1 SCAR=0.0
557 37 my ( $self, $block ) = @_;
558 37 return Langertha::ToolCall->from_responses($block);
559 }
560  
561 # --- Streaming (typed SSE) -----------------------------------------------
562  
563 9 ▶sub stream_format { 'sse' }
Subroutine stream_format: called CC=1 SCAR=0.0
Pod documented
564  
565  
566 90 ▶sub chat_stream_request {
Subroutine chat_stream_request: called CC=13 SCAR=29.0
Pod documented
567 90 my ( $self, $messages, %extra ) = @_;
568  
569 90 ▶ my $controls = delete $extra{controls} // {};
Condition100%2/2
delete $extra{"controls"} // {}
l!l
6723
MC/DC100%1/1
delete $extra{"controls"} // {}
delete $extra{"controls"}
Truth table100%2/2
A
A= delete $extra{"controls"}
Aresult
11
00
570  
571 90 $self->_responses_tools_kwarg(\%extra);
572 90 $self->_responses_tool_choice_kwarg(\%extra);
573 90 $self->_responses_parallel_tool_calls_kwarg(\%extra, $controls);
574  
575 90 my @input;
576 90 for my $msg (@$messages) {
577 90 ▶ next if ( $msg->{role} // '' ) eq 'system';
Branch: 1 branch
BranchTrueFalseTotal
if ($$msg{"role"} // "") eq "system" 0 90 90
Condition50%1/2
$$msg{"role"} // ""
l!l
900
MC/DC0%0/1
$$msg{"role"} // ""
$$msg{"role"}
Truth table50%1/2
A
A= $$msg{"role"}
Aresult
11
00
578 90 push @input, $self->_normalize_input_item($msg);
579 }
580  
581 my $response_format =
582 exists $controls->{response_format} ? $controls->{response_format}
583 90 ▶ : ( $self->can('has_response_format') && $self->has_response_format )
Branch: 2 branches
BranchTrueFalseTotal
exists $$controls{'response_format'} ? : 0 90 90
$self->can('has_response_format') && $self->has_response_format ? : 0 90 90
Condition33%1/3
$self->can("has_response_format") and $self->has_response_format
!ll&&!rl&&r
0900
MC/DC0%0/2
$self->can("has_response_format") and $self->has_response_format
$self->can("has_response_format") $self->has_response_format
Truth table33%1/3
A and B
A= $self->can("has_response_format")B= $self->has_response_format
ABresult
0X0
100
111
584 ? $self->response_format
585 : undef;
586  
587 my @request_args = (
588 $self->_responses_model_kwargs,
589 $self->has_system_prompt ? ( instructions => $self->system_prompt ) : (),
590 scalar(@input) ? ( input => \@input ) : (),
591 $self->_responses_max_tokens_kwargs($controls),
592 defined $response_format
593 ? $self->_responses_format_kwargs($response_format)
594 : (),
595 $self->_temperature_kwargs($controls),
596 90 ▶ exists $controls->{seed} ? ( seed => $controls->{seed} ) : (),
Branch: 5 branches
BranchTrueFalseTotal
$self->has_system_prompt ? : 0 90 90
scalar @input ? : 90 0 90
defined $response_format ? : 0 90 90
exists $$controls{'seed'} ? : 0 90 90
$self->can('reasoning_kwargs_for') ? : 90 0 90
597 ( $self->can('reasoning_kwargs_for') ? $self->reasoning_kwargs_for(%$controls) : () ),
598 stream => JSON->true,
599 %extra,
600 );
601  
602 82 ▶ return $self->_responses_dispatch( sub {}, @request_args );
Subroutine __ANON__: not called CC=1 SCAR=0.0
603 }
604  
605  
606 138 ▶sub parse_stream_chunk {
Subroutine parse_stream_chunk: called CC=31 SCAR=35.6
Pod documented
607 138 my ( $self, $data, $event ) = @_;
608  
609 138 require Langertha::Stream::Chunk;
610  
611 # The Responses/Agent stream is typed: each data payload carries a `type`
612 # naming the event (the `event:` SSE line, when present, mirrors it). Text
613 # arrives as response.output_text.delta with the increment in `delta`; the
614 # terminal response.completed carries usage. `data: [DONE]` is consumed by
615 # Role::Streaming before this is called.
616 #
617 # Live-confirmed against Perplexity's Agent stream (k147): the frame sequence
618 # is response.created -> response.in_progress -> response.output_item.added
619 # -> response.output_text.delta (text in `delta`) -> response.output_text.done
620 # -> response.output_item.done -> response.completed. Usage rides on
621 # response.completed under response.usage (no separate trailing frame), and
622 # the resolved model is under response.model there too -- the earlier frames
623 # may carry the preset label (e.g. "medium") instead, which is why model is
624 # read from response.completed and not response.created.
625 138 ▶ my $type = ref($data) eq 'HASH' ? ( $data->{type} // ( $event // '' ) ) : '';
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'HASH' ? : 138 0 138
Condition25%1/4
$$data{"type"} // ($event // "")
l!l
1380
$event // ""
l!l
00
MC/DC0%0/1
$$data{"type"} // ($event // "")
$$data{"type"}
Truth table50%1/2
A
A= $$data{"type"}
Aresult
11
00
626  
627 138 ▶ if ( $type eq 'response.output_text.delta' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "response.output_text.delta") 11 127 138
628 return Langertha::Stream::Chunk->new(
629 11 ▶ content => ( $data->{delta} // '' ),
Condition50%1/2
$$data{"delta"} // ""
l!l
110
MC/DC0%0/1
$$data{"delta"} // ""
$$data{"delta"}
Truth table50%1/2
A
A= $$data{"delta"}
Aresult
11
00
630 raw => $data,
631 is_final => 0,
632 );
633 }
634  
635 # A failed run ends the stream with response.failed (the error under
636 # response.error) instead of response.completed; a transport-level problem
637 # arrives as a top-level `error` event (code/message on the event itself).
638 # Both are terminal and carry no reply, so fail the stream loudly with the
639 # provider's own message -- the LMStudio parser's pattern: the croak fails
640 # the request future in chat_stream_realtime_f on every backend (ADR 0027),
641 # where returning undef would end the stream as an empty, silent success.
642 # -- karr k212
643 127 ▶ if ( $type eq 'response.failed' || $type eq 'error' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "response.failed" or $type eq "error") 5 122 127
Condition100%3/3
$type eq "response.failed" or $type eq "error"
l!l&&r!l&&!r
41122
MC/DC100%2/2
$type eq "response.failed" or $type eq "error"
$type eq "response.failed" $type eq "error"
Truth table100%3/3
A or B
A= $type eq "response.failed"B= $type eq "error"
ABresult
1X1
011
000
644 5 ▶ my $err = $type eq 'error' ? $data : ( ref $data->{response} eq 'HASH' ? $data->{response}{error} : undef );
Branch: 2 branches
BranchTrueFalseTotal
$type eq 'error' ? : 1 4 5
ref $$data{'response'} eq 'HASH' ? : 4 0 4
645 5 ▶ $err = $err->{error} if ref $err eq 'HASH' && ref $err->{error} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $err eq "HASH" and ref $$err{"error"} eq "HASH" 0 5 5
Condition66%2/3
ref $err eq "HASH" and ref $$err{"error"} eq "HASH"
!ll&&!rl&&r
140
MC/DC0%0/2
ref $err eq "HASH" and ref $$err{"error"} eq "HASH"
ref $err eq "HASH" ref $$err{"error"} eq "HASH"
Truth table66%2/3
A and B
A= ref $err eq "HASH"B= ref $$err{"error"} eq "HASH"
ABresult
0X0
100
111
646 my $message = ref $err eq 'HASH' && defined $err->{message} ? $err->{message}
647 5 ▶ : "$type without an error message";
Branch: 1 branch
BranchTrueFalseTotal
ref $err eq 'HASH' && defined $$err{'message'} ? : 4 1 5
Condition66%2/3
ref $err eq "HASH" and defined $$err{"message"}
!ll&&!rl&&r
104
MC/DC50%1/2
ref $err eq "HASH" and defined $$err{"message"}
ref $err eq "HASH" defined $$err{"message"}
Truth table66%2/3
A and B
A= ref $err eq "HASH"B= defined $$err{"message"}
ABresult
0X0
100
111
648 5 ▶ my $code = ref $err eq 'HASH' && defined $err->{code} && !ref $err->{code} ? " ($err->{code})" : '';
Branch: 1 branch
BranchTrueFalseTotal
ref $err eq 'HASH' && defined $$err{'code'} && !ref($$err{'code'}) ? : 4 1 5
Condition66%4/6
ref $err eq "HASH" and defined $$err{"code"} and not ref $$err{"code"}
!ll&&!rl&&r
104
ref $err eq "HASH" and defined $$err{"code"}
!ll&&!rl&&r
104
MC/DC33%1/3
ref $err eq "HASH" and defined $$err{"code"} and not ref $$err{"code"}
ref $err eq "HASH" defined $$err{"code"} not ref $$err{"code"}
Truth table50%2/4
A and B and not(C)
A= ref $err eq "HASH"B= defined $$err{"code"}C= not ref $$err{"code"}
ABCresult
0XX0
10X0
1100
1111
649 5 croak "".( ref $self )." stream failed$code: $message";
650 }
651  
652 122 ▶ if ( $type eq 'response.completed' || $type eq 'response.incomplete' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "response.completed" or $type eq "response.incomplete") 19 103 122
Condition100%3/3
$type eq "response.completed" or $type eq "response.incomplete"
l!l&&r!l&&!r
163103
MC/DC100%2/2
$type eq "response.completed" or $type eq "response.incomplete"
$type eq "response.completed" $type eq "response.incomplete"
Truth table100%3/3
A or B
A= $type eq "response.completed"B= $type eq "response.incomplete"
ABresult
1X1
011
000
653 19 ▶ my $resp = $data->{response} // {};
Condition50%1/2
$$data{"response"} // {}
l!l
190
MC/DC0%0/1
$$data{"response"} // {}
$$data{"response"}
Truth table50%1/2
A
A= $$data{"response"}
Aresult
11
00
654 19 my $usage = $resp->{usage};
655 # The terminal event carries the whole response object, so its output[]
656 # goes through the same walker chat_response uses: the function calls
657 # land on this final chunk as finished Langertha::ToolCall objects, where
658 # aggregate_tool_calls collects them (karr k212). The incremental
659 # function-call events (output_item.added/.done, function_call_arguments
660 # .delta/.done) are deliberately not assembled -- the terminal output[]
661 # is complete and authoritative, and reading only it means a call can
662 # never arrive twice. Text is not taken from it: that already streamed as
663 # output_text.delta. Thinking is, because no reasoning delta event is
664 # read (drop it here if one ever is). finish_reason is the walker's, as
665 # on chat_response: tool_calls, stop for a completed message, or the
666 # message status (incomplete) -- on text-only streams too (karr k222).
667 19 my %out = $self->_responses_walk_output($resp);
668 # A search-augmented reply carries its sources as a search_results item
669 # in the terminal response.output[] array — the same block
670 # _responses_extra_fields lifts on the non-streaming path. Reuse that
671 # divergence hook (the base envelope returns none) so a streamed reply
672 # surfaces citations too, on the final chunk (karr #158).
673 19 my %extra = $self->_responses_extra_fields($resp);
674 19 my $citations = $self->_responses_merge_citations( $extra{citations}, $out{citations} );
675 # Surface the prefix-cache read count and (Perplexity) cost off the
676 # terminal usage, symmetric to the non-streaming chat_response (k159).
677 # cached_tokens is parsed by Langertha::Usage->from_hash -- the same value
678 # object and spelling precedence the non-streaming path relies on, so both
679 # paths read every Agent/Responses cache spelling identically (from_hash
680 # reads into lexicals, so a missing block never autovivifies into
681 # raw => $data). The dedicated Stream::Chunk cached_tokens Int carries the
682 # read count; the input_tokens_details and cost blocks ride verbatim in
683 # the usage hash (cost has no Chunk attribute), mirroring the non-streaming
684 # normalized usage. -- k160
685 19 ▶ my $cached = ref($usage) eq 'HASH'
Branch: 1 branch
BranchTrueFalseTotal
ref $usage eq 'HASH' ? : 18 1 19
686 ? Langertha::Usage->from_hash($usage)->cached_tokens : undef;
687 return Langertha::Stream::Chunk->new(
688 content => '',
689 raw => $data,
690 is_final => 1,
691 $resp->{model} ? ( model => $resp->{model} ) : (),
692 $usage ? ( usage => {
693 prompt_tokens => $usage->{input_tokens},
694 completion_tokens => $usage->{output_tokens},
695 total_tokens => $usage->{total_tokens},
696 ( ref $usage->{input_tokens_details} eq 'HASH'
697 ? ( input_tokens_details => $usage->{input_tokens_details} ) : () ),
698 ( ref $usage->{cost} eq 'HASH'
699 ? ( cost => $usage->{cost} ) : () ),
700 } ) : (),
701 defined $cached ? ( cached_tokens => $cached ) : (),
702 $citations ? ( citations => $citations ) : (),
703 $out{tool_calls} ? ( tool_calls => $out{tool_calls} ) : (),
704 defined $out{finish_reason} ? ( finish_reason => $out{finish_reason} ) : (),
705 defined $out{thinking} ? ( thinking => $out{thinking} ) : (),
706 19 ▶ defined $out{refusal} ? ( refusal => $out{refusal} ) : (),
Branch: 10 branches
BranchTrueFalseTotal
$$resp{'model'} ? : 18 1 19
$usage ? : 18 1 19
ref $$usage{'input_tokens_details'} eq 'HASH' ? : 14 4 18
ref $$usage{'cost'} eq 'HASH' ? : 8 10 18
defined $cached ? : 14 5 19
$citations ? : 1 18 19
$out{'tool_calls'} ? : 7 12 19
defined $out{'finish_reason'} ? : 16 3 19
defined $out{'thinking'} ? : 0 19 19
defined $out{'refusal'} ? : 0 19 19
707 );
708 }
709  
710 # Every other typed event (response.created, response.output_item.added,
711 # reasoning / search deltas, ...) carries no assistant text -> skip.
712 103 return undef;
713 }
714  
715  
716  
717 37 1;
718  
719 __END__
« blib/lib/Langertha/ServerTool.pm ↑ Summary blib/lib/Langertha/Role/HTTP.pm »