API.pm

filter: Statementstmt 34.5% 64 / 185 Branchbran 2.2% 1 / 44 Conditioncond 0.0% 0 / 36 MC/DCmcdc 0.0% 0 / 23 Subroutinesub 43.2% 16 / 37 Podpod 100% 15 / 15 totaltotal 28.2% 96 / 340 CC 38 SCAR 26.9
CC
38
Cov
25%
new
42.0
count_input_tokens
30.0
query_string
30.0
CRAP 14.7
↑ Summary API/Content.pm »
1 package LLM::API;
2 # Anthropic specific API client
3  
4 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 1 ▶BEGIN {
Subroutine BEGIN: called CC=2 SCAR=10.5
8 1 ▶ if ( $ENV{DEBUG} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"DEBUG"}) 0 1 1
9 0 require Data::Dumper;
10 0 Data::Dumper->import('Dumper');
11 }
12 }
13  
14 1 ▶use English qw(-no_match_vars);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 ▶use CLI::Simple::Utils qw(slurp choose);
Subroutine BEGIN: called CC=1 SCAR=0.0
16 1 ▶use CLI::Simple::Constants qw(:booleans);
Subroutine BEGIN: called CC=1 SCAR=0.0
17 1 ▶use JSON::PP qw(encode_json decode_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
18 1 ▶use HTTP::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 1 ▶use LLM::API::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 1 ▶use MIME::Base64;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 1 ▶use Scalar::Util qw(reftype);
Subroutine BEGIN: called CC=1 SCAR=0.0
22 1 ▶use Time::Piece;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 1 ▶use URI::Encode qw(uri_encode);
Subroutine BEGIN: called CC=1 SCAR=0.0
24  
25 1 ▶use Readonly;
Subroutine BEGIN: called CC=1 SCAR=0.0
26  
27 1 Readonly::Scalar our $DEFAULT_LLM_MODEL => 'claude-sonnet-4-6'; # default model
28  
29 # endpoints
30 1 Readonly::Scalar our $LLM_URL_BASE => 'https://api.anthropic.com/v1/';
31 1 Readonly::Scalar our $LLM_MESSAGES_EP => 'messages';
32 1 Readonly::Scalar our $LLM_MODELS_EP => 'models';
33 1 Readonly::Scalar our $LLM_USAGE_EP => 'organizations/usage_report/messages';
34 1 Readonly::Scalar our $LLM_COUNT_TOKENS_EP => 'messages/count_tokens';
35 1 Readonly::Scalar our $LLM_COST_EP => 'organizations/cost_report';
36 1 Readonly::Scalar our $LLM_KEYS_EP => 'organizations/api_keys';
37  
38 1 Readonly::Scalar our $LLM_MAX_TOKENS => 8192;
39 1 Readonly::Scalar our $LLM_VERSION => '2023-06-01';
40 1 Readonly::Scalar our $LLM_ROLE => 'user';
41 1 Readonly::Scalar our $LLM_TIMEOUT => 300;
42  
43 1 Readonly::Scalar our $LLM_PRICING => {
44 'claude-sonnet-4-6' => [ 3 / 1_000_000, 15 / 1_000_000 ],
45 'claude-haiku-4-5-20251001' => [ 1 / 1_000_000, 5 / 1_000_000 ],
46 'claude-sonnet-5' => [ 3 / 1_000_000, 15 / 1_000_000 ], # see note below
47 'claude-opus-4-8' => [ 5 / 1_000_000, 25 / 1_000_000 ],
48 'claude-fable-5' => [ 10 / 1_000_000, 50 / 1_000_000 ],
49 'claude-mythos-5' => [ 10 / 1_000_000, 50 / 1_000_000 ],
50 };
51  
52 1 Readonly::Hash our %LLM_MEDIA_TYPES => (
53 text => 'text/plain',
54 pdf => 'application/pdf',
55 );
56  
57 1 __PACKAGE__->follow_best_practice;
58 1 __PACKAGE__->mk_accessors(
59 qw(
60 api_key_getter
61 max_tokens
62 model
63 version
64 role
65 timeout
66 )
67 );
68  
69 1 our $VERSION = '1.0.1';
70  
71 1 ▶use parent qw(Class::Accessor::Fast);
Subroutine BEGIN: called CC=1 SCAR=0.0
72  
73 ########################################################################
74 0 ▶sub new {
Subroutine new: not called CC=6 SCAR=37.4
Pod documented
75 ########################################################################
76 0 my ( $class, @args ) = @_;
77  
78 0 ▶ my $options = ref $args[0] ? $args[0] : {@args};
Branch: 1 branch
BranchTrueFalseTotal
ref $args[0] ? : 0 0 0
79  
80 # API key from the option list takes precedence
81 0 my $api_key = $options->{api_key};
82 0 delete $options->{api_key};
83  
84 0 ▶ $api_key //= $ENV{LLM_API_KEY};
Condition0%0/3
$api_key //= $ENV{"LLM_API_KEY"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$api_key //= $ENV{"LLM_API_KEY"}
$api_key $ENV{"LLM_API_KEY"}
Truth table0%0/3
A //= B
A= $api_keyB= $ENV{"LLM_API_KEY"}
ABresult
1X1
011
000
85 0 delete $ENV{LLM_API_KEY};
86  
87 0 ▶ die "ERROR: api_key is a required argument\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $api_key 0 0 0
88 if !$api_key;
89  
90 0 ▶ $options->{model} //= $DEFAULT_LLM_MODEL;
Condition0%0/3
$options->{"model"} //= $LLM::API::DEFAULT_LLM_MODEL
l!l&&r!l&&!r
000
MC/DC0%0/2
$options->{"model"} //= $LLM::API::DEFAULT_LLM_MODEL
$options->{"model"} $LLM::API::DEFAULT_LLM_MODEL
Truth table0%0/3
A //= B
A= $options->{"model"}B= $LLM::API::DEFAULT_LLM_MODEL
ABresult
1X1
011
000
91  
92 0 ▶ $options->{timeout} //= $LLM_TIMEOUT;
Condition0%0/3
$options->{"timeout"} //= $LLM::API::LLM_TIMEOUT
l!l&&r!l&&!r
000
MC/DC0%0/2
$options->{"timeout"} //= $LLM::API::LLM_TIMEOUT
$options->{"timeout"} $LLM::API::LLM_TIMEOUT
Truth table0%0/3
A //= B
A= $options->{"timeout"}B= $LLM::API::LLM_TIMEOUT
ABresult
1X1
011
000
93  
94 0 my $self = $class->SUPER::new($options);
95  
96 0 ▶ $self->set_api_key_getter( sub {$api_key} );
Subroutine __ANON__: not called CC=1 SCAR=6.9
97  
98 0 $self->_init;
99  
100 0 return $self;
101 }
102  
103 ########################################################################
104 0 ▶sub count_input_tokens {
Subroutine count_input_tokens: not called CC=5 SCAR=34.0
Pod documented
105 ########################################################################
106 0 my ( $self, $content ) = @_;
107  
108 0 ▶ die "ERROR: usage: send_prompt(array-ref)\n"
Branch: 1 branch
BranchTrueFalseTotal
if not ref $content or builtin::reftype($content) ne "ARRAY" 0 0 0
Condition0%0/3
not ref $content or builtin::reftype($content) ne "ARRAY"
l!l&&r!l&&!r
000
MC/DC0%0/2
not ref $content or builtin::reftype($content) ne "ARRAY"
not ref $content builtin::reftype($content) ne "ARRAY"
Truth table0%0/3
not(A) or B
A= not ref $contentB= builtin::reftype($content) ne "ARRAY"
ABresult
1X1
011
000
109 if !ref $content || reftype($content) ne 'ARRAY';
110  
111 0 my $req = {
112 headers => $self->headers( 'content-type' => 'application/json' ),
113 content => encode_json(
114 { model => $self->get_model,
115 messages => [
116 { role => $self->get_role,
117 content => $content,
118 }
119 ]
120 }
121 )
122 };
123  
124 0 my $rsp = HTTP::Tiny->new( timeout => $self->get_timeout )->post( $LLM_URL_BASE . $LLM_COUNT_TOKENS_EP, $req );
125  
126 0 die sprintf "ERROR %s:%s\n", @{$rsp}{qw(code content)}
127 0 ▶ if !$rsp->{success};
Branch: 1 branch
BranchTrueFalseTotal
unless $rsp->{"success"} 0 0 0
128  
129 0 ▶ my ($input_token_cost) = $self->pricing( $self->get_model // $DEFAULT_LLM_MODEL );
Condition0%0/3
$self->get_model // $LLM::API::DEFAULT_LLM_MODEL
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->get_model // $LLM::API::DEFAULT_LLM_MODEL
$self->get_model $LLM::API::DEFAULT_LLM_MODEL
Truth table0%0/3
A // B
A= $self->get_modelB= $LLM::API::DEFAULT_LLM_MODEL
ABresult
1X1
011
000
130  
131 0 my $decoded = decode_json( $rsp->{content} );
132  
133 0 my $input_tokens = $decoded->{input_tokens};
134  
135 0 return ( $input_tokens, $input_tokens * $input_token_cost );
136 }
137  
138 ########################################################################
139 0 ▶sub send_prompt {
Subroutine send_prompt: not called CC=3 SCAR=24.8
Pod documented
140 ########################################################################
141 0 my ( $self, $content ) = @_;
142  
143 0 ▶ die "ERROR: usage: send_prompt(array-ref)\n"
Branch: 1 branch
BranchTrueFalseTotal
if not ref $content or builtin::reftype($content) ne "ARRAY" 0 0 0
Condition0%0/3
not ref $content or builtin::reftype($content) ne "ARRAY"
l!l&&r!l&&!r
000
MC/DC0%0/2
not ref $content or builtin::reftype($content) ne "ARRAY"
not ref $content builtin::reftype($content) ne "ARRAY"
Truth table0%0/3
not(A) or B
A= not ref $contentB= builtin::reftype($content) ne "ARRAY"
ABresult
1X1
011
000
144 if !ref $content || reftype($content) ne 'ARRAY';
145  
146 0 my $req = {
147 headers => $self->headers( 'content-type' => 'application/json' ),
148 content => encode_json(
149 { model => $self->get_model,
150 max_tokens => $self->get_max_tokens,
151 messages => [
152 { role => $self->get_role,
153 content => $content,
154 }
155 ]
156 }
157 )
158 };
159  
160 0 my $rsp = HTTP::Tiny->new( timeout => $self->get_timeout )->post( $LLM_URL_BASE . $LLM_MESSAGES_EP, $req );
161  
162 0 return LLM::API::Response->new($rsp);
163 }
164  
165 ########################################################################
166 0 ▶sub document {
Subroutine document: not called CC=4 SCAR=30.0
Pod documented
167 ########################################################################
168 0 my ( $self, %args ) = @_;
169  
170 0 my ( $media_type, $data, $title ) = @args{qw(media_type data title)};
171  
172 0 ▶ $media_type //= 'text';
Condition0%0/2
$media_type //= "text"
l!l
00
MC/DC0%0/1
$media_type //= "text"
$media_type
Truth table0%0/2
A
A= $media_type
Aresult
11
00
173  
174 die "ERROR: unknown media type: $media_type. Only pdf and text are currently supported.\n"
175 0 ▶ if !$LLM_MEDIA_TYPES{$media_type};
Branch: 1 branch
BranchTrueFalseTotal
unless $LLM::API::LLM_MEDIA_TYPES{$media_type} 0 0 0
176  
177 0 ▶ my ( $type, $document_data ) = choose {
Subroutine __ANON__: not called CC=4 SCAR=30.0
178 0 ▶ return ( 'base64', encode_base64( ${$data} ) )
Branch: 1 branch
BranchTrueFalseTotal
if ref $data and builtin::reftype($data) eq "SCALAR" 0 0 0
Condition0%0/3
ref $data and builtin::reftype($data) eq "SCALAR"
!ll&&!rl&&r
000
MC/DC0%0/2
ref $data and builtin::reftype($data) eq "SCALAR"
ref $data builtin::reftype($data) eq "SCALAR"
Truth table0%0/3
A and B
A= ref $dataB= builtin::reftype($data) eq "SCALAR"
ABresult
0X0
100
111
179 if ref $data && reftype($data) eq 'SCALAR';
180  
181 0 ▶ return ( 'text', $data )
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data 0 0 0
182 if !ref $data;
183  
184 0 die "ERROR: only scalars and scalar references supported.\n"
185 0 };
186  
187 my $document = {
188 type => 'document',
189 source => {
190 type => $type,
191 0 ▶ media_type => $LLM_MEDIA_TYPES{$media_type},
Branch: 1 branch
BranchTrueFalseTotal
$title ? : 0 0 0
192 data => $document_data,
193 },
194 $title ? ( title => $title ) : (),
195 };
196  
197 0 return $document;
198 }
199  
200 ########################################################################
201 0 ▶sub models {
Subroutine models: not called CC=3 SCAR=24.8
Pod documented
202 ########################################################################
203 0 my ($self) = @_;
204  
205 0 my @model_list;
206  
207 0 ▶ while ($TRUE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($LLM::API::TRUE) 0 0 0
208 0 my $rsp = $self->_do_api( $LLM_URL_BASE . $LLM_MODELS_EP );
209 0 push @model_list, @{ $rsp->{data} };
210 0 ▶ last if !$rsp->{has_more};
Branch: 1 branch
BranchTrueFalseTotal
unless $rsp->{"has_more"} 0 0 0
211 }
212  
213 0 my %models = map { $_->{id} => $_ } @model_list;
214  
215 0 return \%models;
216 }
217  
218 ########################################################################
219 0 ▶sub api_keys {
Subroutine api_keys: not called CC=1 SCAR=6.9
Pod documented
220 ########################################################################
221 0 my ($self) = @_;
222  
223 0 return $self->_do_api( $LLM_URL_BASE . $LLM_KEYS_EP );
224 }
225  
226 ########################################################################
227 0 ▶sub rfc_3339 {
Subroutine rfc_3339: not called CC=1 SCAR=6.9
Pod documented
228 ########################################################################
229 0 my ( $self, $date ) = @_;
230  
231 0 ▶ my $fmt = choose {
Subroutine __ANON__: not called CC=3 SCAR=24.8
232 0 ▶ return '%Y-%m-%d'
Branch: 1 branch
BranchTrueFalseTotal
if $date =~ /\A\d{4}-\d{2}-\d{2}\z/msx 0 0 0
233 if $date =~ /\A\d{4}-\d{2}-\d{2}\z/xsm;
234  
235 0 ▶ return '%Y-%m-%d %H:%M'
Branch: 1 branch
BranchTrueFalseTotal
if $date =~ /\A\d{4}-\d{2}-\d{2}[ ]\d{2}:\d{2}\z/msx 0 0 0
236 if $date =~ /\A\d{4}-\d{2}-\d{2}[ ]\d{2}:\d{2}\z/xsm;
237  
238 0 die "ERROR: invalid date format (use YYYY-MM-DD or YYYY-MM-DD hh:mm)\n"
239 0 };
240  
241 0 my $t = Time::Piece->strptime( $date, $fmt );
242  
243 # Format to RFC 3339 standard
244 0 return $t->strftime('%Y-%m-%dT%H:%M:%SZ');
245 }
246  
247 ########################################################################
248 0 ▶sub query_string {
Subroutine query_string: not called CC=5 SCAR=34.0
Pod documented
249 ########################################################################
250 0 my ( $self, %params ) = @_;
251  
252 0 my @vars;
253  
254 0 foreach my $k ( keys %params ) {
255  
256 0 ▶ if ( !ref $params{$k} ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not ref $params{$k}) { } 0 0 0
elsif (builtin::reftype($params{$k}) eq 'ARRAY') { } 0 0 0
elsif (builtin::reftype($params{$k}) eq 'HASH') { } 0 0 0
257 0 push @vars, sprintf '%s=%s', $k, uri_encode( $params{$k} );
258 0 next;
259 }
260 elsif ( reftype( $params{$k} ) eq 'ARRAY' ) {
261 0 push @vars, map { sprintf '%s=%s', $k, uri_encode($_) } @{ $params{$k} };
262 0 next;
263 }
264 elsif ( reftype( $params{$k} ) eq 'HASH' ) {
265 0 push @vars, map { sprintf '%s=%s', $_, uri_encode( $params{$k}->{$_} ) } keys %{ $params{$k} };
266 0 next;
267 }
268  
269 0 die "ERROR: unsupport ref type\n";
270 }
271  
272 0 return join q{&}, @vars;
273 }
274  
275 ########################################################################
276 0 ▶sub now {
Subroutine now: not called CC=1 SCAR=6.9
Pod documented
277 ########################################################################
278 0 my ($self) = @_;
279  
280 0 my @t = localtime;
281 0 $t[5] += 1900;
282 0 $t[4]++;
283  
284 0 return sprintf '%04d-%02d-%02d', @t[ ( 5, 4, 3 ) ];
285 }
286  
287 ########################################################################
288 0 ▶sub usage_report {
Subroutine usage_report: not called CC=4 SCAR=30.0
Pod documented
289 ########################################################################
290 0 my ( $self, %args ) = @_;
291  
292 0 my ( $from, $to, $api_key_ids, $bucket_width ) = @args{qw(from to api_key_ids bucket_width)};
293 0 ▶ $from //= $self->now();
Condition0%0/3
$from //= $self->now
l!l&&r!l&&!r
000
MC/DC0%0/2
$from //= $self->now
$from $self->now
Truth table0%0/3
A //= B
A= $fromB= $self->now
ABresult
1X1
011
000
294  
295 0 my $starting_at = $self->rfc_3339($from);
296  
297 0 ▶ my %params = (
Branch: 1 branch
BranchTrueFalseTotal
$to ? : 0 0 0
Condition0%0/2
$bucket_width // "1h"
l!l
00
MC/DC0%0/1
$bucket_width // "1h"
$bucket_width
Truth table0%0/2
A
A= $bucket_width
Aresult
11
00
298 bucket_width => $bucket_width // '1h',
299 starting_at => $starting_at,
300 'api_key_ids[]' => $api_key_ids,
301 $to ? ( ending_at => $self->rfc_3339($to) ) : (),
302 );
303  
304 0 my $url = sprintf '%s?%s', $LLM_URL_BASE . $LLM_USAGE_EP, $self->query_string(%params);
305  
306 0 return $self->_do_admin_api($url);
307 }
308  
309 ########################################################################
310 0 ▶sub cost_report {
Subroutine cost_report: not called CC=4 SCAR=30.0
Pod documented
311 ########################################################################
312 0 my ( $self, %args ) = @_;
313  
314 0 my ( $from, $to, $bucket_width ) = @args{qw(from to bucket_width)};
315 0 ▶ $from //= $self->now();
Condition0%0/3
$from //= $self->now
l!l&&r!l&&!r
000
MC/DC0%0/2
$from //= $self->now
$from $self->now
Truth table0%0/3
A //= B
A= $fromB= $self->now
ABresult
1X1
011
000
316  
317 0 my $starting_at = $self->rfc_3339($from);
318  
319 0 ▶ my %params = (
Branch: 1 branch
BranchTrueFalseTotal
$to ? : 0 0 0
Condition0%0/2
$bucket_width // "1d"
l!l
00
MC/DC0%0/1
$bucket_width // "1d"
$bucket_width
Truth table0%0/2
A
A= $bucket_width
Aresult
11
00
320 bucket_width => $bucket_width // '1d',
321 starting_at => $starting_at,
322 $to ? ( ending_at => $self->rfc_3339($to) ) : (),
323 );
324  
325 0 my $url = sprintf '%s?%s', $LLM_URL_BASE . $LLM_COST_EP, $self->query_string(%params);
326  
327 0 return $self->_do_admin_api($url);
328 }
329  
330 ########################################################################
331 0 ▶sub headers {
Subroutine headers: not called CC=1 SCAR=6.9
Pod documented
332 ########################################################################
333 0 my ( $self, @headers ) = @_;
334  
335 return {
336 0 @headers,
337 'x-api-key' => $self->get_api_key_getter->(),
338 'anthropic-version' => $self->get_version,
339 };
340 }
341  
342 ########################################################################
343 0 ▶sub text {
Subroutine text: not called CC=1 SCAR=6.9
Pod documented
344 ########################################################################
345 0 my ( $self, $text ) = @_;
346  
347 return {
348 0 type => 'text',
349 text => $text,
350 };
351 }
352  
353 ########################################################################
354 0 ▶sub prompt {
Subroutine prompt: not called CC=1 SCAR=6.9
Pod documented
355 ########################################################################
356 0 my ( $self, $prompt ) = @_;
357  
358 0 my $llm_rsp = $self->send_prompt( [ $self->text($prompt) ] );
359  
360 0 return $llm_rsp;
361 }
362  
363 ########################################################################
364 0 ▶sub pricing {
Subroutine pricing: not called CC=3 SCAR=24.8
Pod documented
365 ########################################################################
366 0 my ( $self, $model ) = @_;
367  
368 0 ▶ $model //= $self->get_model;
Condition0%0/3
$model //= $self->get_model
l!l&&r!l&&!r
000
MC/DC0%0/2
$model //= $self->get_model
$model $self->get_model
Truth table0%0/3
A //= B
A= $modelB= $self->get_model
ABresult
1X1
011
000
369  
370 die "ERROR: no pricing for specified model.\n"
371 0 ▶ if !$LLM_PRICING->{$model};
Branch: 1 branch
BranchTrueFalseTotal
unless $LLM::API::LLM_PRICING->{$model} 0 0 0
372  
373 0 return @{ $LLM_PRICING->{$model} };
374 }
375  
376 ########################################################################
377 # Private Methods
378 ########################################################################
379  
380 ########################################################################
381 0 ▶sub _init {
Subroutine _init: not called CC=3 SCAR=19.2
382 ########################################################################
383 0 my ($self) = @_;
384  
385 1 ▶ no strict 'refs'; ## no critic
Subroutine BEGIN: called CC=1 SCAR=0.0
386 0 foreach my $key (qw(max_tokens version role)) {
387 0 my $val = ${ 'LLM::API::LLM_' . uc $key };
388  
389 0 ▶ next if defined $self->get($key);
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->get($key) 0 0 0
390  
391 0 $self->set( $key, $val );
392 }
393  
394 0 return;
395 }
396  
397 ########################################################################
398 0 ▶sub _do_api { goto &_do_admin_api; }
Subroutine _do_api: not called CC=1 SCAR=6.9
399 ########################################################################
400  
401 ########################################################################
402 0 ▶sub _do_admin_api {
Subroutine _do_admin_api: not called CC=2 SCAR=17.9
403 ########################################################################
404 0 my ( $self, $url ) = @_;
405  
406 0 my $rsp = HTTP::Tiny->new( timeout => $self->get_timeout )->get( $url, { headers => $self->headers } );
407  
408 0 die sprintf "%s:%s\n", @{$rsp}{qw(code content)}
409 0 ▶ if !$rsp->{success};
Branch: 1 branch
BranchTrueFalseTotal
unless $rsp->{"success"} 0 0 0
410  
411 0 return decode_json( $rsp->{content} );
412 }
413  
414 1 1;
415  
416 __END__
↑ Summary API/Content.pm »