blib/lib/Langertha/Knarr/Protocol/Anthropic.pm

filter: Statementstmt 79.1% 76 / 96 Branchbran 81.8% 18 / 22 Conditioncond 42.3% 11 / 26 MC/DCmcdc 7.1% 1 / 14 Subroutinesub 68.0% 17 / 25 Podpod 0.0% 0 / 11 totaltotal 63.4% 123 / 194 CC 24 SCAR 15.8
CC
24
Cov
73%
parse_chat_request
9.5
format_chat_response
7.2
format_stream_close
6.5
CRAP 4.8
« blib/lib/Langertha/Knarr/Reasoning.pm ↑ Summary blib/lib/Langertha/Knarr/Handler/RequestLog.pm »
1 package Langertha::Knarr::Protocol::Anthropic;
2 # ABSTRACT: Anthropic-compatible wire protocol (/v1/messages) for Knarr
3  
4 6 our $VERSION = '1.103';
5 6 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 6 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 6 ▶use Time::HiRes qw( time );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 6 ▶use Langertha::Knarr::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 6 ▶use Langertha::Knarr::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 6 ▶use Langertha::Knarr::Image;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 6 ▶use Langertha::Knarr::Reasoning;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 6 with 'Langertha::Knarr::Protocol';
14  
15 # --- Streaming model ---
16 # Anthropic Messages SSE — multiple named events per stream:
17 # event: message_start data: {"type":"message_start","message":{...}}
18 # event: content_block_start data: {"type":"content_block_start","index":0,
19 # "content_block":{"type":"text","text":""}}
20 # event: content_block_delta data: {"type":"content_block_delta","index":0,
21 # "delta":{"type":"text_delta","text":"Hi"}}
22 # event: content_block_stop data: {"type":"content_block_stop","index":0}
23 # event: message_delta data: {"type":"message_delta",
24 # "delta":{"stop_reason":"end_turn"},
25 # "usage":{"output_tokens":N}}
26 # event: message_stop data: {"type":"message_stop"}
27 # So a single delta from the handler MUST translate into a content_block_delta.
28 # We need the protocol to also be able to emit synthesized "start" and "stop"
29 # frames around the stream — the runtime will call format_stream_open / _close.
30 # ----------------------
31  
32 36 ▶has _json => ( is => 'ro', default => sub { JSON::MaybeXS->new( utf8 => 1, canonical => 1 ) } );
Subroutine __ANON__: called CC=1 SCAR=0.0
33 # Tool arguments become a JSON string inside an event that _json encodes to
34 # UTF-8, so they are encoded to characters here, not to bytes.
35 36 ▶has _args_json => ( is => 'ro', default => sub { JSON::MaybeXS->new( canonical => 1 ) } );
Subroutine __ANON__: called CC=1 SCAR=0.0
36  
37 6 has reasoning => (
38 is => 'ro',
39 isa => 'Langertha::Knarr::Reasoning',
40 lazy => 1,
41 builder => '_build_reasoning',
42 );
43  
44 20 ▶sub _build_reasoning { Langertha::Knarr::Reasoning->new }
Subroutine _build_reasoning: called CC=1 SCAR=0.0
45  
46  
47 0 ▶sub protocol_name { 'anthropic' }
Subroutine protocol_name: not called CC=1 SCAR=6.9
Pod undocumented
48  
49 0 ▶sub protocol_routes {
Subroutine protocol_routes: not called CC=1 SCAR=6.9
Pod undocumented
50 return [
51 0 { method => 'POST', path => '/v1/messages', action => 'chat' },
52 ];
53 }
54  
55 # Provider manifest (k14): anthropic-compat, not anthropic. parse_chat_request
56 # below carries tools and tool_choice but not output_config.format, so a
57 # client must do structured output the shim way (synthetic tool + forced
58 # tool_choice). thinking and output_config.effort arrive as reasoning_effort
59 # (k13); cache_control and disable_parallel_tool_use are not forwarded.
60 1 ▶sub manifest_endpoint {
Subroutine manifest_endpoint: called CC=1 SCAR=0.0
Pod undocumented
61 return {
62 1 dialect => 'anthropic-compat',
63 path => '',
64 capabilities => [qw(
65 chat streaming system_prompt
66 tools_native tools_hermes
67 tool_choice_auto tool_choice_any tool_choice_none tool_choice_named
68 temperature response_size reasoning_effort
69 image_input
70 )],
71 # image blocks become Langertha::Content::Image objects (k33); an older
72 # core gets them as sent, readable only by Anthropic-shape engines.
73 image_content_formats => Langertha::Knarr::Image::content_formats(qw( anthropic )),
74 };
75 }
76  
77 27 ▶sub _msg_id { 'msg_' . int( time() * 1000 ) }
Subroutine _msg_id: called CC=1 SCAR=0.0
78  
79 34 ▶sub parse_chat_request {
Subroutine parse_chat_request: called CC=8 SCAR=22.5
Pod undocumented
80 34 my ($self, $http_req, $body_ref) = @_;
81 34 ▶ my $data = $self->_json->decode( $$body_ref || '{}' );
Condition50%1/2
$$body_ref || '{}'
l!l
340
MC/DC0%0/1
$$body_ref || '{}'
$$body_ref
Truth table50%1/2
A
A= $$body_ref
Aresult
11
00
82 # Anthropic puts system prompt outside messages.
83 # system can be a string or an array of content blocks [{type:"text",text:"..."},...]
84 34 my $system_raw = $data->{system};
85 34 my $system_str;
86 34 ▶ if (ref $system_raw eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $system_raw eq 'ARRAY') { } 0 34 34
elsif (defined $system_raw) { } 1 33 34
87 0 ▶ $system_str = join("\n", map { $_->{text} // '' } @$system_raw);
Condition0%0/2
$_->{"text"} // ""
l!l
00
MC/DC0%0/1
$_->{"text"} // ""
$_->{"text"}
Truth table0%0/2
A
A= $_->{"text"}
Aresult
11
00
88 } elsif (defined $system_raw) {
89 1 $system_str = $system_raw;
90 }
91 34 my @msgs;
92 34 ▶ push @msgs, { role => 'system', content => $system_str } if defined $system_str;
Branch: 1 branch
BranchTrueFalseTotal
if defined $system_str 1 33 34
93 34 ▶ push @msgs, @{ Langertha::Knarr::Image::anthropic_messages( $data->{messages} || [] ) };
Condition50%1/2
$data->{'messages'} || []
l!l
340
MC/DC0%0/1
$data->{'messages'} || []
$data->{'messages'}
Truth table50%1/2
A
A= $data->{'messages'}
Aresult
11
00
94 # Capture auth headers for passthrough, one pair per line (k60)
95 34 my $fwd = $self->_forward_headers( $http_req, qw( x-api-key anthropic-version authorization ) );
96 return Langertha::Knarr::Request->new(
97 protocol => 'anthropic',
98 raw => $data,
99 model => $data->{model},
100 messages => \@msgs,
101 stream => $data->{stream} ? 1 : 0,
102 temperature => $data->{temperature},
103 max_tokens => $data->{max_tokens},
104 reasoning_effort => scalar $self->reasoning->from_anthropic($data),
105 system => $system_str,
106 tools => $data->{tools},
107 tool_choice => $data->{tool_choice},
108 34 ▶ extra => { forward_headers => $fwd },
Branch: 1 branch
BranchTrueFalseTotal
$data->{'stream'} ? : 0 34 34
109 );
110 }
111  
112 # Anthropic's stop_reason is a closed enum; the engine Response carries the
113 # backend's own finish_reason (OpenAI tool_calls/length/stop/content_filter,
114 # Gemini STOP/MAX_TOKENS, ...). Values already in Anthropic vocabulary pass
115 # through; a value with no Anthropic counterpart falls back like an absent one.
116 my %STOP_REASON = (
117 6 ( map { $_ => $_ } qw( end_turn max_tokens stop_sequence tool_use pause_turn refusal ) ),
118 tool_calls => 'tool_use',
119 function_call => 'tool_use',
120 length => 'max_tokens',
121 content_filter => 'refusal',
122 );
123  
124 28 ▶sub _stop_reason {
Subroutine _stop_reason: called CC=5 SCAR=16.1
125 28 my ( $finish_reason, $has_tool_calls ) = @_;
126 28 ▶ my $fallback = $has_tool_calls ? 'tool_use' : 'end_turn';
Branch: 1 branch
BranchTrueFalseTotal
$has_tool_calls ? : 7 21 28
127 28 ▶ return $fallback unless defined $finish_reason;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $finish_reason 11 17 28
128 17 my $key = lc $finish_reason;
129 17 ▶ return $fallback if $key eq 'stop';
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "stop" 3 14 17
130 14 ▶ return $STOP_REASON{$key} // $fallback;
Condition66%2/3
$STOP_REASON{$key} // $fallback
l!l&&r!l&&!r
1220
MC/DC0%0/2
$STOP_REASON{$key} // $fallback
$STOP_REASON{$key} $fallback
Truth table66%2/3
A // B
A= $STOP_REASON{$key}B= $fallback
ABresult
1X1
011
000
131 }
132  
133 27 ▶sub format_chat_response {
Subroutine format_chat_response: called CC=7 SCAR=19.7
Pod undocumented
134 27 my ($self, $response, $request) = @_;
135 27 my $r = Langertha::Knarr::Response->coerce($response);
136 27 my @blocks;
137 27 ▶ push @blocks, { type => 'text', text => $r->content } if length $r->content;
Branch: 1 branch
BranchTrueFalseTotal
if length $r->content 21 6 27
138 27 push @blocks, map { $_->to_anthropic_block } @{ $r->tool_calls };
139 27 ▶ push @blocks, { type => 'text', text => '' } unless @blocks;
Branch: 1 branch
BranchTrueFalseTotal
unless @blocks 0 27 27
140 27 my $stop_reason = _stop_reason( $r->finish_reason, $r->has_tool_calls );
141 27 ▶ my $usage = $r->usage && $r->usage->can('to_anthropic_format')
Branch: 1 branch
BranchTrueFalseTotal
$r->usage && $r->usage->can('to_anthropic_format') ? : 7 20 27
Condition66%2/3
$r->usage and $r->usage->can("to_anthropic_format")
!ll&&!rl&&r
2007
MC/DC50%1/2
$r->usage and $r->usage->can("to_anthropic_format")
$r->usage $r->usage->can("to_anthropic_format")
Truth table66%2/3
A and B
A= $r->usageB= $r->usage->can("to_anthropic_format")
ABresult
0X0
100
111
142 ? $r->usage->to_anthropic_format
143 : { input_tokens => 0, output_tokens => 0 };
144 27 ▶ my $payload = {
Condition60%3/5
($r->model // $request->model) // "unknown"
l!l
270
$r->model // $request->model
l!l&&r!l&&!r
6210
MC/DC0%0/2
($r->model // $request->model) // "unknown"
$r->model $request->model
Truth table66%2/3
A // B
A= $r->modelB= $request->model
ABresult
1X1
011
000
145 id => _msg_id(),
146 type => 'message',
147 role => 'assistant',
148 model => $r->model // $request->model // 'unknown',
149 content => \@blocks,
150 stop_reason => $stop_reason,
151 stop_sequence => undef,
152 usage => $usage,
153 };
154 27 return ( 200, { 'Content-Type' => 'application/json' }, $self->_json->encode($payload) );
155 }
156  
157 # Anthropic streaming uses named SSE events. We render full event blocks.
158 3 ▶sub _sse_event {
Subroutine _sse_event: called CC=1 SCAR=0.0
159 3 my ($self, $event, $data) = @_;
160 3 return "event: $event\ndata: " . $self->_json->encode($data) . "\n\n";
161 }
162  
163 0 ▶sub format_stream_open {
Subroutine format_stream_open: not called CC=2 SCAR=17.9
Pod undocumented
164 0 my ($self, $request) = @_;
165 0 my $id = _msg_id();
166 0 ▶ my $model = $request->model // 'unknown';
Condition0%0/2
$request->model // "unknown"
l!l
00
MC/DC0%0/1
$request->model // "unknown"
$request->model
Truth table0%0/2
A
A= $request->model
Aresult
11
00
167 0 return join( '',
168 $self->_sse_event( message_start => {
169 type => 'message_start',
170 message => {
171 id => $id, type => 'message', role => 'assistant',
172 content => [], model => $model,
173 stop_reason => undef, stop_sequence => undef,
174 usage => { input_tokens => 0, output_tokens => 0 },
175 },
176 }),
177 $self->_sse_event( content_block_start => {
178 type => 'content_block_start',
179 index => 0,
180 content_block => { type => 'text', text => '' },
181 }),
182 );
183 }
184  
185 0 ▶sub format_stream_chunk {
Subroutine format_stream_chunk: not called CC=1 SCAR=6.9
Pod undocumented
186 0 my ($self, $delta_text, $request) = @_;
187 0 return $self->_sse_event( content_block_delta => {
188 type => 'content_block_delta',
189 index => 0,
190 delta => { type => 'text_delta', text => $delta_text },
191 });
192 }
193  
194 # The routed stream carries the backend's tool calls complete, not as they
195 # were fragmented upstream, so each call closes the stream as its own
196 # tool_use block: content_block_start with an empty input, one
197 # input_json_delta holding the full arguments, content_block_stop (k19).
198 # message_delta carries the stream's usage, cumulative as Anthropic's own
199 # does -- input_tokens included, since message_start went out before the
200 # backend reported any.
201 1 ▶sub format_stream_close {
Subroutine format_stream_close: called CC=5 SCAR=18.7
Pod undocumented
202 1 my ($self, $request, $finish_reason, $tool_calls, $usage) = @_;
203 1 ▶ my @calls = @{ $tool_calls // [] };
Condition50%1/2
$tool_calls // []
l!l
01
MC/DC0%0/1
$tool_calls // []
$tool_calls
Truth table50%1/2
A
A= $tool_calls
Aresult
11
00
204 1 my $stop_reason = _stop_reason( $finish_reason, scalar @calls );
205 1 my @tool_events;
206 1 my $index = 0;
207 1 for my $tc (@calls) {
208 0 $index++;
209 0 my $block = $tc->to_anthropic_block( fallback_id => "toolu_knarr_$index" );
210 push @tool_events,
211 $self->_sse_event( content_block_start => {
212 type => 'content_block_start',
213 index => $index,
214 content_block => { type => 'tool_use', id => $block->{id}, name => $block->{name}, input => {} },
215 }),
216 $self->_sse_event( content_block_delta => {
217 type => 'content_block_delta',
218 index => $index,
219 0 delta => { type => 'input_json_delta', partial_json => $self->_args_json->encode( $block->{input} ) },
220 }),
221 $self->_sse_event( content_block_stop => { type => 'content_block_stop', index => $index } );
222 }
223 1 ▶ return join( '',
Branch: 1 branch
BranchTrueFalseTotal
$usage && $usage->can('to_anthropic_format') ? : 0 1 1
Condition33%1/3
$usage and $usage->can("to_anthropic_format")
!ll&&!rl&&r
100
MC/DC0%0/2
$usage and $usage->can("to_anthropic_format")
$usage $usage->can("to_anthropic_format")
Truth table33%1/3
A and B
A= $usageB= $usage->can("to_anthropic_format")
ABresult
0X0
100
111
224 $self->_sse_event( content_block_stop => { type => 'content_block_stop', index => 0 } ),
225 @tool_events,
226 $self->_sse_event( message_delta => {
227 type => 'message_delta',
228 delta => { stop_reason => $stop_reason, stop_sequence => undef },
229 usage => ( $usage && $usage->can('to_anthropic_format')
230 ? $usage->to_anthropic_format : { output_tokens => 0 } ),
231 }),
232 $self->_sse_event( message_stop => { type => 'message_stop' } ),
233 );
234 }
235  
236 0 ▶sub format_stream_done { '' }
Subroutine format_stream_done: not called CC=1 SCAR=6.9
Pod undocumented
237  
238 # Anthropic's error types by HTTP status; anything else is an api_error.
239 6 my %ERROR_TYPE = (
240 400 => 'invalid_request_error', 401 => 'authentication_error',
241 403 => 'permission_error', 404 => 'not_found_error',
242 413 => 'request_too_large', 429 => 'rate_limit_error',
243 504 => 'timeout_error', 529 => 'overloaded_error',
244 );
245  
246 0 ▶sub _error_payload {
Subroutine _error_payload: not called CC=2 SCAR=17.9
247 0 my ($status, $message) = @_;
248 return { type => 'error',
249 0 ▶ error => { type => $ERROR_TYPE{$status} // 'api_error', message => "$message" } };
Condition0%0/2
$ERROR_TYPE{$status} // "api_error"
l!l
00
MC/DC0%0/1
$ERROR_TYPE{$status} // "api_error"
$ERROR_TYPE{$status}
Truth table0%0/2
A
A= $ERROR_TYPE{$status}
Aresult
11
00
250 }
251  
252 0 ▶sub format_error_response {
Subroutine format_error_response: not called CC=1 SCAR=6.9
Pod undocumented
253 0 my ($self, $status, $message) = @_;
254 0 return ( $status, { 'Content-Type' => 'application/json' },
255 $self->_json->encode( _error_payload( $status, $message ) ) );
256 }
257  
258 0 ▶sub format_stream_error {
Subroutine format_stream_error: not called CC=1 SCAR=6.9
Pod undocumented
259 0 my ($self, $status, $message) = @_;
260 0 return $self->_sse_event( error => _error_payload( $status, $message ) );
261 }
262  
263 6 __PACKAGE__->meta->make_immutable;
264 6 1;
265  
266 __END__
« blib/lib/Langertha/Knarr/Reasoning.pm ↑ Summary blib/lib/Langertha/Knarr/Handler/RequestLog.pm »