blib/lib/Langertha/Engine/LMStudio.pm

filter: Statementstmt 85.0% 187 / 220 Branchbran 64.1% 109 / 170 Conditioncond 48.0% 48 / 100 MC/DCmcdc 22.0% 11 / 50 Subroutinesub 85.7% 36 / 42 Podpod 22.2% 4 / 18 totaltotal 65.8% 395 / 600 CC 133 SCAR 35.7
CC
133
Cov
70%
list_models
272.0
_extract_text
31.4
parse_stream_chunk
23.6
CRAP 35.4
« blib/lib/Langertha/Tool.pm ↑ Summary blib/lib/Langertha/Role/Chat.pm »
1 package Langertha::Engine::LMStudio;
2 # ABSTRACT: LM Studio native REST API
3 15 our $VERSION = '0.505';
4 15 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 15 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
6 15 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 15 ▶use File::ShareDir::ProjectDistDir qw( :all );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 15 ▶use Module::Runtime qw( use_module );
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 15 extends 'Langertha::Engine::Remote';
11  
12 15 with map { 'Langertha::Role::'.$_ } qw(
13 OpenAPI
14 Models
15 Temperature
16 ResponseSize
17 ContextSize
18 SystemPrompt
19 Streaming
20 Chat
21 ImageInput
22 );
23  
24 # image_input (k266, ADR 0019): self-hosted: the served model is launch state
25 # the client cannot see, so no static claim. A layer-3 catch-all rather than a
26 # layer-2 delete, so a fact probed from /api/v1/models (capabilities.vision)
27 # can answer per model (ADR 0032).
28 52 ▶sub model_capability_corrections {
Subroutine model_capability_corrections: called CC=1 SCAR=0.0
Pod undocumented
29 52 return ( qr/\A/ => { image_input => 0 } );
30 }
31  
32 5 ▶sub model_metadata_format { 'lmstudio' }
Subroutine model_metadata_format: called CC=1 SCAR=0.0
Pod undocumented
33 5 ▶sub model_metadata_url {
Subroutine model_metadata_url: called CC=1 SCAR=0.0
Pod undocumented
34 5 my $url = $_[0]->url;
35 5 $url =~ s{/\z}{};
36 5 return $url . '/api/v1/models';
37 }
38  
39  
40 has '+url' => (
41 lazy => 1,
42 4 ▶ default => sub { 'http://localhost:1234' },
Subroutine __ANON__: called CC=1 SCAR=0.0
43 15 );
44  
45 15 has api_key => (
46 is => 'ro',
47 lazy_build => 1,
48 );
49  
50 24 ▶sub _build_api_key {
Subroutine _build_api_key: called CC=1 SCAR=0.0
51 24 return $ENV{LANGERTHA_LMSTUDIO_API_KEY};
52 }
53  
54  
55 32 ▶sub update_request {
Subroutine update_request: called CC=2 SCAR=6.9
Pod undocumented
56 32 my ( $self, $request ) = @_;
57 32 my $key = $self->api_key;
58 32 ▶ $request->header('Authorization', 'Bearer '.$key) if defined $key;
Branch: 1 branch
BranchTrueFalseTotal
if defined $key 1 31 32
59 }
60  
61 2 ▶sub default_model { 'default' }
Subroutine default_model: called CC=1 SCAR=0.0
Pod undocumented
62  
63 # Native /api/v1/chat input takes { type => 'image', data_url } items carrying a
64 # base64 data URL only (lmstudio.ai/docs/developer/rest/chat), karr k267.
65 10 ▶sub content_format { 'lmstudio' }
Subroutine content_format: called CC=1 SCAR=0.0
Pod undocumented
66 7 ▶sub _content_inline_images_only { 1 }
Subroutine _content_inline_images_only: called CC=1 SCAR=0.0
67 56 ▶sub default_response_size { 1024 }
Subroutine default_response_size: called CC=1 SCAR=0.0
Pod undocumented
68  
69 # api_key_env derives LANGERTHA_LMSTUDIO_API_KEY, the variable _build_api_key
70 # reads: a secured LM Studio needs it, the default local server does not.
71 1 ▶sub api_key_required { 0 }
Subroutine api_key_required: called CC=1 SCAR=0.0
Pod documented
72  
73 0 ▶sub openapi_file { yaml => dist_file('Langertha','lmstudio.yaml') };
Subroutine openapi_file: not called CC=1 SCAR=6.9
Pod documented
74  
75  
76 19 ▶sub _build_openapi_operations {
Subroutine _build_openapi_operations: called CC=1 SCAR=0.0
77 19 return use_module('Langertha::Spec::LMStudio')->data;
78 }
79  
80 19 ▶sub _build_supported_operations {[qw(
Subroutine _build_supported_operations: called CC=1 SCAR=0.0
81 chat
82 listModels
83 )]}
84  
85 3 ▶sub openai {
Subroutine openai: called CC=5 SCAR=16.6
Pod documented
86 3 my ( $self, %args ) = @_;
87  
88 3 require Langertha::Engine::LMStudioOpenAI;
89  
90 3 my $url = $self->url;
91 3 $url =~ s{/\z}{};
92 3 ▶ my $api_key = defined $self->api_key ? $self->api_key : 'lmstudio';
Branch: 1 branch
BranchTrueFalseTotal
defined $self->api_key ? : 1 2 3
93  
94 return Langertha::Engine::LMStudioOpenAI->new(
95 url => $url.'/v1',
96 model => $self->model,
97 api_key => $api_key,
98 # The pin carries over while the url stays on its host (karr k375).
99 3 ▶ $self->_connect_address_for( exists $args{url} ? $args{url} : $url.'/v1' ),
Branch: 3 branches
BranchTrueFalseTotal
exists $args{'url'} ? : 0 3 3
$self->has_system_prompt ? : 0 3 3
$self->has_temperature ? : 0 3 3
100 $self->has_system_prompt ? ( system_prompt => $self->system_prompt ) : (),
101 $self->has_temperature ? ( temperature => $self->temperature ) : (),
102 %args,
103 );
104 }
105  
106  
107 3 ▶sub anthropic {
Subroutine anthropic: called CC=5 SCAR=16.8
Pod documented
108 3 my ( $self, %args ) = @_;
109  
110 3 require Langertha::Engine::LMStudioAnthropic;
111  
112 3 ▶ my $api_key = defined $self->api_key ? $self->api_key : 'lmstudio';
Branch: 1 branch
BranchTrueFalseTotal
defined $self->api_key ? : 1 2 3
113  
114 return Langertha::Engine::LMStudioAnthropic->new(
115 url => $self->url,
116 model => $self->model,
117 api_key => $api_key,
118 3 ▶ $self->_connect_address_for( exists $args{url} ? $args{url} : $self->url ),
Branch: 3 branches
BranchTrueFalseTotal
exists $args{'url'} ? : 0 3 3
$self->has_system_prompt ? : 0 3 3
$self->has_temperature ? : 0 3 3
119 $self->has_system_prompt ? ( system_prompt => $self->system_prompt ) : (),
120 $self->has_temperature ? ( temperature => $self->temperature ) : (),
121 %args,
122 );
123 }
124  
125  
126 5 ▶sub _normalize_usage {
Subroutine _normalize_usage: called CC=14 SCAR=28.1
127 5 my ( $usage ) = @_;
128 5 ▶ return undef unless $usage && ref $usage eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless $usage and ref $usage eq "HASH" 0 5 5
Condition33%1/3
$usage and ref $usage eq "HASH"
!ll&&!rl&&r
005
MC/DC0%0/2
$usage and ref $usage eq "HASH"
$usage ref $usage eq "HASH"
Truth table33%1/3
A and B
A= $usageB= ref $usage eq "HASH"
ABresult
0X0
100
111
129  
130 5 my %normalized;
131 $normalized{prompt_tokens} = $usage->{prompt_tokens}
132 5 ▶ if defined $usage->{prompt_tokens};
Branch: 1 branch
BranchTrueFalseTotal
if defined $$usage{"prompt_tokens"} 0 5 5
133 $normalized{completion_tokens} = $usage->{completion_tokens}
134 5 ▶ if defined $usage->{completion_tokens};
Branch: 1 branch
BranchTrueFalseTotal
if defined $$usage{"completion_tokens"} 0 5 5
135 $normalized{total_tokens} = $usage->{total_tokens}
136 5 ▶ if defined $usage->{total_tokens};
Branch: 1 branch
BranchTrueFalseTotal
if defined $$usage{"total_tokens"} 0 5 5
137  
138 $normalized{prompt_tokens} = $usage->{input_tokens}
139 5 ▶ if !defined($normalized{prompt_tokens}) && defined($usage->{input_tokens});
Branch: 1 branch
BranchTrueFalseTotal
if not defined $normalized{"prompt_tokens"} and defined $$usage{"input_tokens"} 4 1 5
Condition66%2/3
not defined $normalized{"prompt_tokens"} and defined $$usage{"input_tokens"}
!ll&&!rl&&r
014
MC/DC50%1/2
not defined $normalized{"prompt_tokens"} and defined $$usage{"input_tokens"}
not defined $normalized{"prompt_tokens"} defined $$usage{"input_tokens"}
Truth table66%2/3
not(A) and B
A= not defined $normalized{"prompt_tokens"}B= defined $$usage{"input_tokens"}
ABresult
0X0
100
111
140 $normalized{completion_tokens} = $usage->{output_tokens}
141 5 ▶ if !defined($normalized{completion_tokens}) && defined($usage->{output_tokens});
Branch: 1 branch
BranchTrueFalseTotal
if not defined $normalized{"completion_tokens"} and defined $$usage{"output_tokens"} 4 1 5
Condition66%2/3
not defined $normalized{"completion_tokens"} and defined $$usage{"output_tokens"}
!ll&&!rl&&r
014
MC/DC50%1/2
not defined $normalized{"completion_tokens"} and defined $$usage{"output_tokens"}
not defined $normalized{"completion_tokens"} defined $$usage{"output_tokens"}
Truth table66%2/3
not(A) and B
A= not defined $normalized{"completion_tokens"}B= defined $$usage{"output_tokens"}
ABresult
0X0
100
111
142  
143 5 ▶ if (!defined($normalized{total_tokens})
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $normalized{"total_tokens"} and defined $normalized{"prompt_tokens"} and defined $normalized{"completion_tokens"}) 4 1 5
Condition66%4/6
not defined $normalized{"total_tokens"} and defined $normalized{"prompt_tokens"} and defined $normalized{"completion_tokens"}
!ll&&!rl&&r
104
not defined $normalized{"total_tokens"} and defined $normalized{"prompt_tokens"}
!ll&&!rl&&r
014
MC/DC33%1/3
not defined $normalized{"total_tokens"} and defined $normalized{"prompt_tokens"} and defined $normalized{"completion_tokens"}
not defined $normalized{"total_tokens"} defined $normalized{"prompt_tokens"} defined $normalized{"completion_tokens"}
Truth table50%2/4
not(A) and B and C
A= not defined $normalized{"total_tokens"}B= defined $normalized{"prompt_tokens"}C= defined $normalized{"completion_tokens"}
ABCresult
0XX0
10X0
1100
1111
144 && defined($normalized{prompt_tokens})
145 && defined($normalized{completion_tokens})) {
146 4 $normalized{total_tokens} = $normalized{prompt_tokens} + $normalized{completion_tokens};
147 }
148  
149 5 ▶ return %normalized ? \%normalized : undef;
Branch: 1 branch
BranchTrueFalseTotal
%normalized ? : 4 1 5
150 }
151  
152 5 ▶sub _extract_text {
Subroutine _extract_text: called CC=11 SCAR=34.5
153 5 my ( $content ) = @_;
154 5 ▶ return '' unless defined $content;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $content 0 5 5
155 5 ▶ return $content unless ref $content;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $content 0 5 5
156  
157 5 ▶ return '' unless ref $content eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $content eq "ARRAY" 0 5 5
158  
159 5 my @parts;
160 5 for my $part (@{$content}) {
161 5 ▶ next unless ref $part eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $part eq "HASH" 0 5 5
162 5 ▶ if (defined $part->{text}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$part{"text"}) 5 0 5
163 5 push @parts, $part->{text};
164 5 next;
165 }
166 0 ▶ if (defined $part->{content} && !ref $part->{content}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$part{"content"} and not ref $$part{"content"}) 0 0 0
Condition0%0/3
defined $$part{"content"} and not ref $$part{"content"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $$part{"content"} and not ref $$part{"content"}
defined $$part{"content"} not ref $$part{"content"}
Truth table0%0/3
A and not(B)
A= defined $$part{"content"}B= not ref $$part{"content"}
ABresult
0X0
100
111
167 0 push @parts, $part->{content};
168 0 next;
169 }
170 0 ▶ if (defined $part->{delta} && !ref $part->{delta}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $$part{"delta"} and not ref $$part{"delta"}) 0 0 0
Condition0%0/3
defined $$part{"delta"} and not ref $$part{"delta"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $$part{"delta"} and not ref $$part{"delta"}
defined $$part{"delta"} not ref $$part{"delta"}
Truth table0%0/3
A and not(B)
A= defined $$part{"delta"}B= not ref $$part{"delta"}
ABresult
0X0
100
111
171 0 push @parts, $part->{delta};
172 0 next;
173 }
174 }
175  
176 5 return join('', @parts);
177 }
178  
179 2 ▶sub _extract_response_text {
Subroutine _extract_response_text: called CC=9 SCAR=24.0
180 2 my ( $data ) = @_;
181 2 ▶ return '' unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 0 2 2
182  
183 2 my @pieces;
184 2 ▶ for my $item (@{$data->{output} // []}) {
Condition50%1/2
$$data{"output"} // []
l!l
20
MC/DC0%0/1
$$data{"output"} // []
$$data{"output"}
Truth table50%1/2
A
A= $$data{"output"}
Aresult
11
00
185 4 ▶ next unless ref $item eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $item eq "HASH" 0 4 4
186 push @pieces, $item->{content}
187 4 ▶ if ($item->{type} // '') eq 'message' && defined $item->{content};
Branch: 1 branch
BranchTrueFalseTotal
if ($$item{"type"} // "") eq "message" and defined $$item{"content"} 2 2 4
Condition60%3/5
($$item{"type"} // "") eq "message" and defined $$item{"content"}
!ll&&!rl&&r
202
$$item{"type"} // ""
l!l
40
MC/DC0%0/2
($$item{"type"} // "") eq "message" and defined $$item{"content"}
$$item{"type"} defined $$item{"content"}
Truth table33%1/3
A and B
A= $$item{"type"}B= defined $$item{"content"}
ABresult
0X0
100
111
188 }
189 2 ▶ return join('', @pieces) if @pieces;
Branch: 1 branch
BranchTrueFalseTotal
if @pieces 2 0 2
190  
191 0 return '';
192 }
193  
194 2 ▶sub _extract_reasoning_text {
Subroutine _extract_reasoning_text: called CC=9 SCAR=22.9
195 2 my ( $data ) = @_;
196 2 ▶ return undef unless ref $data eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $data eq "HASH" 0 2 2
197  
198 2 my @parts;
199 2 ▶ for my $item (@{$data->{output} // []}) {
Condition50%1/2
$$data{"output"} // []
l!l
20
MC/DC0%0/1
$$data{"output"} // []
$$data{"output"}
Truth table50%1/2
A
A= $$data{"output"}
Aresult
11
00
200 4 ▶ next unless ref $item eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $item eq "HASH" 0 4 4
201 push @parts, $item->{content}
202 4 ▶ if ($item->{type} // '') eq 'reasoning' && defined $item->{content};
Branch: 1 branch
BranchTrueFalseTotal
if ($$item{"type"} // "") eq "reasoning" and defined $$item{"content"} 2 2 4
Condition60%3/5
($$item{"type"} // "") eq "reasoning" and defined $$item{"content"}
!ll&&!rl&&r
202
$$item{"type"} // ""
l!l
40
MC/DC0%0/2
($$item{"type"} // "") eq "reasoning" and defined $$item{"content"}
$$item{"type"} defined $$item{"content"}
Truth table33%1/3
A and B
A= $$item{"type"}B= defined $$item{"content"}
ABresult
0X0
100
111
203 }
204 2 ▶ return @parts ? join("\n", @parts) : undef;
Branch: 1 branch
BranchTrueFalseTotal
@parts ? : 1 1 2
205 }
206  
207 # Native /api/v1/chat input is ONE user turn: a string, or an array of content
208 # parts { type => 'text', content } / { type => 'image', data_url }
209 # (lmstudio.ai/docs/developer/rest/chat, corrected in lmstudio-ai/docs 9b8bc20,
210 # karr k268). The items carry no role, so the caller has already cut the
211 # history down to the trailing user turn(s) (_trailing_turns).
212 29 ▶sub _normalize_input {
Subroutine _normalize_input: called CC=14 SCAR=26.7
213 29 my ( $messages ) = @_;
214 29 my @items;
215 29 for my $msg (@{$messages}) {
216 35 ▶ next unless ref $msg eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $msg eq "HASH" 0 35 35
217 35 ▶ next if ($msg->{role} // '') eq 'system';
Branch: 1 branch
BranchTrueFalseTotal
if ($$msg{"role"} // "") eq "system" 2 33 35
Condition50%1/2
$$msg{"role"} // ""
l!l
350
MC/DC0%0/1
$$msg{"role"} // ""
$$msg{"role"}
Truth table50%1/2
A
A= $$msg{"role"}
Aresult
11
00
218 33 ▶ next unless defined $msg->{content};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$msg{"content"} 0 33 33
219 33 ▶ if ( ref $msg->{content} eq 'ARRAY'
Branch: 1 branch
BranchTrueFalseTotal
if (ref $$msg{"content"} eq "ARRAY" and grep {ref $_ eq "HASH" and ($$_{"type"} // "") eq "image";} @{$$msg{"content"};}) 5 28 33
Condition100%3/3
ref $$msg{"content"} eq "ARRAY" and grep {ref $_ eq "HASH" and ($$_{"type"} // "") eq "image";} @{$$msg{"content"};}
!ll&&!rl&&r
2715
MC/DC100%2/2
ref $$msg{"content"} eq "ARRAY" and grep {ref $_ eq "HASH" and ($$_{"type"} // "") eq "image";} @{$$msg{"content"};}
ref $$msg{"content"} eq "ARRAY" grep {ref $_ eq "HASH" and ($$_{"type"} // "") eq "image";} @{$$msg{"content"};}
Truth table100%3/3
A and B
A= ref $$msg{"content"} eq "ARRAY"B= grep {ref $_ eq "HASH" and ($$_{"type"} // "") eq "image";} @{$$msg{"content"};}
ABresult
0X0
100
111
220 10 ▶ && grep { ref $_ eq 'HASH' && ( $_->{type} // '' ) eq 'image' } @{ $msg->{content} } ) {
Condition60%3/5
ref $_ eq 'HASH' && ($$_{'type'} // '') eq 'image'
!ll&&!rl&&r
055
$$_{"type"} // ""
l!l
100
MC/DC0%0/2
ref $_ eq 'HASH' && ($$_{'type'} // '') eq 'image'
ref $_ eq 'HASH' $$_{"type"}
Truth table33%1/3
A && B
A= ref $_ eq 'HASH'B= $$_{"type"}
ABresult
0X0
100
111
221 5 push @items, _input_items_with_images($msg->{content});
222 5 next;
223 }
224 28 ▶ my $content = ref $msg->{content} ? _extract_text($msg->{content}) : $msg->{content};
Branch: 1 branch
BranchTrueFalseTotal
ref $$msg{'content'} ? : 1 27 28
225 28 push @items, {
226 type => 'text',
227 content => $content,
228 };
229 }
230  
231 29 ▶ return '' unless @items;
Branch: 1 branch
BranchTrueFalseTotal
unless @items 0 29 29
232 29 ▶ return $items[0]{content} if @items == 1 && $items[0]{type} eq 'text';
Branch: 1 branch
BranchTrueFalseTotal
if @items == 1 and $items[0]{"type"} eq "text" 20 9 29
Condition100%3/3
@items == 1 and $items[0]{"type"} eq "text"
!ll&&!rl&&r
7220
MC/DC100%2/2
@items == 1 and $items[0]{"type"} eq "text"
@items == 1 $items[0]{"type"} eq "text"
Truth table100%3/3
A and B
A= @items == 1B= $items[0]{"type"} eq "text"
ABresult
0X0
100
111
233 9 return \@items;
234 }
235  
236 # A content array holding image items (Content::Image->to_lmstudio, karr k267):
237 # the images become their own { type => 'image', data_url } input items, in
238 # order, between the text runs around them.
239 5 ▶sub _input_items_with_images {
Subroutine _input_items_with_images: called CC=5 SCAR=16.1
240 5 my ( $parts ) = @_;
241 5 my ( @items, @run );
242 10 ▶ my $flush = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
243 10 ▶ push @items, { type => 'text', content => _extract_text([ @run ]) } if @run;
Branch: 1 branch
BranchTrueFalseTotal
if @run 4 6 10
244 10 @run = ();
245 5 };
246 5 for my $part (@{$parts}) {
247 9 ▶ if ( ref $part eq 'HASH' && ( $part->{type} // '' ) eq 'image' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $part eq 'HASH' and ($$part{'type'} // '') eq 'image') { } 5 4 9
Condition60%3/5
ref $part eq "HASH" and ($$part{"type"} // "") eq "image"
!ll&&!rl&&r
045
$$part{"type"} // ""
l!l
90
MC/DC0%0/2
ref $part eq "HASH" and ($$part{"type"} // "") eq "image"
ref $part eq "HASH" $$part{"type"}
Truth table33%1/3
A and B
A= ref $part eq "HASH"B= $$part{"type"}
ABresult
0X0
100
111
248 5 $flush->();
249 5 push @items, { type => 'image', data_url => $part->{data_url} };
250 }
251 else {
252 4 push @run, $part;
253 }
254 }
255 5 $flush->();
256 5 return @items;
257 }
258  
259 # The native chat endpoint takes no assistant messages ("Include assistant
260 # messages in the request: NO", lmstudio.ai/docs/developer/rest, karr k268):
261 # flattening earlier assistant replies into the input would present them as
262 # user text. Multi-turn on this wire is stateful (store + previous_response_id),
263 # so a history with assistant turns is cut to what follows the last one, with a
264 # carp per request. System messages stay: they go out as system_prompt.
265 29 ▶sub _trailing_turns {
Subroutine _trailing_turns: called CC=6 SCAR=18.0
266 29 my ( $self, $messages ) = @_;
267 29 my $last_assistant;
268 29 for my $i ( 0 .. $#{$messages} ) {
269 56 my $msg = $messages->[$i];
270 56 ▶ $last_assistant = $i if ref $msg eq 'HASH' && ( $msg->{role} // '' ) eq 'assistant';
Branch: 1 branch
BranchTrueFalseTotal
if ref $msg eq "HASH" and ($$msg{"role"} // "") eq "assistant" 9 47 56
Condition60%3/5
ref $msg eq "HASH" and ($$msg{"role"} // "") eq "assistant"
!ll&&!rl&&r
0479
$$msg{"role"} // ""
l!l
560
MC/DC0%0/2
ref $msg eq "HASH" and ($$msg{"role"} // "") eq "assistant"
ref $msg eq "HASH" $$msg{"role"}
Truth table33%1/3
A and B
A= ref $msg eq "HASH"B= $$msg{"role"}
ABresult
0X0
100
111
271 }
272 29 ▶ return $messages unless defined $last_assistant;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $last_assistant 24 5 29
273 5 $self->_langertha_carp( "".( ref $self ).": LM Studio native has no multi-turn "
274 . "history; sending only the trailing user turn(s); use ->openai/->anthropic "
275 . "or previous_response_id" );
276 5 return [ @{$messages}[ $last_assistant + 1 .. $#{$messages} ] ];
277 }
278  
279 29 ▶sub _normalize_system_prompt {
Subroutine _normalize_system_prompt: called CC=7 SCAR=19.7
280 29 my ( $messages ) = @_;
281 29 my @system;
282 29 for my $msg (@{$messages}) {
283 56 ▶ next unless ref $msg eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $msg eq "HASH" 0 56 56
284 56 ▶ next unless ($msg->{role} // '') eq 'system';
Branch: 1 branch
BranchTrueFalseTotal
unless ($$msg{"role"} // "") eq "system" 51 5 56
Condition50%1/2
$$msg{"role"} // ""
l!l
560
MC/DC0%0/1
$$msg{"role"} // ""
$$msg{"role"}
Truth table50%1/2
A
A= $$msg{"role"}
Aresult
11
00
285 5 ▶ next unless defined $msg->{content};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$msg{"content"} 0 5 5
286 5 push @system, $msg->{content};
287 }
288 29 ▶ return @system ? join("\n\n", @system) : undef;
Branch: 1 branch
BranchTrueFalseTotal
@system ? : 5 24 29
289 }
290  
291 # LM Studio's native /api/v1/chat takes neither tools nor tool_choice: its
292 # endpoint table lists "Custom tools: NO" for /api/v1/chat (yes on
293 # /v1/chat/completions, /v1/messages, /v1/responses; lmstudio.ai/docs/
294 # developer/rest), and the tool_call items it returns are server-run
295 # plugin/MCP calls. A tools list croaks, like a ServerTool off its wire, since
296 # no tool call could ever come back; an empty one or undef is simply not sent. A
297 # tool_choice goes through the shared rule (karr k239): this engine claims no
298 # tool_choice_*, so it is dropped, a forced one with a carp.
299 33 ▶sub _lmstudio_tool_kwargs {
Subroutine _lmstudio_tool_kwargs: called CC=5 SCAR=16.1
300 33 my ( $self, $extra ) = @_;
301 33 ▶ if ( exists $extra->{tools} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $$extra{"tools"}) 8 25 33
302 8 my $tools = delete $extra->{tools};
303 8 ▶ croak "".( ref $self ).": LM Studio's native /api/v1/chat takes no tools; use "
Branch: 1 branch
BranchTrueFalseTotal
if defined $tools and ref $tools ne "ARRAY" || @$tools 4 4 8
Condition100%6/6
defined $tools and ref $tools ne "ARRAY" || @$tools
!ll&&!rl&&r
224
ref $tools ne "ARRAY" or @$tools
l!l&&r!l&&!r
222
MC/DC100%3/3
defined $tools and ref $tools ne "ARRAY" || @$tools
defined $tools ref $tools ne "ARRAY" @$tools
Truth table100%4/4
A and B or C
A= defined $toolsB= ref $tools ne "ARRAY"C= @$tools
ABCresult
0XX0
1000
11X1
1011
304 . "Langertha::Engine::LMStudioOpenAI or Langertha::Engine::LMStudioAnthropic "
305 . "(the ->openai / ->anthropic methods) for tool calling"
306 if defined $tools && ( ref $tools ne 'ARRAY' || @$tools );
307 }
308 29 $self->_gate_tool_choice($extra);
309 29 return;
310 }
311  
312 24 ▶sub chat_request {
Subroutine chat_request: called CC=8 SCAR=21.3
Pod undocumented
313 24 my ( $self, $messages, %extra ) = @_;
314 24 $self->_lmstudio_tool_kwargs(\%extra);
315  
316 # Canonical per-request controls (chat_f, karr #46) beat the engine
317 # attributes on a per-key basis; the rest of %extra passes straight through.
318 # LM Studio's native wire only honors temperature and max_output_tokens;
319 # the other canonical controls have no native placement here and are
320 # consumed without being emitted.
321 22 ▶ my $controls = delete $extra{controls} // {};
Condition50%1/2
delete $extra{"controls"} // {}
l!l
022
MC/DC0%0/1
delete $extra{"controls"} // {}
delete $extra{"controls"}
Truth table50%1/2
A
A= delete $extra{"controls"}
Aresult
11
00
322  
323 22 my $system_prompt = _normalize_system_prompt($messages);
324 22 my $input = _normalize_input( $self->_trailing_turns($messages) );
325  
326 return $self->generate_request(
327 'chat',
328 1 ▶ sub { $self->chat_response(shift) },
Subroutine __ANON__: called CC=1 SCAR=0.0
329 model => $self->chat_model,
330 input => $input,
331 $system_prompt ? ( system_prompt => $system_prompt ) : (),
332 exists $controls->{temperature}
333 ? ( temperature => $controls->{temperature} )
334 : ( $self->has_temperature ? ( temperature => $self->temperature ) : () ),
335 exists $controls->{max_tokens}
336 ? ( max_output_tokens => $controls->{max_tokens} )
337 22 ▶ : ( $self->get_response_size ? ( max_output_tokens => $self->get_response_size ) : () ),
Branch: 6 branches
BranchTrueFalseTotal
$system_prompt ? : 4 18 22
exists $$controls{'temperature'} ? : 0 22 22
$self->has_temperature ? : 1 21 22
exists $$controls{'max_tokens'} ? : 0 22 22
$self->get_response_size ? : 22 0 22
$self->has_context_size ? : 1 21 22
338 $self->has_context_size ? ( context_length => $self->get_context_size ) : (),
339 %extra,
340 );
341 }
342  
343 5 ▶sub chat_response {
Subroutine chat_response: called CC=5 SCAR=16.5
344 5 my ( $self, $response ) = @_;
345 5 my $data = $self->parse_response($response);
346 2 my $text = _extract_response_text($data);
347 2 my $thinking = _extract_reasoning_text($data);
348 my $usage = _normalize_usage({
349 input_tokens => $data->{stats}{input_tokens},
350 output_tokens => $data->{stats}{total_output_tokens},
351 2 });
352  
353 2 require Langertha::Response;
354 return Langertha::Response->new(
355 content => $text,
356 raw => $data,
357 $data->{response_id} ? ( id => $data->{response_id} ) : (),
358 2 ▶ $data->{model_instance_id} ? ( model => $data->{model_instance_id} ) : (),
Branch: 4 branches
BranchTrueFalseTotal
$$data{'response_id'} ? : 2 0 2
$$data{'model_instance_id'} ? : 2 0 2
$usage ? : 2 0 2
defined $thinking ? : 1 1 2
359 $usage ? ( usage => $usage ) : (),
360 defined $thinking ? ( thinking => $thinking ) : (),
361 );
362 }
363  
364 1 ▶sub stream_format { 'sse' }
Subroutine stream_format: called CC=1 SCAR=0.0
Pod undocumented
365  
366 9 ▶sub chat_stream_request {
Subroutine chat_stream_request: called CC=8 SCAR=22.8
Pod undocumented
367 9 my ( $self, $messages, %extra ) = @_;
368 9 $self->_lmstudio_tool_kwargs(\%extra);
369  
370 # Canonical per-request controls (chat_f, karr #46) beat the engine
371 # attributes on a per-key basis; the rest of %extra passes straight through.
372 7 ▶ my $controls = delete $extra{controls} // {};
Condition50%1/2
delete $extra{"controls"} // {}
l!l
07
MC/DC0%0/1
delete $extra{"controls"} // {}
delete $extra{"controls"}
Truth table50%1/2
A
A= delete $extra{"controls"}
Aresult
11
00
373  
374 7 my $system_prompt = _normalize_system_prompt($messages);
375 7 my $input = _normalize_input( $self->_trailing_turns($messages) );
376  
377 return $self->generate_request(
378 'chat',
379 0 ▶ sub {},
Subroutine __ANON__: not called CC=1 SCAR=0.0
380 model => $self->chat_model,
381 input => $input,
382 $system_prompt ? ( system_prompt => $system_prompt ) : (),
383 stream => JSON->true,
384 exists $controls->{temperature}
385 ? ( temperature => $controls->{temperature} )
386 : ( $self->has_temperature ? ( temperature => $self->temperature ) : () ),
387 exists $controls->{max_tokens}
388 ? ( max_output_tokens => $controls->{max_tokens} )
389 7 ▶ : ( $self->get_response_size ? ( max_output_tokens => $self->get_response_size ) : () ),
Branch: 6 branches
BranchTrueFalseTotal
$system_prompt ? : 1 6 7
exists $$controls{'temperature'} ? : 0 7 7
$self->has_temperature ? : 0 7 7
exists $$controls{'max_tokens'} ? : 0 7 7
$self->get_response_size ? : 7 0 7
$self->has_context_size ? : 0 7 7
390 $self->has_context_size ? ( context_length => $self->get_context_size ) : (),
391 %extra,
392 );
393 }
394  
395 14 ▶sub parse_stream_chunk {
Subroutine parse_stream_chunk: called CC=19 SCAR=31.6
Pod undocumented
396 14 my ( $self, $data, $event, $state ) = @_;
397 14 ▶ $state //= {};
Condition100%2/2
$state //= {}
l!l
122
MC/DC100%1/1
$state //= {}
$state
Truth table100%2/2
A
A= $state
Aresult
11
00
398  
399 14 require Langertha::Stream::Chunk;
400  
401 # LM Studio native SSE event stream (/api/v1/chat)
402 14 ▶ my $type = $data->{type} // $event // '';
Condition40%2/5
($$data{"type"} // $event) // ""
l!l
140
$$data{"type"} // $event
l!l&&r!l&&!r
1400
MC/DC0%0/2
($$data{"type"} // $event) // ""
$$data{"type"} $event
Truth table33%1/3
A // B
A= $$data{"type"}B= $event
ABresult
1X1
011
000
403 14 ▶ if ($type eq 'error') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "error") 0 14 14
404 0 ▶ my $message = ref $data->{error} eq 'HASH' ? ($data->{error}{message} // 'Unknown LM Studio stream error') : 'Unknown LM Studio stream error';
Branch: 1 branch
BranchTrueFalseTotal
ref $$data{'error'} eq 'HASH' ? : 0 0 0
Condition0%0/2
$$data{"error"}{"message"} // "Unknown LM Studio stream error"
l!l
00
MC/DC0%0/1
$$data{"error"}{"message"} // "Unknown LM Studio stream error"
$$data{"error"}{"message"}
Truth table0%0/2
A
A= $$data{"error"}{"message"}
Aresult
11
00
405 0 croak "LMStudio stream error: $message";
406 }
407 # reasoning.start / reasoning.delta / reasoning.end
408 # (lmstudio.ai/docs/developer/rest/streaming-events): each delta goes onto
409 # the chunk's thinking so aggregate_thinking rebuilds what chat_response
410 # lifts from output[type=reasoning] -- including its "\n" between separate
411 # reasoning blocks. -- karr k334
412 14 ▶ if ($type eq 'reasoning.start') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "reasoning.start") 2 12 14
413 2 ▶ $state->{lmstudio_reasoning_separator} = 1 if $state->{lmstudio_reasoning_seen};
Branch: 1 branch
BranchTrueFalseTotal
if $$state{"lmstudio_reasoning_seen"} 1 1 2
414 2 return undef;
415 }
416 12 ▶ if ($type eq 'reasoning.delta') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "reasoning.delta") 3 9 12
417 3 ▶ return undef unless defined $data->{content};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $$data{"content"} 0 3 3
418 3 my $thinking = $data->{content};
419 3 ▶ $thinking = "\n" . $thinking if delete $state->{lmstudio_reasoning_separator};
Branch: 1 branch
BranchTrueFalseTotal
if delete $$state{"lmstudio_reasoning_separator"} 1 2 3
420 3 $state->{lmstudio_reasoning_seen} = 1;
421 3 return Langertha::Stream::Chunk->new(
422 content => '',
423 thinking => $thinking,
424 raw => $data,
425 is_final => 0,
426 );
427 }
428 9 ▶ if ($type eq 'message.delta') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "message.delta") 1 8 9
429 return Langertha::Stream::Chunk->new(
430 1 ▶ content => $data->{content} // '',
Condition50%1/2
$$data{"content"} // ""
l!l
10
MC/DC0%0/1
$$data{"content"} // ""
$$data{"content"}
Truth table50%1/2
A
A= $$data{"content"}
Aresult
11
00
431 raw => $data,
432 is_final => 0,
433 );
434 }
435 8 ▶ if ($type eq 'chat.end') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "chat.end") 3 5 8
436 3 ▶ my $result = $data->{result} || {};
Condition50%1/2
$$data{'result'} || {}
l!l
30
MC/DC0%0/1
$$data{'result'} || {}
$$data{'result'}
Truth table50%1/2
A
A= $$data{'result'}
Aresult
11
00
437 my $usage = _normalize_usage({
438 input_tokens => $result->{stats}{input_tokens},
439 output_tokens => $result->{stats}{total_output_tokens},
440 3 });
441  
442 return Langertha::Stream::Chunk->new(
443 content => '',
444 raw => $data,
445 is_final => 1,
446 defined $result->{response_id} ? ( finish_reason => 'end' ) : (),
447 3 ▶ $result->{model_instance_id} ? ( model => $result->{model_instance_id} ) : (),
Branch: 3 branches
BranchTrueFalseTotal
defined $$result{'response_id'} ? : 2 1 3
$$result{'model_instance_id'} ? : 3 0 3
$usage ? : 2 1 3
448 $usage ? ( usage => $usage ) : (),
449 );
450 }
451  
452 5 return undef;
453 }
454  
455 # Dynamic model listing
456 0 ▶sub list_models_request {
Subroutine list_models_request: not called CC=1 SCAR=6.9
Pod undocumented
457 0 my ( $self ) = @_;
458 return $self->generate_request(
459 'listModels',
460 0 ▶ sub { $self->list_models_response(shift) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
461 0 );
462 }
463  
464 0 ▶sub list_models_response {
Subroutine list_models_response: not called CC=1 SCAR=6.9
Pod undocumented
465 0 my ( $self, $response ) = @_;
466 0 return $self->parse_response($response);
467 }
468  
469 0 ▶sub list_models {
Subroutine list_models: not called CC=16 SCAR=56.1
Pod undocumented
470 0 my ( $self, %opts ) = @_;
471  
472 0 ▶ unless ($opts{force_refresh}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($opts{"force_refresh"}) 0 0 0
473 0 my $cache = $self->_models_cache;
474 0 ▶ if ($cache->{timestamp} && time - $cache->{timestamp} < $self->models_cache_ttl) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$cache{"timestamp"} and time - $$cache{"timestamp"} < $self->models_cache_ttl) 0 0 0
Condition0%0/3
$$cache{"timestamp"} and time - $$cache{"timestamp"} < $self->models_cache_ttl
!ll&&!rl&&r
000
MC/DC0%0/2
$$cache{"timestamp"} and time - $$cache{"timestamp"} < $self->models_cache_ttl
$$cache{"timestamp"} time - $$cache{"timestamp"} < $self->models_cache_ttl
Truth table0%0/3
A and B
A= $$cache{"timestamp"}B= time - $$cache{"timestamp"} < $self->models_cache_ttl
ABresult
0X0
100
111
475 0 ▶ return $opts{full} ? $cache->{models} : $cache->{model_ids};
Branch: 1 branch
BranchTrueFalseTotal
$opts{'full'} ? : 0 0 0
476 }
477 }
478  
479 0 my $request = $self->list_models_request;
480 0 my $response = $self->user_agent->request($request);
481 0 my $data = $request->response_call->($response);
482  
483 my $models = ref $data eq 'HASH'
484 0 ▶ ? ($data->{data} // $data->{models} // [])
Branch: 1 branch
BranchTrueFalseTotal
ref $data eq 'HASH' ? : 0 0 0
Condition0%0/5
($$data{"data"} // $$data{"models"}) // []
l!l
00
$$data{"data"} // $$data{"models"}
l!l&&r!l&&!r
000
MC/DC0%0/2
($$data{"data"} // $$data{"models"}) // []
$$data{"data"} $$data{"models"}
Truth table0%0/3
A // B
A= $$data{"data"}B= $$data{"models"}
ABresult
1X1
011
000
485 : $data;
486 0 ▶ $models = [] unless ref $models eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $models eq "ARRAY" 0 0 0
487  
488 0 my @model_ids;
489 0 for my $model (@{$models}) {
490 0 ▶ next unless ref $model eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $model eq "HASH" 0 0 0
491 0 ▶ my $id = $model->{key} // $model->{id} // $model->{model} // $model->{name};
Condition0%0/9
(($$model{"key"} // $$model{"id"}) // $$model{"model"}) // $$model{"name"}
l!l&&r!l&&!r
000
($$model{"key"} // $$model{"id"}) // $$model{"model"}
l!l&&r!l&&!r
000
$$model{"key"} // $$model{"id"}
l!l&&r!l&&!r
000
MC/DC0%0/4
(($$model{"key"} // $$model{"id"}) // $$model{"model"}) // $$model{"name"}
$$model{"key"} $$model{"id"} $$model{"model"} $$model{"name"}
Truth table0%0/5
A // B // C // D
A= $$model{"key"}B= $$model{"id"}C= $$model{"model"}D= $$model{"name"}
ABCDresult
1XXX1
01XX1
001X1
00011
00000
492 0 ▶ push @model_ids, $id if defined $id;
Branch: 1 branch
BranchTrueFalseTotal
if defined $id 0 0 0
493 }
494  
495 $self->_models_cache({
496 0 timestamp => time,
497 models => $models,
498 model_ids => \@model_ids,
499 });
500  
501 0 ▶ return $opts{full} ? $models : \@model_ids;
Branch: 1 branch
BranchTrueFalseTotal
$opts{'full'} ? : 0 0 0
502 }
503  
504 15 __PACKAGE__->meta->make_immutable;
505  
506  
507 15 1;
508  
509 __END__
« blib/lib/Langertha/Tool.pm ↑ Summary blib/lib/Langertha/Role/Chat.pm »