blib/lib/Langertha/Engine/SGLang.pm

filter: Statementstmt 100% 33 / 33 Branchbran 100% 6 / 6 Conditioncond 80.0% 4 / 5 MC/DCmcdc 66.6% 2 / 3 Subroutinesub 100% 11 / 11 Podpod 50.0% 2 / 4 totaltotal 93.5% 58 / 62 CC 6 SCAR 10.6
CC
6
Cov
98%
_exclude_forced_tool_choice_with_response_format
6.0
BEGIN
1.0
BEGIN
1.0
CRAP 2.9
« blib/lib/Langertha/Engine/OpenRouter.pm ↑ Summary blib/lib/Langertha/Engine/MiniMaxAnthropic.pm »
1 package Langertha::Engine::SGLang;
2 # ABSTRACT: SGLang inference server
3 13 our $VERSION = '0.503';
4 13 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 13 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 13 extends 'Langertha::Engine::OpenAIBase';
8  
9 13 with 'Langertha::Role::Tools',
10 'Langertha::Role::Embedding',
11 'Langertha::Role::Runtime::MetricsPoll',
12 'Langertha::Role::RuntimeKnobs';
13  
14 # SGLang's per-request runtime knobs: cache_salt, extra_key, priority,
15 # return_cached_tokens_details. Speculative decoding is a server-launch flag
16 # (--speculative-*), not a request knob — see Langertha::Runtime::Knobs.
17 1 ▶sub _build_knob_wire_format { 'sglang' }
Subroutine _build_knob_wire_format: called CC=1 SCAR=0.0
18  
19  
20 13 has '+url' => (
21 required => 1,
22 );
23  
24 44 ▶sub default_model { 'default' }
Subroutine default_model: called CC=1 SCAR=0.0
Pod documented
25 # No fixed embedding model: the caller's model, else no model field (the vLLM
26 # rule, k297); the server embeds with the model it was launched with (k309).
27 4 ▶sub default_embedding_model { undef }
Subroutine default_embedding_model: called CC=1 SCAR=0.0
Pod undocumented
28  
29 # LANGERTHA_SGLANG_API_KEY is derived from the class name; a local server
30 # needs no key, a --api-key-protected `sglang.launch_server` does.
31 3 ▶sub api_key_required { 0 }
Subroutine api_key_required: called CC=1 SCAR=0.0
Pod documented
32  
33 21 ▶sub _build_api_key {
Subroutine _build_api_key: called CC=1 SCAR=0.0
34 21 return $ENV{LANGERTHA_SGLANG_API_KEY};
35 }
36  
37 51 ▶sub _build_supported_operations {[qw(
Subroutine _build_supported_operations: called CC=1 SCAR=0.0
38 createChatCompletion
39 createCompletion
40 createEmbedding
41 )]}
42  
43 # tool_choice: all four forms stay. ChatCompletionRequest.tool_choice is
44 # auto|required|none or a named function, default auto
45 # (python/sglang/srt/entrypoints/openai/protocol.py, source-checked 2026-09-25,
46 # karr k244), and serving_chat honors none. The tool_parser docs list only
47 # required and named because those two need the grammar backend (xgrammar, the
48 # default); that omission, not a wire rejection, was why k138 cleared auto and
49 # none. Every tool field needs the server started with --tool-call-parser.
50 # prompt_cache_key (OpenAI's cache-routing hint) is not a field of SGLang's
51 # ChatCompletionRequest, a pydantic model that silently drops unknown keys
52 # (python/sglang/srt/entrypoints/openai/protocol.py, checked 2026-09-25, karr
53 # #200). Prefix-cache control is cache_salt / extra_key via RuntimeKnobs.
54 230 ▶around engine_capabilities => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
55 230 my ( $orig, $self, @rest ) = @_;
56 230 my $caps = $self->$orig(@rest);
57 230 delete $caps->{prompt_cache_key};
58 # image_input (k266, ADR 0019): self-hosted: the served model is launch state the client cannot see, so no claim.
59 230 delete $caps->{image_input};
60 230 return $caps;
61 13 };
62  
63 # karr k245: SGLang rejects tool_choice 'required' or a named tool together
64 # with an output constraint ("tool_choice 'required' or a named tool cannot be
65 # combined with response_format, regex, or ebnf", ValueError in
66 # python/sglang/srt/entrypoints/openai/protocol.py since 307a90f6d3 /
67 # 17ba2c2e7c, source-checked 2026-09-25): json_schema, json_object (becomes
68 # json_schema '{"type":"object"}') and structural_tag constrain, text does not.
69 # tool_choice auto + response_format is accepted. The server exempts parsers
70 # whose tool constraint is full_assistant_ebnf; that is a launch flag Langertha
71 # cannot see, so the rule holds for every model (qr//), like Groq/Cerebras.
72 13 my %SGLANG_CONSTRAINING_RF = map { $_ => 1 } qw( json_schema json_object structural_tag );
73  
74 16 ▶sub model_capability_exclusions {
Subroutine model_capability_exclusions: called CC=1 SCAR=0.0
Pod undocumented
75 return (
76 16 qr// => \&_exclude_forced_tool_choice_with_response_format,
77 );
78 }
79  
80 16 ▶sub _exclude_forced_tool_choice_with_response_format {
Subroutine _exclude_forced_tool_choice_with_response_format: called CC=6 SCAR=17.9
81 16 my ( $self, %request ) = @_;
82 16 ▶ return unless $request{has_tools} && $request{tool_choice_forced};
Branch: 1 branch
BranchTrueFalseTotal
unless $request{"has_tools"} and $request{"tool_choice_forced"} 3 13 16
Condition100%3/3
$request{"has_tools"} and $request{"tool_choice_forced"}
!ll&&!rl&&r
1213
MC/DC100%2/2
$request{"has_tools"} and $request{"tool_choice_forced"}
$request{"has_tools"} $request{"tool_choice_forced"}
Truth table100%3/3
A and B
A= $request{"has_tools"}B= $request{"tool_choice_forced"}
ABresult
0X0
100
111
83 13 my $rf = $request{response_format};
84 13 ▶ my $type = ( ref $rf eq 'HASH' ) ? ( $rf->{type} // '' ) : '';
Branch: 1 branch
BranchTrueFalseTotal
ref $rf eq 'HASH' ? : 12 1 13
Condition50%1/2
$$rf{"type"} // ""
l!l
120
MC/DC0%0/1
$$rf{"type"} // ""
$$rf{"type"}
Truth table50%1/2
A
A= $$rf{"type"}
Aresult
11
00
85 13 ▶ return unless $SGLANG_CONSTRAINING_RF{$type};
Branch: 1 branch
BranchTrueFalseTotal
unless $SGLANG_CONSTRAINING_RF{$type} 3 10 13
86 10 croak "".(ref $self)." cannot combine a forced tool_choice (required or a "
87 ."named tool) with response_format $type in one request: the SGLang server "
88 ."rejects it (the tool-call constraint and the output constraint cannot both "
89 ."be honored) with HTTP 400. Use tool_choice auto, or drop the response_format.";
90 }
91  
92 13 __PACKAGE__->meta->make_immutable;
93  
94  
95  
96 13 1;
97  
98 __END__
99  
100 =pod
101  
102 =encoding UTF-8
103  
104 =head1 NAME
105  
106 Langertha::Engine::SGLang - SGLang inference server
107  
108 =head1 VERSION
109  
110 version 0.503
111  
112 =head1 SYNOPSIS
113  
114 use Langertha::Engine::SGLang;
115  
116 # 1. Simple chat
117 my $sglang = Langertha::Engine::SGLang->new(
118 url => 'http://localhost:30000/v1',
119 model => 'Qwen/Qwen2.5-7B-Instruct',
120 );
121  
122 print $sglang->simple_chat('Say something nice');
123  
124 # 2. Streaming
125 $sglang->simple_chat_stream(sub {
126 print shift->content;
127 }, 'Write a haiku about Perl');
128  
129 # 3. MCP tool calling (requires a tool-call-parser-compatible model)
130 use Future::AsyncAwait;
131  
132 my $sglang = Langertha::Engine::SGLang->new(
133 url => 'http://localhost:30000/v1',
134 model => 'Qwen/Qwen2.5-7B-Instruct',
135 mcp_servers => [$mcp],
136 );
137  
138 my $response = await $sglang->chat_with_tools_f('Add 7 and 15');
139  
140 # 4. Multimodal input (vision-capable models served by SGLang)
141 use Langertha::Content::Image;
142  
143 my $img = Langertha::Content::Image->from_url('https://example.com/cat.jpg');
144 my $resp = await $sglang->simple_chat_f({
145 role => 'user',
146 content => [ 'What is in this image?', $img ],
147 });
148  
149 # 5. Prometheus /metrics scraping (Runtime::MetricsPoll)
150 my $records = await $sglang->poll_metrics_f('sglang:');
151  
152 # 6. Embeddings (server launched with an embedding model)
153 my $embedder = Langertha::Engine::SGLang->new(
154 url => 'http://localhost:30000/v1',
155 model => 'Alibaba-NLP/gte-Qwen2-1.5B-instruct',
156 );
157 my $vector = $embedder->simple_embedding('Some text to embed');
158 my $vectors = $embedder->simple_embedding([ 'first', 'second' ]);
159  
160 =head1 DESCRIPTION
161  
162 Adapter for SGLang's OpenAI-compatible endpoint.
163 SGLang is typically exposed as C</v1/chat/completions> with optional
164 tool-calling support depending on model/backend setup.
165  
166 Extends L<Langertha::Engine::OpenAIBase> (which composes
167 L<Langertha::Role::OpenAICompatible>, L<Langertha::Role::OpenAPI>,
168 L<Langertha::Role::Models>, L<Langertha::Role::Temperature>,
169 L<Langertha::Role::ResponseSize>, L<Langertha::Role::SystemPrompt>,
170 L<Langertha::Role::ResponseFormat>, L<Langertha::Role::Streaming>,
171 L<Langertha::Role::Chat>, L<Langertha::Role::ReasoningEffort>, and
172 L<Langertha::Role::PromptCache>); SGLang itself additionally composes
173 L<Langertha::Role::Tools> (MCP tool calling), L<Langertha::Role::Embedding>
174 (OpenAI-compatible C</v1/embeddings>) and
175 L<Langertha::Role::Runtime::MetricsPoll> (Prometheus C</metrics> scrape).
176  
177 Supports chat, streaming, tool calling, embeddings, structured output,
178 multimodal input, and Prometheus /metrics scraping. Transcription is not
179 exposed on the OpenAI-compatible surface SGLang serves.
180  
181 Only C<url> is required. Use the full C</v1> base URL.
182 No API key is required for local setups.
183  
184 See L<https://docs.sglang.ai/> for installation and configuration details.
185  
186 =head1 EMBEDDINGS
187  
188 Composes L<Langertha::Role::Embedding>. SGLang serves C</v1/embeddings> when
189 launched with an embedding model (decoder-style models also need
190 C<--is-embedding>). The request carries C<embedding_model> if you set it,
191 else C<model> if you set it, else no C<model> field at all: the server
192 embeds with the model it serves. A string returns one vector, an ArrayRef of
193 strings one vector per input, in input order.
194  
195 =head1 CAPABILITIES
196  
197 Advertised flags (derived from composed roles via L<Langertha::Role::Capabilities>):
198  
199 =over 4
200  
201 =item * C<chat> — L<Langertha::Role::Chat>
202  
203 =item * C<streaming> — L<Langertha::Role::Streaming>
204  
205 =item * C<tools_native> + C<tool_choice_{auto,any,none,named}> — L<Langertha::Role::Tools>
206 (tool calling needs the server started with C<--tool-call-parser>; C<any> (wire
207 C<required>) and a named tool also need the grammar backend, xgrammar by default)
208  
209 =item * C<embedding> — L<Langertha::Role::Embedding>
210  
211 =item * C<runtime_metrics> — L<Langertha::Role::Runtime::MetricsPoll>
212  
213 =item * C<response_format_{json_object,json_schema}> — L<Langertha::Role::ResponseFormat>
214  
215 =item * C<temperature> — L<Langertha::Role::Temperature>
216  
217 =item * C<reasoning_effort> — L<Langertha::Role::ReasoningEffort>
218  
219 =item * C<response_size>, C<system_prompt>, C<parallel_tool_use>, C<context_size>, C<seed>
220 — generation-parameter knobs the engine will honour
221  
222 =back
223  
224 A forced C<tool_choice> (C<required> or a named tool) together with a
225 C<response_format> of C<json_schema>, C<json_object> or C<structural_tag>
226 croaks before the request is sent: the SGLang server rejects that combination
227 with HTTP 400. C<tool_choice> C<auto> with a C<response_format> is sent.
228  
229 =head1 SEE ALSO
230  
231 =over
232  
233 =item * L<https://docs.sglang.ai/> - SGLang documentation
234  
235 =item * L<Langertha::Engine::OpenAIBase> - Base class for OpenAI-compatible engines
236  
237 =item * L<Langertha::Role::OpenAICompatible> - OpenAI API format role
238  
239 =item * L<Langertha::Role::Tools> - MCP tool calling interface
240  
241 =item * L<Langertha::Role::Runtime::MetricsPoll> - Prometheus /metrics scraper
242  
243 =item * L<Langertha::Engine::vLLM> - Sister self-hosted OpenAI-compatible engine (also Embedding + MetricsPoll)
244  
245 =item * L<Langertha::Engine::LlamaCpp> - Sister self-hosted OpenAI-compatible engine (also Embedding + MetricsPoll)
246  
247 =back
248  
249 =head1 SUPPORT
250  
251 =head2 Issues
252  
253 Please report bugs and feature requests on GitHub at
254 L<https://github.com/Getty/langertha/issues>.
255  
256 =head2 IRC
257  
258 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
259  
260 =head1 CONTRIBUTING
261  
262 Contributions are welcome! Please fork the repository and submit a pull request.
263  
264 =head1 AUTHOR
265  
266 Torsten Raudssus <getty@cpan.org>
267  
268 =head1 COPYRIGHT AND LICENSE
269  
270 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
271  
272 This is free software; you can redistribute it and/or modify it under
273 the same terms as the Perl 5 programming language system itself.
274  
275 =cut
« blib/lib/Langertha/Engine/OpenRouter.pm ↑ Summary blib/lib/Langertha/Engine/MiniMaxAnthropic.pm »