blib/lib/Langertha/Engine/Virtual.pm

filter: Statementstmt 100% 336 / 336 Branchbran 91.9% 160 / 174 Conditioncond 62.3% 91 / 146 MC/DCmcdc 40.0% 30 / 75 Subroutinesub 100% 54 / 54 Podpod 85.7% 6 / 7 totaltotal 85.4% 677 / 792 CC 150 SCAR 26.0
CC
150
Cov
89%
_normalize_reaction
44.9
_request_view
17.2
_message_text
17.0
CRAP 13.5
« blib/lib/Langertha/CachedContent.pm ↑ Summary blib/lib/Langertha/RateLimit.pm »
1 package Langertha::Engine::Virtual;
2 # ABSTRACT: Rule-driven engine that answers without network, key or model
3 10 our $VERSION = '0.505';
4 10 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 10 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 10 ▶use Encode ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 10 ▶use HTTP::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 10 ▶use HTTP::Status ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 10 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 10 ▶use Module::Runtime qw( use_module );
Subroutine BEGIN: called CC=1 SCAR=0.0
11 10 ▶use Path::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 10 ▶use Scalar::Util qw( looks_like_number weaken );
Subroutine BEGIN: called CC=1 SCAR=0.0
13 10 ▶use YAML::PP;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 10 ▶use Langertha::Request::SyncHTTP;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 10 ▶use Langertha::Virtual::Rules ();
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 10 extends 'Langertha::Engine::Remote';
18  
19 # Chat, streaming and the tool loop run through the real OpenAI-dialect request
20 # builders and parsers (OpenAICompatible + OpenAPI + Streaming); only the
21 # transport is replaced by the in-process rule evaluation below. No
22 # Temperature, ResponseFormat, ...: the engine claims only what it serves.
23 10 with map { 'Langertha::Role::'.$_ } qw(
24 OpenAICompatible
25 OpenAPI
26 Models
27 ResponseSize
28 SystemPrompt
29 Streaming
30 Chat
31 Tools
32 StreamUsage
33 );
34  
35  
36 10 has '+url' => (
37 default => 'http://virtual.invalid/v1',
38 );
39  
40  
41 42 ▶sub default_model { 'virtual' }
Subroutine default_model: called CC=1 SCAR=0.0
Pod documented
42  
43  
44 2 ▶sub api_key_env { undef }
Subroutine api_key_env: called CC=1 SCAR=0.0
Pod documented
45  
46  
47 43 ▶sub _build_openapi_operations {
Subroutine _build_openapi_operations: called CC=1 SCAR=0.0
48 43 return use_module('Langertha::Spec::OpenAI')->data;
49 }
50  
51 has rules => (
52 is => 'ro',
53 isa => 'ArrayRef',
54 24 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
55 10 );
56  
57  
58 10 has fallback => (
59 is => 'ro',
60 predicate => 'has_fallback',
61 );
62  
63  
64 10 has script => (
65 is => 'ro',
66 isa => 'ArrayRef',
67 predicate => 'has_script',
68 );
69  
70  
71 10 has rules_file => (
72 is => 'ro',
73 isa => 'Str',
74 predicate => 'has_rules_file',
75 );
76  
77  
78 10 has default_usage => (
79 is => 'ro',
80 isa => 'HashRef|CodeRef',
81 predicate => 'has_default_usage',
82 );
83  
84  
85 10 has stream_chunk_size => (
86 is => 'ro',
87 isa => 'Int',
88 default => 8,
89 );
90  
91  
92 has requests => (
93 is => 'ro',
94 isa => 'ArrayRef',
95 init_arg => undef,
96 82 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
97 10 );
98  
99  
100 has calls => (
101 is => 'ro',
102 isa => 'ArrayRef',
103 init_arg => undef,
104 83 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
105 10 );
106  
107  
108 has results => (
109 is => 'ro',
110 isa => 'ArrayRef',
111 init_arg => undef,
112 82 ▶ default => sub { [] },
Subroutine __ANON__: called CC=1 SCAR=0.0
113 10 );
114  
115  
116 10 has _script_position => (
117 is => 'rw',
118 isa => 'Int',
119 init_arg => undef,
120 default => 0,
121 );
122  
123 10 my %RULES_FILE_KEYS = map { $_ => 1 } qw( rules after fallback script );
124 10 my %REACTION_KEYS = map { $_ => 1 } qw( answer text tool_calls error usage );
125 10 my %PRESETS = (
126 echo => '_preset_echo',
127 files => '_preset_files',
128 );
129  
130 85 ▶around BUILDARGS => sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
131 85 my ( $orig, $class, @args ) = @_;
132 85 my $args = $class->$orig(@args);
133 85 ▶ return $args unless defined $args->{rules_file};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$args{"rules_file"} 79 6 85
134 6 my $file = $args->{rules_file} = "$args->{rules_file}";
135 6 my $loaded = $class->_load_rules_file($file);
136 5 for my $key ( sort keys %$loaded ) {
137 6 ▶ croak $class.": $key is given to the constructor and in rules_file $file" if exists $args->{$key};
Branch: 1 branch
BranchTrueFalseTotal
if exists $$args{$key} 1 5 6
138 5 $args->{$key} = $loaded->{$key};
139 }
140 4 return $args;
141 10 };
142  
143 82 ▶sub BUILD {
Subroutine BUILD: called CC=9 SCAR=22.0
Pod undocumented
144 82 my ( $self ) = @_;
145 82 my $class = ref $self;
146 82 my @rules = @{ $self->rules };
147 82 ▶ croak $class.': rules must be a list of TRIGGER => REACTION pairs (odd number of elements)' if @rules % 2;
Branch: 1 branch
BranchTrueFalseTotal
if @rules % 2 1 81 82
148 81 ▶ croak $class.': rules and script cannot be combined' if @rules && $self->has_script;
Branch: 1 branch
BranchTrueFalseTotal
if @rules and $self->has_script 1 80 81
Condition100%3/3
@rules and $self->has_script
!ll&&!rl&&r
24561
MC/DC100%2/2
@rules and $self->has_script
@rules $self->has_script
Truth table100%3/3
A and B
A= @rulesB= $self->has_script
ABresult
0X0
100
111
149 80 ▶ croak $class.': stream_chunk_size must be at least 1' if $self->stream_chunk_size < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->stream_chunk_size < 1 1 79 80
150 79 my $number = 0;
151 79 ▶ while ( my ( $trigger, $reaction ) = splice @rules, 0, 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = splice(@rules, 0, 2)) 155 67 222
152 155 $number++;
153 155 $self->_check_trigger( $trigger, "rule $number" );
154 153 $self->_check_reaction( $reaction, "rule $number" );
155 }
156 67 ▶ if ( $self->has_script ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_script) 5 62 67
157 5 my $position = 0;
158 5 $self->_check_reaction( $_, 'script entry '.++$position ) for @{ $self->script };
159 }
160 66 ▶ $self->_check_reaction( $self->fallback, 'fallback' ) if $self->has_fallback;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_fallback 23 43 66
161 65 return;
162 }
163  
164 155 ▶sub _check_trigger {
Subroutine _check_trigger: called CC=8 SCAR=20.8
165 155 my ( $self, $trigger, $where ) = @_;
166 155 my $class = ref $self;
167 155 ▶ croak $class.": the trigger of $where is undef" unless defined $trigger;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $trigger 1 154 155
168 154 ▶ return if !ref $trigger || ref $trigger eq 'Regexp' || ref $trigger eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if not ref $trigger or ref $trigger eq "Regexp" or ref $trigger eq "CODE" 138 16 154
Condition100%6/6
not ref $trigger or ref $trigger eq "Regexp" or ref $trigger eq "CODE"
l!l&&r!l&&!r
136216
not ref $trigger or ref $trigger eq "Regexp"
l!l&&r!l&&!r
1241218
MC/DC100%3/3
not ref $trigger or ref $trigger eq "Regexp" or ref $trigger eq "CODE"
not ref $trigger ref $trigger eq "Regexp" ref $trigger eq "CODE"
Truth table100%4/4
not(A) or B or C
A= not ref $triggerB= ref $trigger eq "Regexp"C= ref $trigger eq "CODE"
ABCresult
1XX1
01X1
0011
0000
169 16 ▶ return if ref $trigger eq 'HASH' && keys %$trigger == 1 && ref $trigger->{after} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $trigger eq "HASH" and keys %$trigger == 1 and ref $$trigger{"after"} eq "HASH" 15 1 16
Condition66%4/6
ref $trigger eq "HASH" and keys %$trigger == 1 and ref $$trigger{"after"} eq "HASH"
!ll&&!rl&&r
1015
ref $trigger eq "HASH" and keys %$trigger == 1
!ll&&!rl&&r
1015
MC/DC33%1/3
ref $trigger eq "HASH" and keys %$trigger == 1 and ref $$trigger{"after"} eq "HASH"
ref $trigger eq "HASH" keys %$trigger == 1 ref $$trigger{"after"} eq "HASH"
Truth table50%2/4
A and B and C
A= ref $trigger eq "HASH"B= keys %$trigger == 1C= ref $$trigger{"after"} eq "HASH"
ABCresult
0XX0
10X0
1100
1111
170 1 croak $class.": the trigger of $where must be a string, a Regexp, a sub or after(...)";
171 }
172  
173 186 ▶sub _check_reaction {
Subroutine _check_reaction: called CC=2 SCAR=6.9
174 186 my ( $self, $reaction, $where ) = @_;
175 186 ▶ return if ref $reaction eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $reaction eq "CODE" 31 155 186
176 155 $self->_normalize_reaction( $reaction, $where );
177 143 return;
178 }
179  
180 # A reaction as data: { answer => Maybe[Str], tool_calls => [ [ $name, \%arguments ], ... ] },
181 # plus usage => \%usage when it gives one.
182 278 ▶sub _normalize_reaction {
Subroutine _normalize_reaction: called CC=34 SCAR=38.1
183 278 my ( $self, $reaction, $where ) = @_;
184 278 my $class = ref $self;
185 278 ▶ return { answer => $reaction, tool_calls => [] } if defined $reaction && !ref $reaction;
Branch: 1 branch
BranchTrueFalseTotal
if defined $reaction and not ref $reaction 20 258 278
Condition100%3/3
defined $reaction and not ref $reaction
!ll&&!rl&&r
125720
MC/DC100%2/2
defined $reaction and not ref $reaction
defined $reaction not ref $reaction
Truth table100%3/3
A and not(B)
A= defined $reactionB= not ref $reaction
ABresult
0X0
100
111
186 258 ▶ croak $class.": $where must be a text, a HashRef or a sub, not ".( defined $reaction ? ref $reaction : 'undef' )
Branch: 2 branches
BranchTrueFalseTotal
unless ref $reaction eq "HASH" 4 254 258
defined $reaction ? : 3 1 4
187 unless ref $reaction eq 'HASH';
188 254 my @unknown = grep { !$REACTION_KEYS{$_} } sort keys %$reaction;
189 254 ▶ croak $class.": $where has unknown keys: @unknown (known: answer, text, tool_calls, usage, error)" if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 2 252 254
190 252 ▶ croak $class.": $where has both answer and text" if exists $reaction->{answer} && exists $reaction->{text};
Branch: 1 branch
BranchTrueFalseTotal
if exists $$reaction{"answer"} and exists $$reaction{"text"} 1 251 252
Condition100%3/3
exists $$reaction{"answer"} and exists $$reaction{"text"}
!ll&&!rl&&r
1051461
MC/DC100%2/2
exists $$reaction{"answer"} and exists $$reaction{"text"}
exists $$reaction{"answer"} exists $$reaction{"text"}
Truth table100%3/3
A and B
A= exists $$reaction{"answer"}B= exists $$reaction{"text"}
ABresult
0X0
100
111
191 251 ▶ if ( exists $reaction->{error} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $$reaction{"error"}) 30 221 251
192 30 my $error = $reaction->{error};
193 croak $class.": the error of $where must be { status => ..., message => ... }"
194 unless ref $error eq 'HASH' && defined $error->{status} && $error->{status} =~ /\A[45]\d\d\z/
195 30 ▶ && defined $error->{message} && !ref $error->{message};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $error eq "HASH" and defined $$error{"status"} and $$error{"status"} =~ /\A[45]\d\d\z/ and defined $$error{"message"} and not ref $$error{"message"} 0 30 30
Condition33%4/12
ref $error eq "HASH" and defined $$error{"status"} and $$error{"status"} =~ /\A[45]\d\d\z/ and defined $$error{"message"} and not ref $$error{"message"}
!ll&&!rl&&r
0030
ref $error eq "HASH" and defined $$error{"status"} and $$error{"status"} =~ /\A[45]\d\d\z/ and defined $$error{"message"}
!ll&&!rl&&r
0030
ref $error eq "HASH" and defined $$error{"status"} and $$error{"status"} =~ /\A[45]\d\d\z/
!ll&&!rl&&r
0030
ref $error eq "HASH" and defined $$error{"status"}
!ll&&!rl&&r
0030
MC/DC0%0/5
ref $error eq "HASH" and defined $$error{"status"} and $$error{"status"} =~ /\A[45]\d\d\z/ and defined $$error{"message"} and not ref $$error{"message"}
ref $error eq "HASH" defined $$error{"status"} $$error{"status"} =~ /\A[45]\d\d\z/ defined $$error{"message"} not ref $$error{"message"}
Truth table16%1/6
A and B and C and D and not(E)
A= ref $error eq "HASH"B= defined $$error{"status"}C= $$error{"status"} =~ /\A[45]\d\d\z/D= defined $$error{"message"}E= not ref $$error{"message"}
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
196 croak $class.": $where has an error together with an answer, tool calls or usage"
197 30 ▶ if grep { exists $reaction->{$_} } qw( answer text tool_calls usage );
Branch: 1 branch
BranchTrueFalseTotal
if grep {exists $$reaction{$_};} "answer", "text", "tool_calls", "usage" 2 28 30
198 28 return { error => { status => 0 + $error->{status}, message => $error->{message} } };
199 }
200 croak $class.": the usage of $where must be a HashRef"
201 221 ▶ if exists $reaction->{usage} && ref $reaction->{usage} ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if exists $$reaction{"usage"} and ref $$reaction{"usage"} ne "HASH" 1 220 221
Condition100%3/3
exists $$reaction{"usage"} and ref $$reaction{"usage"} ne "HASH"
!ll&&!rl&&r
184361
MC/DC100%2/2
exists $$reaction{"usage"} and ref $$reaction{"usage"} ne "HASH"
exists $$reaction{"usage"} ref $$reaction{"usage"} ne "HASH"
Truth table100%3/3
A and B
A= exists $$reaction{"usage"}B= ref $$reaction{"usage"} ne "HASH"
ABresult
0X0
100
111
202 220 ▶ my $answer = exists $reaction->{answer} ? $reaction->{answer} : $reaction->{text};
Branch: 1 branch
BranchTrueFalseTotal
exists $$reaction{'answer'} ? : 144 76 220
203 220 ▶ croak $class.": the answer of $where must be a text" if ref $answer;
Branch: 1 branch
BranchTrueFalseTotal
if ref $answer 0 220 220
204 220 ▶ my $calls = $reaction->{tool_calls} // [];
Condition100%2/2
$$reaction{"tool_calls"} // []
l!l
83137
MC/DC100%1/1
$$reaction{"tool_calls"} // []
$$reaction{"tool_calls"}
Truth table100%2/2
A
A= $$reaction{"tool_calls"}
Aresult
11
00
205 220 ▶ croak $class.": the tool_calls of $where must be an ArrayRef" unless ref $calls eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $calls eq "ARRAY" 0 220 220
206 220 my @tool_calls;
207 220 for my $call (@$calls) {
208 107 ▶ croak $class.": each tool call of $where must be [ \$name, \\%arguments ]"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $call eq "ARRAY" and @$call >= 1 and @$call <= 2 and defined $$call[0] and not ref $$call[0] and length $$call[0] and !defined($$call[1]) || ref $$call[1] eq "HASH" 2 105 107
Condition52%11/21
ref $call eq "ARRAY" and @$call >= 1 and @$call <= 2 and defined $$call[0] and not ref $$call[0] and length $$call[0] and !defined($$call[1]) || ref $$call[1] eq "HASH"
!ll&&!rl&&r
11105
ref $call eq "ARRAY" and @$call >= 1 and @$call <= 2 and defined $$call[0] and not ref $$call[0] and length $$call[0]
!ll&&!rl&&r
01106
ref $call eq "ARRAY" and @$call >= 1 and @$call <= 2 and defined $$call[0] and not ref $$call[0]
!ll&&!rl&&r
00107
ref $call eq "ARRAY" and @$call >= 1 and @$call <= 2 and defined $$call[0]
!ll&&!rl&&r
00107
ref $call eq "ARRAY" and @$call >= 1 and @$call <= 2
!ll&&!rl&&r
00107
ref $call eq "ARRAY" and @$call >= 1
!ll&&!rl&&r
00107
not defined $$call[1] or ref $$call[1] eq "HASH"
l!l&&r!l&&!r
01051
MC/DC25%2/8
ref $call eq "ARRAY" and @$call >= 1 and @$call <= 2 and defined $$call[0] and not ref $$call[0] and length $$call[0] and !defined($$call[1]) || ref $$call[1] eq "HASH"
ref $call eq "ARRAY" @$call >= 1 @$call <= 2 defined $$call[0] not ref $$call[0] length $$call[0] not defined $$call[1] ref $$call[1] eq "HASH"
Truth table33%3/9
A and B and C and D and not(E) and F and not(G) or H
A= ref $call eq "ARRAY"B= @$call >= 1C= @$call <= 2D= defined $$call[0]E= not ref $$call[0]F= length $$call[0]G= not defined $$call[1]H= ref $$call[1] eq "HASH"
ABCDEFGHresult
0XXXXXXX0
10XXXXXX0
110XXXXX0
1110XXXX0
11110XXX0
111110XX0
111111000
1111111X1
111111011
209 unless ref $call eq 'ARRAY' && @$call >= 1 && @$call <= 2
210 && defined $call->[0] && !ref $call->[0] && length $call->[0]
211 && ( !defined $call->[1] || ref $call->[1] eq 'HASH' );
212 105 ▶ push @tool_calls, [ $call->[0], $call->[1] // {} ];
Condition50%1/2
$$call[1] // {}
l!l
1050
MC/DC0%0/1
$$call[1] // {}
$$call[1]
Truth table50%1/2
A
A= $$call[1]
Aresult
11
00
213 }
214 218 ▶ croak $class.": $where has neither an answer nor tool calls" unless defined $answer || @tool_calls;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $answer or @tool_calls 1 217 218
Condition100%3/3
defined $answer or @tool_calls
l!l&&r!l&&!r
148691
MC/DC100%2/2
defined $answer or @tool_calls
defined $answer @tool_calls
Truth table100%3/3
A or B
A= defined $answerB= @tool_calls
ABresult
1X1
011
000
215 return { answer => $answer, tool_calls => \@tool_calls,
216 217 ▶ exists $reaction->{usage} ? ( usage => $reaction->{usage} ) : () };
Branch: 1 branch
BranchTrueFalseTotal
exists $$reaction{'usage'} ? : 36 181 217
217 }
218  
219 6 ▶sub _load_rules_file {
Subroutine _load_rules_file: called CC=9 SCAR=22.0
220 6 my ( $class, $file ) = @_;
221 6 my $data = YAML::PP->new( boolean => 'JSON::PP' )->load_string( path($file)->slurp_utf8 );
222 6 ▶ croak $class.": rules_file $file must hold a mapping" unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 0 6 6
223 6 my @unknown = grep { !$RULES_FILE_KEYS{$_} } sort keys %$data;
224 6 ▶ croak $class.": rules_file $file has unknown keys: @unknown (known: after, fallback, rules, script)" if @unknown;
Branch: 1 branch
BranchTrueFalseTotal
if @unknown 1 5 6
225 5 my %args;
226 5 for my $key (qw( rules after )) {
227 10 ▶ next unless exists $data->{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $$data{$key} 4 6 10
228 6 my $map = $data->{$key};
229 6 ▶ croak $class.": $key in rules_file $file must be a mapping" unless ref $map eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $map eq "HASH" 0 6 6
230 6 push @{ $args{rules} }, map {
231 6 ▶ ( $key eq 'after' ? Langertha::Virtual::Rules::after($_) : $_ ) => $map->{$_}
Branch: 1 branch
BranchTrueFalseTotal
$key eq 'after' ? : 2 8 10
232 } sort keys %$map;
233 }
234 5 ▶ $args{fallback} = $data->{fallback} if exists $data->{fallback};
Branch: 1 branch
BranchTrueFalseTotal
if exists $$data{"fallback"} 2 3 5
235 5 ▶ $args{script} = $data->{script} if exists $data->{script};
Branch: 1 branch
BranchTrueFalseTotal
if exists $$data{"script"} 1 4 5
236 5 return \%args;
237 }
238  
239 5 ▶sub preset {
Subroutine preset: called CC=4 SCAR=14.2
Pod documented
240 5 my ( $class, $name, @args ) = @_;
241 5 ▶ my $method = defined $name ? $PRESETS{$name} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 5 0 5
242 5 ▶ croak $class.'->preset: unknown preset '.( $name // 'undef' ).' (known: '.join( ', ', sort keys %PRESETS ).')'
Branch: 1 branch
BranchTrueFalseTotal
unless $method 1 4 5
Condition50%1/2
$name // "undef"
l!l
10
MC/DC0%0/1
$name // "undef"
$name
Truth table50%1/2
A
A= $name
Aresult
11
00
243 unless $method;
244 4 return $class->new( $class->$method, @args );
245 }
246  
247  
248 2 ▶sub _preset_echo {
Subroutine _preset_echo: called CC=1 SCAR=0.1
249 return (
250 4 ▶ fallback => sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
251 4 my ( $request ) = @_;
252 4 ▶ return Langertha::Virtual::Rules::answer( $request->{last_user_text} // '' );
Condition50%1/2
$$request{"last_user_text"} // ""
l!l
40
MC/DC0%0/1
$$request{"last_user_text"} // ""
$$request{"last_user_text"}
Truth table50%1/2
A
A= $$request{"last_user_text"}
Aresult
11
00
253 },
254 2 );
255 }
256  
257 2 ▶sub _preset_files {
Subroutine _preset_files: called CC=1 SCAR=0.0
258 return (
259 rules => [
260 2 ▶ qr/\ARead the file (\S+)\z/ => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
261 2 my ( $request, $path ) = @_;
262 2 return Langertha::Virtual::Rules::tool( read_file => { path => $path } );
263 },
264 3 ▶ qr/\AWrite the file (\S+): (.*)\z/s => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
265 3 my ( $request, $path, $content ) = @_;
266 3 return Langertha::Virtual::Rules::tool( write_file => { path => $path, content => $content } );
267 },
268 2 ▶ qr/\ARun the command (.+)\z/s => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
269 2 my ( $request, $command ) = @_;
270 2 return Langertha::Virtual::Rules::tool( bash => { command => $command } );
271 },
272 4 ▶ Langertha::Virtual::Rules::after() => sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
273 4 my ( $request ) = @_;
274 return Langertha::Virtual::Rules::answer(
275 4 ▶ join "\n", map { $_->{content} // '' } @{ $request->{tool_results} } );
Condition50%1/2
$$_{"content"} // ""
l!l
40
MC/DC0%0/1
$$_{"content"} // ""
$$_{"content"}
Truth table50%1/2
A
A= $$_{"content"}
Aresult
11
00
276 },
277 2 ],
278 fallback => Langertha::Virtual::Rules::answer(
279 "I know these prompts:\nRead the file PATH\nWrite the file PATH: CONTENT\nRun the command COMMAND" ),
280 );
281 }
282  
283 2 ▶sub list_models {
Subroutine list_models: called CC=2 SCAR=6.9
Pod documented
284 2 my ( $self, %opts ) = @_;
285 2 my @models = ( { id => $self->model } );
286 2 ▶ return $opts{full} ? \@models : [ map { $_->{id} } @models ];
Branch: 1 branch
BranchTrueFalseTotal
$opts{'full'} ? : 1 1 2
287 }
288  
289  
290 # The transport. Every request the sync user agent sends is answered by the
291 # request_send handler before LWP picks a protocol, and the _f calls run over
292 # the same agent through the sync shim, so nothing ever reaches the network.
293 41 ▶sub _build_user_agent {
Subroutine _build_user_agent: called CC=1 SCAR=0.0
294 41 my ( $self ) = @_;
295 41 my $ua = LWP::UserAgent->new( agent => $self->user_agent_agent );
296 41 my $engine = $self;
297 41 weaken $engine;
298 110 ▶ $ua->add_handler( request_send => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
299 110 my ( $request ) = @_;
300 110 return $engine->_virtual_response($request);
301 41 } );
302 41 return $ua;
303 }
304  
305 26 ▶sub _build__async_http {
Subroutine _build__async_http: called CC=1 SCAR=0.0
306 26 my ( $self ) = @_;
307 26 return Langertha::Request::SyncHTTP->new( user_agent => $self->user_agent );
308 }
309  
310 8 ▶around format_tool_results => sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
311 8 my ( $orig, $self, $data, $results ) = @_;
312 8 ▶ push @{ $self->results }, @{ $results // [] };
Condition50%1/2
$results // []
l!l
80
MC/DC0%0/1
$results // []
$results
Truth table50%1/2
A
A= $results
Aresult
11
00
313 8 return $self->$orig( $data, $results );
314 10 };
315  
316 # A request the engine cannot answer comes back as an error status, so the
317 # caller fails with core's own "<class> request failed: <status> - <reason>"
318 # on every path (sync, _f, the tool loops), as with a real server.
319 110 ▶sub _virtual_response {
Subroutine _virtual_response: called CC=3 SCAR=11.0
320 110 my ( $self, $request ) = @_;
321 110 my $reply = $self->virtual_reply( $request->method, $request->uri->path, $request->content );
322 110 ▶ if ( $reply->{code} == 200 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$reply{"code"} == 200) 96 14 110
323 96 my $body = $self->json->decode( $request->content );
324 96 ▶ return $self->_virtual_stream_response( $request, $body, $reply->{content} ) if $body->{stream};
Branch: 1 branch
BranchTrueFalseTotal
if $$body{"stream"} 13 83 96
325 }
326 97 return $self->_virtual_http_response( $request, @{$reply}{qw( code message content )} );
327 }
328  
329 # A stream request's reply as the server-sent events an OpenAI server sends.
330 13 ▶sub _virtual_stream_response {
Subroutine _virtual_stream_response: called CC=3 SCAR=11.0
331 13 my ( $self, $request, $body, $completion ) = @_;
332 my $chunks = $self->virtual_stream_chunks( $completion,
333 13 ▶ include_usage => ref $body->{stream_options} eq 'HASH' && $body->{stream_options}{include_usage} ? 1 : 0 );
Branch: 1 branch
BranchTrueFalseTotal
ref $$body{'stream_options'} eq 'HASH' && $$body{'stream_options'}{'include_usage'} ? : 11 2 13
Condition66%2/3
ref $$body{"stream_options"} eq "HASH" and $$body{"stream_options"}{"include_usage"}
!ll&&!rl&&r
0211
MC/DC50%1/2
ref $$body{"stream_options"} eq "HASH" and $$body{"stream_options"}{"include_usage"}
ref $$body{"stream_options"} eq "HASH" $$body{"stream_options"}{"include_usage"}
Truth table66%2/3
A and B
A= ref $$body{"stream_options"} eq "HASH"B= $$body{"stream_options"}{"include_usage"}
ABresult
0X0
100
111
334 13 my $events = join( '', map { 'data: '.$self->json->encode($_)."\n\n" } @$chunks )."data: [DONE]\n\n";
335 13 my $response = HTTP::Response->new( 200, 'OK',
336 [ 'Content-Type' => 'text/event-stream', 'Cache-Control' => 'no-cache' ], $events );
337 13 $response->request($request);
338 13 return $response;
339 }
340  
341 130 ▶sub virtual_reply {
Subroutine virtual_reply: called CC=11 SCAR=24.0
Pod documented
342 130 my ( $self, $method, $path, $content ) = @_;
343 130 ▶ unless ( uc($method) eq 'POST' && $path =~ m{/chat/completions\z} ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (uc $method eq "POST" and $path =~ m[/chat/completions\z]) 1 129 130
Condition66%2/3
uc $method eq "POST" and $path =~ m[/chat/completions\z]
!ll&&!rl&&r
10129
MC/DC50%1/2
uc $method eq "POST" and $path =~ m[/chat/completions\z]
uc $method eq "POST" $path =~ m[/chat/completions\z]
Truth table66%2/3
A and B
A= uc $method eq "POST"B= $path =~ m[/chat/completions\z]
ABresult
0X0
100
111
344 1 return { code => 404, message => 'Not Found',
345 content => "answers only chat completions, not $method $path" };
346 }
347 129 my $view = $self->_request_view( $self->json->decode($content) );
348 129 push @{ $self->requests }, $view;
349 129 my ( $reaction, $usage, $error );
350 129 ▶ eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { $reaction = $self->_reaction_for($view); $usage = $self->_usage_for($view, $reaction) if $reaction and not $$reaction{"error"}; 1 } } or $error = $@ || "unknown error" 126 3 129
351 129 $reaction = $self->_reaction_for($view);
352 127 ▶ $usage = $self->_usage_for( $view, $reaction ) if $reaction && !$reaction->{error};
Branch: 1 branch
BranchTrueFalseTotal
if $reaction and not $$reaction{"error"} 114 13 127
Condition100%3/3
$reaction and not $$reaction{"error"}
!ll&&!rl&&r
58114
MC/DC100%2/2
$reaction and not $$reaction{"error"}
$reaction not $$reaction{"error"}
Truth table100%3/3
A and not(B)
A= $reactionB= not $$reaction{"error"}
ABresult
0X0
100
111
353 126 ▶ 1;
Condition50%1/2
$@ || 'unknown error'
l!l
30
MC/DC0%0/1
$@ || 'unknown error'
$@
Truth table50%1/2
A
A= $@
Aresult
11
00
354 } or $error = $@ || 'unknown error';
355 129 ▶ if ( defined $error ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $error) 3 126 129
356 3 $error =~ s/\s+\z//;
357 3 return { code => 500, message => 'Reaction Failed', content => $error };
358 }
359 126 ▶ return { code => 500, message => 'No Reaction', content => $self->_no_reaction_message($view) }
Branch: 1 branch
BranchTrueFalseTotal
unless $reaction 5 121 126
360 unless $reaction;
361 121 ▶ if ( my $failure = $reaction->{error} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $failure = $$reaction{"error"}) 8 113 121
362 return { code => $failure->{status}, message => HTTP::Status::status_message( $failure->{status} ) // 'Error',
363 8 ▶ content => $failure->{message} };
Condition50%1/2
&HTTP::Status::status_message($$failure{"status"}) // "Error"
l!l
80
MC/DC0%0/1
&HTTP::Status::status_message($$failure{"status"}) // "Error"
&HTTP::Status::status_message($$failure{"status"})
Truth table50%1/2
A
A= &HTTP::Status::status_message($$failure{"status"})
Aresult
11
00
364 }
365 113 return { code => 200, message => 'OK', content => $self->_completion( $view, $reaction, $usage ) };
366 }
367  
368  
369 20 ▶sub virtual_stream_chunks {
Subroutine virtual_stream_chunks: called CC=6 SCAR=17.9
Pod documented
370 20 my ( $self, $completion, %opts ) = @_;
371 20 my $choice = $completion->{choices}[0];
372 20 my $message = $choice->{message};
373 my %base = (
374 id => $completion->{id},
375 object => 'chat.completion.chunk',
376 created => $completion->{created},
377 model => $completion->{model},
378 20 );
379 20 my @deltas = map { { content => $_ } } $self->_stream_pieces( $message->{content} );
380 20 ▶ my $tool_calls = $message->{tool_calls} // [];
Condition100%2/2
$$message{"tool_calls"} // []
l!l
614
MC/DC100%1/1
$$message{"tool_calls"} // []
$$message{"tool_calls"}
Truth table100%2/2
A
A= $$message{"tool_calls"}
Aresult
11
00
381 20 for my $index ( 0 .. $#$tool_calls ) {
382 8 my $call = $tool_calls->[$index];
383 push @deltas, { tool_calls => [ {
384 index => $index,
385 id => $call->{id},
386 type => $call->{type},
387 8 function => { name => $call->{function}{name}, arguments => '' },
388 } ] };
389 18 push @deltas, map { { tool_calls => [ { index => $index, function => { arguments => $_ } } ] } }
390 8 $self->_stream_pieces( $call->{function}{arguments} );
391 }
392 20 ▶ push @deltas, { content => '' } unless @deltas;
Branch: 1 branch
BranchTrueFalseTotal
unless @deltas 0 20 20
393 20 $deltas[0] = { role => 'assistant', %{ $deltas[0] } };
394 20 my @chunks = map { { %base, choices => [ { index => 0, delta => $_ } ] } } @deltas;
395 20 push @chunks, { %base, choices => [ { index => 0, delta => {}, finish_reason => $choice->{finish_reason} } ] };
396 push @chunks, { %base, choices => [], usage => $completion->{usage} }
397 20 ▶ if $opts{include_usage} && $completion->{usage};
Branch: 1 branch
BranchTrueFalseTotal
if $opts{"include_usage"} and $$completion{"usage"} 8 12 20
Condition100%3/3
$opts{"include_usage"} and $$completion{"usage"}
!ll&&!rl&&r
578
MC/DC100%2/2
$opts{"include_usage"} and $$completion{"usage"}
$opts{"include_usage"} $$completion{"usage"}
Truth table100%3/3
A and B
A= $opts{"include_usage"}B= $$completion{"usage"}
ABresult
0X0
100
111
398 20 return \@chunks;
399 }
400  
401  
402 # The text in pieces of stream_chunk_size characters; none for an empty text.
403 28 ▶sub _stream_pieces {
Subroutine _stream_pieces: called CC=3 SCAR=11.0
404 28 my ( $self, $text ) = @_;
405 28 ▶ return () unless defined $text && length $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text and length $text 5 23 28
Condition66%2/3
defined $text and length $text
!ll&&!rl&&r
5023
MC/DC50%1/2
defined $text and length $text
defined $text length $text
Truth table66%2/3
A and B
A= defined $textB= length $text
ABresult
0X0
100
111
406 23 my $size = $self->stream_chunk_size;
407 23 return $text =~ /(.{1,$size})/gs;
408 }
409  
410 # The reply's usage block (see USAGE): the reaction's, else default_usage's,
411 # else none. total_tokens is added when the wire would carry it.
412 114 ▶sub _usage_for {
Subroutine _usage_for: called CC=11 SCAR=24.0
413 114 my ( $self, $view, $reaction ) = @_;
414 114 my $usage = $reaction->{usage};
415 114 ▶ if ( !$usage && $self->has_default_usage ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $usage and $self->has_default_usage) 6 108 114
Condition100%3/3
not $usage and $self->has_default_usage
!ll&&!rl&&r
19896
MC/DC100%2/2
not $usage and $self->has_default_usage
not $usage $self->has_default_usage
Truth table100%3/3
not(A) and B
A= not $usageB= $self->has_default_usage
ABresult
0X0
100
111
416 6 $usage = $self->default_usage;
417 6 ▶ if ( ref $usage eq 'CODE' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $usage eq "CODE") 4 2 6
418 4 my %data = ( answer => $reaction->{answer}, tool_calls => $reaction->{tool_calls} );
419 4 $usage = $usage->( $view, \%data );
420 4 ▶ return unless defined $usage;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $usage 1 3 4
421 3 ▶ croak ref($self).': default_usage returned '.( ref $usage || 'a non-reference' ).', not a HashRef or undef'
Branch: 1 branch
BranchTrueFalseTotal
unless ref $usage eq "HASH" 1 2 3
Condition50%1/2
ref $usage || 'a non-reference'
l!l
01
MC/DC0%0/1
ref $usage || 'a non-reference'
ref $usage
Truth table50%1/2
A
A= ref $usage
Aresult
11
00
422 unless ref $usage eq 'HASH';
423 }
424 }
425 112 ▶ return unless $usage;
Branch: 1 branch
BranchTrueFalseTotal
unless $usage 89 23 112
426 23 my %usage = %$usage;
427 $usage{total_tokens} = $usage{prompt_tokens} + $usage{completion_tokens}
428 if !defined $usage{total_tokens}
429 23 ▶ && looks_like_number( $usage{prompt_tokens} ) && looks_like_number( $usage{completion_tokens} );
Branch: 1 branch
BranchTrueFalseTotal
if not defined $usage{"total_tokens"} and &looks_like_number($usage{"prompt_tokens"}) and &looks_like_number($usage{"completion_tokens"}) 22 1 23
Condition66%4/6
not defined $usage{"total_tokens"} and &looks_like_number($usage{"prompt_tokens"}) and &looks_like_number($usage{"completion_tokens"})
!ll&&!rl&&r
1022
not defined $usage{"total_tokens"} and &looks_like_number($usage{"prompt_tokens"})
!ll&&!rl&&r
1022
MC/DC33%1/3
not defined $usage{"total_tokens"} and &looks_like_number($usage{"prompt_tokens"}) and &looks_like_number($usage{"completion_tokens"})
not defined $usage{"total_tokens"} &looks_like_number($usage{"prompt_tokens"}) &looks_like_number($usage{"completion_tokens"})
Truth table50%2/4
not(A) and B and C
A= not defined $usage{"total_tokens"}B= &looks_like_number($usage{"prompt_tokens"})C= &looks_like_number($usage{"completion_tokens"})
ABCresult
0XX0
10X0
1100
1111
430 23 return \%usage;
431 }
432  
433 # $content is a completion body (JSON) or an error text (text/plain).
434 97 ▶sub _virtual_http_response {
Subroutine _virtual_http_response: called CC=2 SCAR=6.9
435 97 my ( $self, $request, $code, $message, $content ) = @_;
436 97 ▶ my $response = ref $content
Branch: 1 branch
BranchTrueFalseTotal
ref $content ? : 83 14 97
437 ? HTTP::Response->new( $code, $message, [ 'Content-Type' => 'application/json' ], $self->json->encode($content) )
438 : HTTP::Response->new( $code, $message, [ 'Content-Type' => 'text/plain; charset=utf-8' ], Encode::encode( 'UTF-8', $content ) );
439 97 $response->request($request);
440 97 return $response;
441 }
442  
443 # What the rules see of a request (documented under "The request").
444 129 ▶sub _request_view {
Subroutine _request_view: called CC=15 SCAR=28.4
445 129 my ( $self, $body ) = @_;
446 129 ▶ my @messages = @{ $body->{messages} // [] };
Condition50%1/2
$$body{"messages"} // []
l!l
1290
MC/DC0%0/1
$$body{"messages"} // []
$$body{"messages"}
Truth table50%1/2
A
A= $$body{"messages"}
Aresult
11
00
447 129 ▶ my $last_role = @messages ? $messages[-1]{role} // '' : '';
Branch: 1 branch
BranchTrueFalseTotal
@messages ? : 129 0 129
Condition50%1/2
$messages[-1]{"role"} // ""
l!l
1290
MC/DC0%0/1
$messages[-1]{"role"} // ""
$messages[-1]{"role"}
Truth table50%1/2
A
A= $messages[-1]{"role"}
Aresult
11
00
448 129 ▶ my ($last_user) = grep { ( $_->{role} // '' ) eq 'user' } reverse @messages;
Condition50%1/2
$$_{"role"} // ""
l!l
1720
MC/DC0%0/1
$$_{"role"} // ""
$$_{"role"}
Truth table50%1/2
A
A= $$_{"role"}
Aresult
11
00
449 20 ▶ my %tool_names = map { ( $_->{id} // '' ) => $_->{function}{name} }
Condition50%1/2
$$_{"id"} // ""
l!l
200
MC/DC0%0/1
$$_{"id"} // ""
$$_{"id"}
Truth table50%1/2
A
A= $$_{"id"}
Aresult
11
00
450 20 ▶ map { @{ $_->{tool_calls} // [] } }
Condition100%2/2
$$_{"tool_calls"} // []
l!l
182
MC/DC100%1/1
$$_{"tool_calls"} // []
$$_{"tool_calls"}
Truth table100%2/2
A
A= $$_{"tool_calls"}
Aresult
11
00
451 129 ▶ grep { ( $_->{role} // '' ) eq 'assistant' } @messages;
Condition50%1/2
$$_{"role"} // ""
l!l
1720
MC/DC0%0/1
$$_{"role"} // ""
$$_{"role"}
Truth table50%1/2
A
A= $$_{"role"}
Aresult
11
00
452 129 my @results;
453 129 my $index = $#messages;
454 129 ▶ while ( $index >= 0 && ( $messages[$index]{role} // '' ) eq 'tool' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($index >= 0 and ($messages[$index]{"role"} // "") eq "tool") 20 129 149
Condition60%3/5
$index >= 0 and ($messages[$index]{"role"} // "") eq "tool"
!ll&&!rl&&r
012920
$messages[$index]{"role"} // ""
l!l
1490
MC/DC0%0/2
$index >= 0 and ($messages[$index]{"role"} // "") eq "tool"
$index >= 0 $messages[$index]{"role"}
Truth table33%1/3
A and B
A= $index >= 0B= $messages[$index]{"role"}
ABresult
0X0
100
111
455 20 unshift @results, $messages[ $index-- ];
456 }
457 return {
458 129 ▶ number => scalar @{ $self->requests } + 1,
Branch: 2 branches
BranchTrueFalseTotal
$last_role eq 'user' ? : 110 19 129
$last_user ? : 129 0 129
459 model => $body->{model},
460 messages => \@messages,
461 text => $last_role eq 'user' ? $self->_message_text( $messages[-1] ) : undef,
462 last_user_text => $last_user ? $self->_message_text($last_user) : undef,
463 tool_results => [ map { {
464 id => $_->{tool_call_id},
465 20 ▶ name => $tool_names{ $_->{tool_call_id} // '' },
Condition75%3/4
$$_{"tool_call_id"} // ""
l!l
200
$$body{"tools"} // []
l!l
19110
MC/DC0%0/1
$$_{"tool_call_id"} // ""
$$_{"tool_call_id"}
MC/DC100%1/1
$$body{"tools"} // []
$$body{"tools"}
Truth table50%1/2
A
A= $$_{"tool_call_id"}
Aresult
11
00
Truth table100%2/2
A
A= $$body{"tools"}
Aresult
11
00
466 content => $self->_message_text($_),
467 } } @results ],
468 129 tools => $body->{tools} // [],
469 body => $body,
470 };
471 }
472  
473 259 ▶sub _message_text {
Subroutine _message_text: called CC=9 SCAR=28.3
474 259 my ( $self, $message ) = @_;
475 259 my $content = $message->{content};
476 259 ▶ return $content // '' unless ref $content eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $content eq "ARRAY" 257 2 259
Condition50%1/2
$content // ""
l!l
2570
MC/DC0%0/1
$content // ""
$content
Truth table50%1/2
A
A= $content
Aresult
11
00
477 2 ▶ return join "\n", map { ref $_ ? $_->{text} // () : $_ // () }
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 2 0 2
Condition16%1/6
$$_{"text"} // ()
l!l&&r!l&&!r
200
$_ // ()
l!l&&r!l&&!r
000
MC/DC0%0/2
$$_{"text"} // ()
$$_{"text"} ()
MC/DC0%0/2
$_ // ()
$_ ()
Truth table33%1/3
A // B
A= $$_{"text"}B= ()
ABresult
1X1
011
000
Truth table0%0/3
A // B
A= $_B= ()
ABresult
1X1
011
000
478 2 ▶ grep { !ref $_ || ( ref $_ eq 'HASH' && ( $_->{type} // '' ) eq 'text' ) } @$content;
Condition37%3/8
!ref($_) || ref $_ eq 'HASH' && ($$_{'type'} // '') eq 'text'
l!l&&r!l&&!r
020
ref $_ eq "HASH" and ($$_{"type"} // "") eq "text"
!ll&&!rl&&r
002
$$_{"type"} // ""
l!l
20
MC/DC0%0/3
!ref($_) || ref $_ eq 'HASH' && ($$_{'type'} // '') eq 'text'
!ref($_) ref $_ eq "HASH" $$_{"type"}
Truth table25%1/4
not(A) || B and C
A= !ref($_)B= ref $_ eq "HASH"C= $$_{"type"}
ABCresult
1XX1
0111
00X0
0100
479 }
480  
481 129 ▶sub _reaction_for {
Subroutine _reaction_for: called CC=6 SCAR=17.9
482 129 my ( $self, $view ) = @_;
483 129 ▶ if ( $self->has_script ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_script) { } 11 118 129
484 11 my $position = $self->_script_position;
485 11 ▶ if ( $position < @{ $self->script } ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($position < @{$self->script;}) 8 3 11
486 8 $self->_script_position( $position + 1 );
487 8 return $self->_resolve_reaction( $self->script->[$position], $view, [], 'script entry '.( $position + 1 ) );
488 }
489 }
490 else {
491 118 my @rules = @{ $self->rules };
492 118 my $number = 0;
493 118 ▶ while ( my ( $trigger, $reaction ) = splice @rules, 0, 2 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = splice(@rules, 0, 2)) 242 24 266
494 242 $number++;
495 242 ▶ my $captures = $self->_match_trigger( $trigger, $view ) or next;
Branch: 1 branch
BranchTrueFalseTotal
my $captures = $self->_match_trigger($trigger, $view) or next 94 148 242
496 94 return $self->_resolve_reaction( $reaction, $view, $captures, "rule $number" );
497 }
498 }
499 27 ▶ return $self->_resolve_reaction( $self->fallback, $view, [], 'fallback' ) if $self->has_fallback;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_fallback 22 5 27
500 5 return;
501 }
502  
503 5 ▶sub _no_reaction_message {
Subroutine _no_reaction_message: called CC=5 SCAR=16.2
504 5 my ( $self, $view ) = @_;
505 5 ▶ my $what = $self->has_script ? 'the script has run out' : 'no rule matches';
Branch: 1 branch
BranchTrueFalseTotal
$self->has_script ? : 1 4 5
506 my $last = defined $view->{text} ? "the user message '$view->{text}'"
507 1 : @{ $view->{tool_results} } ? 'the tool result of '
508 5 ▶ .join( ', ', map { $_->{name} // 'an unknown call' } @{ $view->{tool_results} } )
Branch: 2 branches
BranchTrueFalseTotal
defined $$view{'text'} ? : 4 1 5
@{$$view{'tool_results'};} ? : 1 0 1
Condition50%1/2
$$_{"name"} // "an unknown call"
l!l
10
MC/DC0%0/1
$$_{"name"} // "an unknown call"
$$_{"name"}
Truth table50%1/2
A
A= $$_{"name"}
Aresult
11
00
509 : 'a conversation that does not end in a user message or a tool result';
510 5 return $what.' and no fallback is set (request '.$view->{number}.", last message: $last)";
511 }
512  
513 # Captures (an ArrayRef, empty for none) when the trigger matches, else undef.
514 242 ▶sub _match_trigger {
Subroutine _match_trigger: called CC=5 SCAR=16.1
515 242 my ( $self, $trigger, $view ) = @_;
516 242 ▶ return $self->_match_after( $trigger->{after}, $view ) if ref $trigger eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $trigger eq "HASH" 28 214 242
517 214 ▶ return $trigger->($view) ? [] : undef if ref $trigger eq 'CODE';
Branch: 2 branches
BranchTrueFalseTotal
if ref $trigger eq "CODE" 3 211 214
&$trigger($view) ? : 1 2 3
518 211 ▶ return undef unless defined $view->{text};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$view{"text"} 32 179 211
519 179 return $self->_match_value( $trigger, $view->{text} );
520 }
521  
522 28 ▶sub _match_after {
Subroutine _match_after: called CC=4 SCAR=13.9
523 28 my ( $self, $match, $view ) = @_;
524 28 for my $result ( @{ $view->{tool_results} } ) {
525 26 ▶ my $tool = $self->_match_value( $match->{tool}, $result->{name} ) or next;
Branch: 1 branch
BranchTrueFalseTotal
my $tool = $self->_match_value($$match{"tool"}, $$result{"name"}) or next 15 11 26
526 15 ▶ my $text = $self->_match_value( $match->{result}, $result->{content} ) or next;
Branch: 1 branch
BranchTrueFalseTotal
my $text = $self->_match_value($$match{"result"}, $$result{"content"}) or next 15 0 15
527 15 return [ @$tool, @$text ];
528 }
529 13 return undef;
530 }
531  
532 # A string matcher compares exactly, a Regexp matches; undef matches anything.
533 220 ▶sub _match_value {
Subroutine _match_value: called CC=7 SCAR=19.5
534 220 my ( $self, $matcher, $value ) = @_;
535 220 ▶ return [] unless defined $matcher;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $matcher 19 201 220
536 201 ▶ return undef unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 201 201
537 201 ▶ return $value eq $matcher ? [] : undef unless ref $matcher;
Branch: 2 branches
BranchTrueFalseTotal
unless ref $matcher 163 38 201
$value eq $matcher ? : 73 90 163
538 38 ▶ my @captures = $value =~ $matcher or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my(@captures) = $value =~ /$matcher/ or return undef 16 22 38
539 16 ▶ return $#+ ? \@captures : [];
Branch: 1 branch
BranchTrueFalseTotal
$#+ ? : 14 2 16
540 }
541  
542 124 ▶sub _resolve_reaction {
Subroutine _resolve_reaction: called CC=3 SCAR=11.0
543 124 my ( $self, $reaction, $view, $captures, $where ) = @_;
544 124 ▶ if ( ref $reaction eq 'CODE' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $reaction eq "CODE") 35 89 124
545 35 $reaction = $reaction->( $view, @$captures );
546 34 ▶ croak ref($self).": the sub of $where returned a sub, not a reaction" if ref $reaction eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $reaction eq "CODE" 0 34 34
547 34 $where = "the reply of the sub of $where";
548 }
549 123 return $self->_normalize_reaction( $reaction, $where );
550 }
551  
552 # The reaction as an OpenAI chat completion body.
553 113 ▶sub _completion {
Subroutine _completion: called CC=5 SCAR=16.2
554 113 my ( $self, $view, $reaction, $usage ) = @_;
555 my @tool_calls = map {
556 40 my ( $name, $arguments ) = @$_;
557 40 push @{ $self->calls }, [ $name, $arguments ];
558 {
559 40 id => 'call_virtual_'.scalar @{ $self->calls },
560 type => 'function',
561 function => { name => $name, arguments => $self->encode_json_text($arguments) },
562 };
563 113 } @{ $reaction->{tool_calls} };
564 return {
565 id => 'virtual-'.$view->{number},
566 object => 'chat.completion',
567 created => time,
568 model => $view->{model} // $self->chat_model,
569 choices => [ {
570 index => 0,
571 message => {
572 role => 'assistant',
573 content => $reaction->{answer},
574 113 ▶ @tool_calls ? ( tool_calls => \@tool_calls ) : (),
Branch: 3 branches
BranchTrueFalseTotal
@tool_calls ? : 33 80 113
@tool_calls ? : 33 80 113
$usage ? : 23 90 113
Condition33%1/3
$$view{"model"} // $self->chat_model
l!l&&r!l&&!r
11300
MC/DC0%0/2
$$view{"model"} // $self->chat_model
$$view{"model"} $self->chat_model
Truth table33%1/3
A // B
A= $$view{"model"}B= $self->chat_model
ABresult
1X1
011
000
575 },
576 finish_reason => @tool_calls ? 'tool_calls' : 'stop',
577 } ],
578 $usage ? ( usage => $usage ) : (),
579 };
580 }
581  
582 10 __PACKAGE__->meta->make_immutable;
583  
584  
585 10 1;
586  
587 __END__
« blib/lib/Langertha/CachedContent.pm ↑ Summary blib/lib/Langertha/RateLimit.pm »