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

filter: Statementstmt 97.9% 94 / 96 Branchbran 90.9% 20 / 22 Conditioncond 57.6% 15 / 26 MC/DCmcdc 21.4% 3 / 14 Subroutinesub 100% 25 / 25 Podpod 0.0% 0 / 11 totaltotal 80.9% 157 / 194 CC 24 SCAR 14.2
CC
24
Cov
90%
parse_chat_request
9.0
format_chat_response
7.2
_stop_reason
5.0
CRAP 4.2
« blib/lib/Langertha/Knarr/Stream.pm ↑ Summary blib/lib/Langertha/Knarr/Protocol/OpenAI.pm »
1 package Langertha::Knarr::Protocol::Anthropic;
2 # ABSTRACT: Anthropic-compatible wire protocol (/v1/messages) for Knarr
3  
4 46 our $VERSION = '1.102';
5 46 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 46 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 46 ▶use Time::HiRes qw( time );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 46 ▶use Langertha::Knarr::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 46 ▶use Langertha::Knarr::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 46 ▶use Langertha::Knarr::Image;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 46 ▶use Langertha::Knarr::Reasoning;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 46 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 132 ▶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 132 ▶has _args_json => ( is => 'ro', default => sub { JSON::MaybeXS->new( canonical => 1 ) } );
Subroutine __ANON__: called CC=1 SCAR=0.0
36  
37 46 has reasoning => (
38 is => 'ro',
39 isa => 'Langertha::Knarr::Reasoning',
40 lazy => 1,
41 builder => '_build_reasoning',
42 );
43  
44 52 ▶sub _build_reasoning { Langertha::Knarr::Reasoning->new }
Subroutine _build_reasoning: called CC=1 SCAR=0.0
45  
46  
47 37 ▶sub protocol_name { 'anthropic' }
Subroutine protocol_name: called CC=1 SCAR=0.0
Pod undocumented
48  
49 91 ▶sub protocol_routes {
Subroutine protocol_routes: called CC=1 SCAR=0.0
Pod undocumented
50 return [
51 91 { 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 37 ▶sub manifest_endpoint {
Subroutine manifest_endpoint: called CC=1 SCAR=0.0
Pod undocumented
61 return {
62 37 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 139 ▶sub _msg_id { 'msg_' . int( time() * 1000 ) }
Subroutine _msg_id: called CC=1 SCAR=0.0
78  
79 214 ▶sub parse_chat_request {
Subroutine parse_chat_request: called CC=8 SCAR=22.0
Pod undocumented
80 214 my ($self, $http_req, $body_ref) = @_;
81 214 ▶ my $data = $self->_json->decode( $$body_ref || '{}' );
Condition50%1/2
$$body_ref || '{}'
l!l
2140
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 214 my $system_raw = $data->{system};
85 214 my $system_str;
86 214 ▶ if (ref $system_raw eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $system_raw eq 'ARRAY') { } 0 214 214
elsif (defined $system_raw) { } 1 213 214
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 214 my @msgs;
92 214 ▶ push @msgs, { role => 'system', content => $system_str } if defined $system_str;
Branch: 1 branch
BranchTrueFalseTotal
if defined $system_str 1 213 214
93 214 ▶ push @msgs, @{ Langertha::Knarr::Image::anthropic_messages( $data->{messages} || [] ) };
Condition50%1/2
$data->{'messages'} || []
l!l
2140
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 214 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 214 ▶ extra => { forward_headers => $fwd },
Branch: 1 branch
BranchTrueFalseTotal
$data->{'stream'} ? : 82 132 214
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 46 ( 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 141 ▶sub _stop_reason {
Subroutine _stop_reason: called CC=5 SCAR=16.1
125 141 my ( $finish_reason, $has_tool_calls ) = @_;
126 141 ▶ my $fallback = $has_tool_calls ? 'tool_use' : 'end_turn';
Branch: 1 branch
BranchTrueFalseTotal
$has_tool_calls ? : 18 123 141
127 141 ▶ return $fallback unless defined $finish_reason;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $finish_reason 80 61 141
128 61 my $key = lc $finish_reason;
129 61 ▶ return $fallback if $key eq 'stop';
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "stop" 11 50 61
130 50 ▶ return $STOP_REASON{$key} // $fallback;
Condition66%2/3
$STOP_REASON{$key} // $fallback
l!l&&r!l&&!r
4820
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 82 ▶sub format_chat_response {
Subroutine format_chat_response: called CC=7 SCAR=19.7
Pod undocumented
134 82 my ($self, $response, $request) = @_;
135 82 my $r = Langertha::Knarr::Response->coerce($response);
136 82 my @blocks;
137 82 ▶ push @blocks, { type => 'text', text => $r->content } if length $r->content;
Branch: 1 branch
BranchTrueFalseTotal
if length $r->content 76 6 82
138 82 push @blocks, map { $_->to_anthropic_block } @{ $r->tool_calls };
139 82 ▶ push @blocks, { type => 'text', text => '' } unless @blocks;
Branch: 1 branch
BranchTrueFalseTotal
unless @blocks 0 82 82
140 82 my $stop_reason = _stop_reason( $r->finish_reason, $r->has_tool_calls );
141 82 ▶ my $usage = $r->usage && $r->usage->can('to_anthropic_format')
Branch: 1 branch
BranchTrueFalseTotal
$r->usage && $r->usage->can('to_anthropic_format') ? : 9 73 82
Condition66%2/3
$r->usage and $r->usage->can("to_anthropic_format")
!ll&&!rl&&r
7309
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 82 ▶ my $payload = {
Condition60%3/5
($r->model // $request->model) // "unknown"
l!l
820
$r->model // $request->model
l!l&&r!l&&!r
59230
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 82 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 414 ▶sub _sse_event {
Subroutine _sse_event: called CC=1 SCAR=0.0
159 414 my ($self, $event, $data) = @_;
160 414 return "event: $event\ndata: " . $self->_json->encode($data) . "\n\n";
161 }
162  
163 57 ▶sub format_stream_open {
Subroutine format_stream_open: called CC=2 SCAR=7.0
Pod undocumented
164 57 my ($self, $request) = @_;
165 57 my $id = _msg_id();
166 57 ▶ my $model = $request->model // 'unknown';
Condition50%1/2
$request->model // "unknown"
l!l
570
MC/DC0%0/1
$request->model // "unknown"
$request->model
Truth table50%1/2
A
A= $request->model
Aresult
11
00
167 57 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 61 ▶sub format_stream_chunk {
Subroutine format_stream_chunk: called CC=1 SCAR=0.0
Pod undocumented
186 61 my ($self, $delta_text, $request) = @_;
187 61 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 59 ▶sub format_stream_close {
Subroutine format_stream_close: called CC=5 SCAR=16.1
Pod undocumented
202 59 my ($self, $request, $finish_reason, $tool_calls, $usage) = @_;
203 59 ▶ my @calls = @{ $tool_calls // [] };
Condition100%2/2
$tool_calls // []
l!l
527
MC/DC100%1/1
$tool_calls // []
$tool_calls
Truth table100%2/2
A
A= $tool_calls
Aresult
11
00
204 59 my $stop_reason = _stop_reason( $finish_reason, scalar @calls );
205 59 my @tool_events;
206 59 my $index = 0;
207 59 for my $tc (@calls) {
208 19 $index++;
209 19 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 19 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 59 ▶ return join( '',
Branch: 1 branch
BranchTrueFalseTotal
$usage && $usage->can('to_anthropic_format') ? : 3 56 59
Condition66%2/3
$usage and $usage->can("to_anthropic_format")
!ll&&!rl&&r
5603
MC/DC50%1/2
$usage and $usage->can("to_anthropic_format")
$usage $usage->can("to_anthropic_format")
Truth table66%2/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 48 ▶sub format_stream_done { '' }
Subroutine format_stream_done: called CC=1 SCAR=0.0
Pod undocumented
237  
238 # Anthropic's error types by HTTP status; anything else is an api_error.
239 46 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 22 ▶sub _error_payload {
Subroutine _error_payload: called CC=2 SCAR=7.2
247 22 my ($status, $message) = @_;
248 return { type => 'error',
249 22 ▶ error => { type => $ERROR_TYPE{$status} // 'api_error', message => "$message" } };
Condition50%1/2
$ERROR_TYPE{$status} // "api_error"
l!l
220
MC/DC0%0/1
$ERROR_TYPE{$status} // "api_error"
$ERROR_TYPE{$status}
Truth table50%1/2
A
A= $ERROR_TYPE{$status}
Aresult
11
00
250 }
251  
252 17 ▶sub format_error_response {
Subroutine format_error_response: called CC=1 SCAR=0.0
Pod undocumented
253 17 my ($self, $status, $message) = @_;
254 17 return ( $status, { 'Content-Type' => 'application/json' },
255 $self->_json->encode( _error_payload( $status, $message ) ) );
256 }
257  
258 5 ▶sub format_stream_error {
Subroutine format_stream_error: called CC=1 SCAR=0.0
Pod undocumented
259 5 my ($self, $status, $message) = @_;
260 5 return $self->_sse_event( error => _error_payload( $status, $message ) );
261 }
262  
263 46 __PACKAGE__->meta->make_immutable;
264 46 1;
265  
266 __END__
267  
268 =pod
269  
270 =encoding UTF-8
271  
272 =head1 NAME
273  
274 Langertha::Knarr::Protocol::Anthropic - Anthropic-compatible wire protocol (/v1/messages) for Knarr
275  
276 =head1 VERSION
277  
278 version 1.102
279  
280 =head1 DESCRIPTION
281  
282 Implements the Anthropic Messages wire format on top of
283 L<Langertha::Knarr::Protocol>. Loaded by default.
284  
285 =over
286  
287 =item * C<POST /v1/messages> — sync and named-event SSE streaming
288  
289 =back
290  
291 Streaming emits the full event sequence the Anthropic SDK expects:
292 C<message_start>, C<content_block_start>, C<content_block_delta>×N,
293 C<content_block_stop>, C<message_delta>, C<message_stop>.
294  
295 =head2 reasoning
296  
297 The L<Langertha::Knarr::Reasoning> that maps the body's C<thinking> (and an
298 explicit C<output_config.effort>) onto the request's C<reasoning_effort>.
299 Pass your own to override its default level or budget anchors.
300  
301 =head1 SUPPORT
302  
303 =head2 Issues
304  
305 Please report bugs and feature requests on GitHub at
306 L<https://github.com/Getty/langertha-knarr/issues>.
307  
308 =head2 IRC
309  
310 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
311  
312 =head1 CONTRIBUTING
313  
314 Contributions are welcome! Please fork the repository and submit a pull request.
315  
316 =head1 AUTHOR
317  
318 Torsten Raudssus <torsten@raudssus.de> L<https://raudssus.de/>
319  
320 =head1 COPYRIGHT AND LICENSE
321  
322 This software is copyright (c) 2026 by Torsten Raudssus.
323  
324 This is free software; you can redistribute it and/or modify it under
325 the same terms as the Perl 5 programming language system itself.
326  
327 =cut
« blib/lib/Langertha/Knarr/Stream.pm ↑ Summary blib/lib/Langertha/Knarr/Protocol/OpenAI.pm »