blib/lib/Langertha.pm

filter: Statementstmt 87.8% 94 / 107 Branchbran 70.0% 21 / 30 Conditioncond 30.0% 6 / 20 MC/DCmcdc 0.0% 0 / 12 Subroutinesub 85.0% 17 / 20 Podpod 80.0% 4 / 5 totaltotal 73.2% 142 / 194 CC 26 SCAR 15.1
CC
26
Cov
77%
resolve_engine_class
8.2
discover_modules_in_scope
6.3
import
6.0
CRAP 4.5
« blib/lib/Langertha/Moment.pm ↑ Summary blib/lib/Langertha/Engine/HuggingFace.pm »
1 package Langertha;
2 # ABSTRACT: The clan of fierce vikings with 🪓 and 🛡️ to AId your rAId
3 4 our $VERSION = '0.503';
4 4 ▶use utf8;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 4 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 4 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 4 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 4 ▶use Import::Into;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 4 ▶use Module::Pluggable::Object ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 4 ▶use Module::Runtime qw( require_module use_module );
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 4 my %_sugar_plugins; # per-class plugin accumulator
14  
15 my %setup = (
16 0 ▶ Raider => sub {
Subroutine __ANON__: not called CC=1 SCAR=4.4
17 0 my ( $caller ) = @_;
18 0 Moose->import::into($caller);
19 0 Future::AsyncAwait->import::into($caller);
20 0 $caller->meta->superclasses('Langertha::Raider');
21 0 $_sugar_plugins{$caller} = [];
22 4 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
23 0 ▶ *{"${caller}::plugin"} = sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
24 0 push @{$_sugar_plugins{$caller}}, @_;
25 0 };
26 0 ▶ $caller->meta->add_method('_sugar_plugins' => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
27 0 ▶ return [@{$_sugar_plugins{$caller} // []}];
Condition0%0/2
$_sugar_plugins{$caller} // []
l!l
00
MC/DC0%0/1
$_sugar_plugins{$caller} // []
$_sugar_plugins{$caller}
Truth table0%0/2
A
A= $_sugar_plugins{$caller}
Aresult
11
00
28 0 });
29 },
30 1 ▶ Plugin => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
31 1 my ( $caller ) = @_;
32 1 Moose->import::into($caller);
33 1 Future::AsyncAwait->import::into($caller);
34 1 $caller->meta->superclasses('Langertha::Plugin');
35 },
36 4 );
37  
38 3 ▶sub import {
Subroutine import: called CC=6 SCAR=18.0
39 3 my ( $class, @args ) = @_;
40 3 ▶ return unless @args;
Branch: 1 branch
BranchTrueFalseTotal
unless @args 1 2 3
41 2 my $caller = caller;
42 2 for my $arg (@args) {
43 2 ▶ my $setup = $setup{$arg}
Branch: 1 branch
BranchTrueFalseTotal
my $setup = $setup{$arg} or Carp::croak("Unknown Langertha import '${arg}' (known: " . join(", ", sort(keys %setup)) . ')') 1 1 2
44 or Carp::croak("Unknown Langertha import '$arg' (known: ".join(', ', sort keys %setup).")");
45 1 require Moose;
46 1 require Future::AsyncAwait;
47 1 ▶ use_module('Langertha::Raider') if $arg eq 'Raider';
Branch: 1 branch
BranchTrueFalseTotal
if $arg eq "Raider" 0 1 1
48 1 ▶ use_module('Langertha::Plugin') if $arg eq 'Plugin';
Branch: 1 branch
BranchTrueFalseTotal
if $arg eq "Plugin" 1 0 1
49 1 $setup->($caller);
50 }
51 }
52  
53 2 ▶sub _module_path {
Subroutine _module_path: called CC=1 SCAR=0.0
54 2 my ($module) = @_;
55 2 my $path = $module;
56 2 $path =~ s{::}{/}g;
57 2 return $path . '.pm';
58 }
59  
60 2 ▶sub _is_missing_module_error {
Subroutine _is_missing_module_error: called CC=4 SCAR=15.6
61 2 my ($err, $module) = @_;
62 2 ▶ return 0 unless defined $err && length $err;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $err and length $err 0 2 2
Condition33%1/3
defined $err and length $err
!ll&&!rl&&r
002
MC/DC0%0/2
defined $err and length $err
defined $err length $err
Truth table33%1/3
A and B
A= defined $errB= length $err
ABresult
0X0
100
111
63 2 my $pm_path = _module_path($module);
64 2 ▶ return index($err, "Can't locate $pm_path in \@INC") >= 0 ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
index($err, "Can't locate $pm_path in \@INC") != -1 ? : 2 0 2
65 }
66  
67 7 ▶sub discover_modules_in_scope {
Subroutine discover_modules_in_scope: called CC=5 SCAR=18.3
Pod undocumented
68 7 my ($class, %args) = @_;
69 7 my $search_path = $args{search_path};
70 7 ▶ $search_path = ['Langertha::Engine', 'LangerthaX::Engine']
Branch: 1 branch
BranchTrueFalseTotal
unless ref $search_path eq "ARRAY" and @$search_path 0 7 7
Condition33%1/3
ref $search_path eq "ARRAY" and @$search_path
!ll&&!rl&&r
007
MC/DC0%0/2
ref $search_path eq "ARRAY" and @$search_path
ref $search_path eq "ARRAY" @$search_path
Truth table33%1/3
A and B
A= ref $search_path eq "ARRAY"B= @$search_path
ABresult
0X0
100
111
71 unless ref($search_path) eq 'ARRAY' && @$search_path;
72  
73 7 my $finder = Module::Pluggable::Object->new(
74 search_path => $search_path,
75 require => 0,
76 inner => 0,
77 );
78  
79 7 my %seen;
80 7 ▶ my @modules = grep { defined $_ && length $_ && !$seen{$_}++ } $finder->plugins;
Condition33%2/6
defined $_ && length $_ && !$seen{$_}++
!ll&&!rl&&r
00273
defined $_ and length $_
!ll&&!rl&&r
00273
MC/DC0%0/3
defined $_ && length $_ && !$seen{$_}++
defined $_ length $_ !$seen{$_}++
Truth table25%1/4
A and B && not(C)
A= defined $_B= length $_C= !$seen{$_}++
ABCresult
0XX0
10X0
1100
1111
81 7 return [ sort @modules ];
82 }
83  
84 7 ▶sub available_engine_classes {
Subroutine available_engine_classes: called CC=1 SCAR=0.0
Pod documented
85 7 my ($class) = @_;
86 7 return $class->discover_modules_in_scope(
87 search_path => ['Langertha::Engine', 'LangerthaX::Engine'],
88 );
89 }
90  
91 1 ▶sub available_engine_ids {
Subroutine available_engine_ids: called CC=3 SCAR=11.0
Pod documented
92 1 my ($class) = @_;
93 1 my %ids;
94 1 for my $module (@{$class->available_engine_classes}) {
95 39 ▶ next unless $module =~ /::([^:]+)\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $module =~ /::([^:]+)\z/ 0 39 39
96 39 $ids{lc($1)} = 1;
97 }
98 1 return [ sort keys %ids ];
99 }
100  
101 6 ▶sub resolve_engine_class {
Subroutine resolve_engine_class: called CC=8 SCAR=21.0
Pod documented
102 6 my ($class, $engine) = @_;
103 6 ▶ Carp::croak("No engine specified") unless defined($engine) && length($engine);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $engine and length $engine 0 6 6
Condition33%1/3
defined $engine and length $engine
!ll&&!rl&&r
006
MC/DC0%0/2
defined $engine and length $engine
defined $engine length $engine
Truth table33%1/3
A and B
A= defined $engineB= length $engine
ABresult
0X0
100
111
104  
105 6 my @candidates;
106 6 ▶ if ($engine =~ /::/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($engine =~ /::/) { } 1 5 6
107 1 @candidates = ($engine);
108 } else {
109 5 my @ordered = ("Langertha::Engine::$engine", "LangerthaX::Engine::$engine");
110 5 my %available = map { $_ => 1 } @{$class->available_engine_classes};
111 5 @candidates = grep { $available{$_} } @ordered;
112 5 ▶ @candidates = @ordered unless @candidates;
Branch: 1 branch
BranchTrueFalseTotal
unless @candidates 1 4 5
113 }
114  
115 6 my @errors;
116 6 for my $candidate (@candidates) {
117 7 my $ok = eval {
118 7 require_module($candidate);
119 5 1;
120 };
121 7 ▶ return $candidate if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 5 2 7
122 2 my $err = $@;
123 2 ▶ if (!_is_missing_module_error($err, $candidate)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (_is_missing_module_error($err, $candidate)) 0 2 2
124 0 Carp::croak($err);
125 }
126 2 push @errors, $candidate;
127 }
128  
129 Carp::croak(
130 1 "Engine '$engine' not found (tried: " . join(', ', @errors) . ")"
131 );
132 }
133  
134 3 ▶sub new_engine {
Subroutine new_engine: called CC=4 SCAR=14.5
Pod documented
135 3 my ($class, $engine, @args) = @_;
136 3 ▶ Carp::croak("No engine specified") unless defined($engine) && length($engine);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $engine and length $engine 0 3 3
Condition33%1/3
defined $engine and length $engine
!ll&&!rl&&r
003
MC/DC0%0/2
defined $engine and length $engine
defined $engine length $engine
Truth table33%1/3
A and B
A= defined $engineB= length $engine
ABresult
0X0
100
111
137 3 ▶ Carp::croak("Engine constructor arguments must be key/value pairs")
Branch: 1 branch
BranchTrueFalseTotal
if @args % 2 1 2 3
138 if @args % 2;
139  
140 2 my $engine_class = $class->resolve_engine_class($engine);
141 2 return $engine_class->new(@args);
142 }
143  
144  
145 4 1;
146  
147 __END__
148  
149 =pod
150  
151 =encoding UTF-8
152  
153 =head1 NAME
154  
155 Langertha - The clan of fierce vikings with 🪓 and 🛡️ to AId your rAId
156  
157 =head1 VERSION
158  
159 version 0.503
160  
161 =head1 SYNOPSIS
162  
163 my $system_prompt = 'You are a helpful assistant.';
164  
165 # Local models via Ollama
166 use Langertha::Engine::Ollama;
167  
168 my $ollama = Langertha::Engine::Ollama->new(
169 url => 'http://127.0.0.1:11434',
170 model => 'a small chat model you have pulled locally',
171 system_prompt => $system_prompt,
172 );
173 print $ollama->simple_chat('Do you wanna build a snowman?');
174  
175 # OpenAI
176 use Langertha::Engine::OpenAI;
177  
178 my $openai = Langertha::Engine::OpenAI->new(
179 api_key => $ENV{OPENAI_API_KEY},
180 model => 'a small fast model from your provider',
181 system_prompt => $system_prompt,
182 );
183 print $openai->simple_chat('Do you wanna build a snowman?');
184  
185 # Anthropic Claude
186 use Langertha::Engine::Anthropic;
187  
188 my $claude = Langertha::Engine::Anthropic->new(
189 api_key => $ENV{ANTHROPIC_API_KEY},
190 model => 'a frontier chat model from your provider',
191 );
192 print $claude->simple_chat('Generate Perl Moose classes to represent GeoJSON data.');
193  
194 # Google Gemini
195 use Langertha::Engine::Gemini;
196  
197 my $gemini = Langertha::Engine::Gemini->new(
198 api_key => $ENV{GEMINI_API_KEY},
199 model => 'a fast model from your provider',
200 );
201 print $gemini->simple_chat('Explain the difference between Moose and Moo.');
202  
203 =head1 DESCRIPTION
204  
205 Langertha provides a unified Perl interface for interacting with various Large
206 Language Model (LLM) APIs. It abstracts away provider-specific differences,
207 giving you a consistent API whether you're using OpenAI, Anthropic Claude,
208 Ollama, Groq, Mistral, or other providers.
209  
210 B<THIS API IS WORK IN PROGRESS.>
211  
212 =head2 Key Features
213  
214 =over 4
215  
216 =item * B<35 engines> -- unified API across cloud and local LLM providers
217  
218 =item * B<Chat, streaming, embeddings, transcription, image generation>
219  
220 =item * B<MCP tool calling> -- automatic multi-round tool loops over any
221 L<Net::Async::MCP>-compatible client (see L<Langertha::Role::Tools>)
222  
223 =item * B<Raider> -- autonomous agent with history, compression, and plugins,
224 shipped separately in the L<langertha-raider|Langertha::Raider> distribution
225  
226 =item * B<Response metadata> -- token usage, model, timing, rate limits
227  
228 =item * B<Async/await> via L<Future::AsyncAwait>, sync via L<LWP::UserAgent>
229  
230 =item * B<Langfuse observability> -- traces, generations, and tool spans
231  
232 =item * B<Dynamic model discovery> -- query provider APIs with caching
233  
234 =item * B<Chain-of-thought> -- native extraction and C<E<lt>thinkE<gt>> tag filtering
235  
236 =item * B<Plugin system> for extending Chat, Embedder, ImageGen, and Raider
237  
238 =back
239  
240 =head2 Class Sugar
241  
242 Langertha can set up your package as a Raider subclass or Plugin role:
243  
244 # Build a custom Raider agent
245 package MyAgent;
246 use Langertha qw( Raider );
247 plugin 'Langfuse';
248  
249 around plugin_before_llm_call => async sub {
250 my ($orig, $self, $conversation, $iteration) = @_;
251 $conversation = await $self->$orig($conversation, $iteration);
252 # ... custom logic ...
253 return $conversation;
254 };
255  
256 __PACKAGE__->meta->make_immutable;
257  
258 # Build a custom Plugin
259 package MyApp::Guardrails;
260 use Langertha qw( Plugin );
261  
262 around plugin_before_tool_call => async sub {
263 my ($orig, $self, $name, $input) = @_;
264 my @result = await $self->$orig($name, $input);
265 return unless @result;
266 return if $name eq 'dangerous_tool';
267 return @result;
268 };
269  
270 C<use Langertha qw( Raider )> imports L<Moose> and L<Future::AsyncAwait>,
271 sets L<Langertha::Raider> as superclass, and provides the C<plugin>
272 function for applying plugins by short name. L<Langertha::Raider> ships in
273 the separate C<langertha-raider> distribution, which must be installed for
274 this sugar to load.
275  
276 C<use Langertha qw( Plugin )> imports L<Moose> and
277 L<Future::AsyncAwait>, and sets L<Langertha::Plugin> as superclass.
278  
279 =head2 Engine Discovery
280  
281 Langertha discovers engine modules in scope via L<Module::Pluggable> across
282 both namespaces:
283  
284 =over 4
285  
286 =item * C<Langertha::Engine::*>
287  
288 =item * C<LangerthaX::Engine::*>
289  
290 =back
291  
292 Useful class methods:
293  
294 =over 4
295  
296 =item * C<< Langertha->available_engine_classes >>
297  
298 Returns discovered fully-qualified engine class names.
299  
300 =item * C<< Langertha->available_engine_ids >>
301  
302 Returns discovered engine IDs (lowercased short names).
303  
304 =item * C<< Langertha->resolve_engine_class($name_or_class) >>
305  
306 Resolves short names (for example C<OpenAI>) with core-first lookup,
307 or accepts fully-qualified class names.
308  
309 =item * C<< Langertha->new_engine($name_or_class, %args) >>
310  
311 Resolves and constructs an engine instance in one call.
312  
313 =back
314  
315 =head2 Engine Modules
316  
317 Each module below is a ready-to-use engine. They are built on the abstract
318 bases L<Langertha::Engine::Remote>, L<Langertha::Engine::OpenAIBase> and
319 L<Langertha::Engine::AnthropicBase>, which are not listed here because they
320 are meant for subclassing (including third-party engines in the C<LangerthaX>
321 namespace) rather than for direct use.
322  
323 =over 4
324  
325 =item * L<Langertha::Engine::Anthropic> - Claude models (Sonnet, Opus, Haiku)
326  
327 =item * L<Langertha::Engine::OpenAI> - frontier GPT models, embeddings, Whisper transcription
328  
329 =item * L<Langertha::Engine::OpenAIResponses> - OpenAI Responses API for reasoning models
330  
331 =item * L<Langertha::Engine::Ollama> - Local LLM hosting via L<https://ollama.com/>
332  
333 =item * L<Langertha::Engine::Groq> - Fast inference API
334  
335 =item * L<Langertha::Engine::Mistral> - Mistral AI models, embeddings, Voxtral transcription
336  
337 =item * L<Langertha::Engine::DeepSeek> - DeepSeek models
338  
339 =item * L<Langertha::Engine::MiniMax> - MiniMax large language models via OpenAI-compatible endpoint (coding, reasoning, agentic tool use)
340  
341 =item * L<Langertha::Engine::MiniMaxAnthropic> - MiniMax via legacy Anthropic-compatible endpoint
342  
343 =item * L<Langertha::Engine::Moonshot> - Moonshot AI Kimi models via OpenAI-compatible endpoint
344  
345 =item * L<Langertha::Engine::MoonshotAnthropic> - Moonshot AI Kimi via Anthropic-compatible endpoint
346  
347 =item * L<Langertha::Engine::Gemini> - Google Gemini models (Flash, Pro), embeddings
348  
349 =item * L<Langertha::Engine::XAI> - xAI Grok models, Imagine image generation
350  
351 =item * L<Langertha::Engine::vLLM> - vLLM inference server
352  
353 =item * L<Langertha::Engine::VLLMHook> - vLLM inference server with vLLM-Hook probe capture
354  
355 =item * L<Langertha::Engine::SGLang> - SGLang inference server (chat, embeddings)
356  
357 =item * L<Langertha::Engine::HuggingFace> - HuggingFace Inference Providers
358  
359 =item * L<Langertha::Engine::Perplexity> - Perplexity AI models
360  
361 =item * L<Langertha::Engine::NousResearch> - Nous Research (Hermes models)
362  
363 =item * L<Langertha::Engine::Cerebras> - Cerebras (wafer-scale, fastest inference)
364  
365 =item * L<Langertha::Engine::OpenRouter> - OpenRouter (300+ models, meta-provider)
366  
367 =item * L<Langertha::Engine::Replicate> - Replicate (thousands of open-source models)
368  
369 =item * L<Langertha::Engine::OllamaOpenAI> - Ollama via OpenAI-compatible API
370  
371 =item * L<Langertha::Engine::LlamaCpp> - llama.cpp server (chat, embeddings)
372  
373 =item * L<Langertha::Engine::LMStudio> - LM Studio native local REST API
374  
375 =item * L<Langertha::Engine::LMStudioOpenAI> - LM Studio via OpenAI-compatible API
376  
377 =item * L<Langertha::Engine::LMStudioAnthropic> - LM Studio via Anthropic-compatible API
378  
379 =item * L<Langertha::Engine::AKI> - AKI.IO native API (EU/Germany)
380  
381 =item * L<Langertha::Engine::AKIOpenAI> - AKI.IO via OpenAI-compatible API
382  
383 =item * L<Langertha::Engine::AKIAnthropic> - AKI.IO via Anthropic-compatible API
384  
385 =item * L<Langertha::Engine::TSystems> - T-Systems AI Foundation Services / LLM Hub (EU/Germany)
386  
387 =item * L<Langertha::Engine::Scaleway> - Scaleway Generative APIs (EU)
388  
389 =item * L<Langertha::Engine::Hetzner> - Hetzner Inference API (EU/Germany, OpenAI-compatible)
390  
391 =item * L<Langertha::Engine::TranscriptionBase> - Slim base for OpenAI-shape
392 transcription-only engines (no chat / tools / embeddings / image generation).
393 L<Langertha::Engine::OpenAI> exposes a C<whisper> attribute returning an
394 instance of this class bound to the parent's C<api_key> / C<url>.
395  
396 =item * L<Langertha::Engine::Whisper> - Self-hosted Whisper-compatible
397 transcription server (extends TranscriptionBase)
398  
399 =back
400  
401 =head2 Roles
402  
403 Roles provide composable functionality to engines and to the wrapper classes:
404  
405 =over 4
406  
407 =item * L<Langertha::Role::Capabilities> - C<engine_capabilities> registry
408 plus C<supports($cap)> helper, composed by L<Langertha::Role::Chat>
409  
410 =item * L<Langertha::Role::Chat> - Synchronous and async chat methods,
411 including C<chat_f(messages =E<gt> [...], tools =E<gt> [...], tool_choice
412 =E<gt> ..., response_format =E<gt> ...)> for single-turn structured
413 calls and C<aggregate_tool_calls(\@chunks)> for streaming
414  
415 =item * L<Langertha::Role::ThinkTag> - Configurable C<E<lt>thinkE<gt>> tag
416 filtering for reasoning models, composed by L<Langertha::Role::Chat>
417  
418 =item * L<Langertha::Role::HTTP> - HTTP request/response handling
419  
420 =item * L<Langertha::Role::AsyncHTTP> - Async HTTP backend selection (injected client / Net::Async::HTTP / synchronous LWP fallback), composed by L<Langertha::Role::Chat>, L<Langertha::Role::Embedding>, L<Langertha::Role::Transcription>, L<Langertha::Role::ImageGeneration> and L<Langertha::Role::Runtime::MetricsPoll>
421  
422 =item * L<Langertha::Role::Streaming> - Streaming response processing
423  
424 =item * L<Langertha::Role::JSON> - JSON encode/decode
425  
426 =item * L<Langertha::Role::OpenAICompatible> - OpenAI-compatible API behaviour
427  
428 =item * L<Langertha::Role::AnthropicCompatible> - Anthropic-compatible API behaviour
429  
430 =item * L<Langertha::Role::ResponsesCompatible> - Open-Responses wire envelope (OpenAI /v1/responses, Perplexity Agent API)
431  
432 =item * L<Langertha::Role::SystemPrompt> - System prompt attribute
433  
434 =item * L<Langertha::Role::Temperature> - Temperature parameter
435  
436 =item * L<Langertha::Role::ResponseSize> - Max response size parameter
437  
438 =item * L<Langertha::Role::ResponseFormat> - Response format (JSON mode)
439  
440 =item * L<Langertha::Role::ReasoningEffort> - Request-side reasoning-effort control
441  
442 =item * L<Langertha::Role::PromptCache> - Request-side prompt-caching control
443  
444 =item * L<Langertha::Role::CachedContent> - Explicit cached-content resource
445 lifecycle (create/get/list/update/delete)
446  
447 =item * L<Langertha::Role::ContextSize> - Context window size parameter
448  
449 =item * L<Langertha::Role::Seed> - Deterministic seed parameter
450  
451 =item * L<Langertha::Role::Models> - Model listing
452  
453 =item * L<Langertha::Role::StaticModels> - Model listing from a hardcoded list,
454 for providers without a models endpoint
455  
456 =item * L<Langertha::Role::Embedding> - Embedding generation
457  
458 =item * L<Langertha::Role::Transcription> - Audio transcription
459  
460 =item * L<Langertha::Role::Tools> - Tool/function calling
461  
462 =item * L<Langertha::Role::HermesTools> - Hermes-style tool calling via
463 C<E<lt>tool_callE<gt>> XML tags for models without native API tool support
464  
465 =item * L<Langertha::Role::ParallelToolUse> - Parallel tool calling control
466  
467 =item * L<Langertha::Role::ServerTools> - Provider-native server-side tools
468 (C<server_tools> capability and per-engine defaults)
469  
470 =item * L<Langertha::Role::ImageGeneration> - Image generation
471  
472 =item * L<Langertha::Role::ImageInput> - Image input (vision), claimed per model
473  
474 =item * L<Langertha::Role::KeepAlive> - Keep-alive duration for local models
475  
476 =item * L<Langertha::Role::RuntimeKnobs> - Per-request prefix-cache runtime knobs
477 for self-hosted engines
478  
479 =item * L<Langertha::Role::Runtime::MetricsPoll> - Async Prometheus C</metrics>
480 scraper for self-hosted engines
481  
482 =item * L<Langertha::Role::PluginHost> - Plugin system for the wrapper classes
483 (and for L<Langertha::Raider> from the langertha-raider distribution)
484  
485 =item * L<Langertha::Role::Runnable> - Generic C<run_f($ctx)> execution contract,
486 a dependency-free core primitive (consumed by the Raid/Raider nodes in the
487 langertha-raider distribution)
488  
489 =item * L<Langertha::Role::Langfuse> - Engine-level Langfuse observability,
490 composed by L<Langertha::Role::Chat>
491  
492 =item * L<Langertha::Role::OpenAPI> - OpenAPI spec support
493  
494 =back
495  
496 =head2 Wrapper Classes
497  
498 These classes wrap an engine with optional overrides and plugin lifecycle hooks:
499  
500 =over 4
501  
502 =item * L<Langertha::Chat> - Chat wrapper with system prompt, model, and temperature overrides
503  
504 =item * L<Langertha::Embedder> - Embedding wrapper with optional model override
505  
506 =item * L<Langertha::ImageGen> - Image generation wrapper with model, size, and quality overrides
507  
508 =back
509  
510 =head2 Plugins
511  
512 =over 4
513  
514 =item * L<Langertha::Plugin> - Base class for all plugins
515  
516 =item * L<Langertha::Plugin::Langfuse> - Langfuse observability (traces, generations, spans)
517  
518 =back
519  
520 =head2 Data Objects
521  
522 =over 4
523  
524 =item * L<Langertha::Response> - LLM response with content, usage, and rate
525 limit metadata; C<tool_calls> is an ArrayRef of L<Langertha::ToolCall> and
526 the single source of truth for both native and synthesized tool calls
527  
528 =item * L<Langertha::Usage> - Token usage of one call (L<Langertha::Response/usage>),
529 normalized across providers, with cache reads/writes and whether the wire
530 counts them inside C<input_tokens>
531  
532 =item * L<Langertha::CallResult> - Result of an embedding, transcription or
533 image call (C<simple_embedding_result>, C<simple_transcription_call>,
534 C<simple_image_result>): the value plus usage, rate limit, model and timing
535  
536 =item * L<Langertha::Pricing> - Model-to-price catalogue that turns a
537 L<Langertha::Usage> into a L<Langertha::Cost>, with optional cache rates
538  
539 =item * L<Langertha::Cost> - Monetary cost of one call (input, output, cache
540 read/write, total)
541  
542 =item * L<Langertha::UsageRecord> - Ledger entry combining a
543 L<Langertha::Usage>, its L<Langertha::Cost> and request metadata
544  
545 =item * L<Langertha::ToolCall> - Canonical tool invocation produced by an
546 LLM, with C<synthetic> flag for forced-tool fallbacks
547  
548 =item * L<Langertha::ToolChoice> - Canonical tool-selection policy with
549 per-provider serializers (C<to_openai>, C<to_anthropic>, C<to_gemini>,
550 legacy C<to_perplexity>)
551  
552 =item * L<Langertha::Tool> - Canonical tool definition with cross-provider
553 serializers (C<to_openai>, C<to_anthropic>, C<to_gemini>, C<to_mcp>,
554 C<to_json_schema>) and accepting constructors (C<from_openai>,
555 C<from_anthropic>, C<from_mcp>, C<from_gemini>, C<from_hash>)
556  
557 =item * L<Langertha::ServerTool> - Provider-native server-side tool (web
558 search, file search, remote MCP, ...), pinned to its C<tool_wire_format>
559  
560 =item * L<Langertha::ServerToolCall> - Record of a tool call the provider ran
561 itself, on L<Langertha::Response/server_tool_calls> (never on C<tool_calls>)
562  
563 =item * L<Langertha::Content> / L<Langertha::Content::Image> -
564 Provider-agnostic vision input
565  
566 =item * L<Langertha::ModelProbe> - Reads model-scoped capability facts
567 (C<image_input>) from a provider's own model metadata, for
568 L<Langertha::Role::Capabilities/probe_model_capabilities_f>
569  
570 =item * L<Langertha::Manifest> - Provider manifest
571 (C</.well-known/langertha.json>) value object, parser and validator
572  
573 =item * L<Langertha::Manifest::Builder> - Builds a L<Langertha::Manifest>
574 offline from configured engines, never copying a secret
575  
576 =item * L<Langertha::RateLimit> - Normalized rate limit data from HTTP response headers
577  
578 =item * L<Langertha::Moment> - Instant reported by a provider
579 (L<Langertha::Response/created>); a L<Time::Moment> subclass that keeps the
580 sub-seconds and numifies to the Unix epoch
581  
582 =item * L<Langertha::Stream> - Iterator over streaming chunks
583  
584 =item * L<Langertha::Stream::Chunk> - A single chunk from a streaming
585 response (with optional C<tool_calls> for engines that emit them mid-stream)
586  
587 =item * L<Langertha::Request::HTTP> - Internal HTTP request object
588  
589 =back
590  
591 =head2 Streaming
592  
593 All engines that implement L<Langertha::Role::Chat> support streaming. There
594 are several ways to consume a stream:
595  
596 B<Synchronous with callback:>
597  
598 $engine->simple_chat_stream(sub {
599 my ($chunk) = @_;
600 print $chunk->content;
601 }, 'Tell me a story');
602  
603 B<Synchronous with iterator (L<Langertha::Stream>):>
604  
605 my $stream = $engine->simple_chat_stream_iterator('Tell me a story');
606 while (my $chunk = $stream->next) {
607 print $chunk->content;
608 }
609  
610 B<Async with Future (traditional):>
611  
612 my $future = $engine->simple_chat_f('Hello');
613 my $response = $future->get;
614  
615 my $future = $engine->simple_chat_stream_f('Tell me a story');
616 my ($content, $chunks) = $future->get;
617  
618 B<Async with Future::AsyncAwait (recommended):>
619  
620 use Future::AsyncAwait;
621  
622 async sub chat_with_ai {
623 my ($engine) = @_;
624 my $response = await $engine->simple_chat_f('Hello');
625 say "AI says: $response";
626 return $response;
627 }
628  
629 async sub stream_chat {
630 my ($engine) = @_;
631 my ($content, $chunks) = await $engine->simple_chat_stream_realtime_f(
632 sub { print shift->content },
633 'Tell me a story',
634 );
635 say "\nReceived ", scalar(@$chunks), " chunks";
636 return $content;
637 }
638  
639 chat_with_ai($engine)->get;
640 stream_chat($engine)->get;
641  
642 The C<_f> methods pick their HTTP backend through L<Langertha::Role::AsyncHTTP>:
643 an injected C<_async_http> client, else L<Net::Async::HTTP> on an L<IO::Async>
644 loop (both loaded lazily only when you call them), else a synchronous
645 L<LWP::UserAgent> fallback. The fallback keeps every C<_f> method working and
646 returning a L<Future>, but blocking and sequential, with no concurrency; install
647 L<Net::Async::HTTP> + L<IO::Async> for real async. See C<examples/async_await_example.pl> for
648 complete working examples.
649  
650 B<Using with Mojolicious:>
651  
652 use Mojo::Base -strict;
653 use Future::Mojo;
654 use Langertha::Engine::OpenAI;
655  
656 my $openai = Langertha::Engine::OpenAI->new(
657 api_key => $ENV{OPENAI_API_KEY},
658 model => 'a small fast model from your provider',
659 );
660  
661 my $future = $openai->simple_chat_stream_realtime_f(
662 sub { print shift->content },
663 'Hello!',
664 );
665 $future->on_done(sub {
666 my ($content, $chunks) = @_;
667 say "Done: $content";
668 });
669 Mojo::IOLoop->start;
670  
671 =head2 Response Metadata
672  
673 C<simple_chat> returns L<Langertha::Response> objects that stringify to text
674 content (backward compatible) but carry full metadata:
675  
676 my $r = $engine->simple_chat('Hello!');
677 print $r; # prints the text
678 say $r->model; # actual model used
679 say $r->prompt_tokens; # input tokens
680 say $r->completion_tokens; # output tokens
681 say $r->total_tokens; # total
682 say $r->finish_reason; # stop, end_turn, tool_calls, ...
683 say $r->thinking; # chain-of-thought (if available)
684  
685 =head2 Rate Limiting
686  
687 Rate limit information from HTTP response headers is extracted automatically
688 into L<Langertha::RateLimit> objects. Available per-response and on the engine:
689  
690 if ($r->has_rate_limit) {
691 say $r->requests_remaining;
692 say $r->tokens_remaining;
693 say $r->rate_limit->requests_reset;
694 }
695  
696 # Engine always reflects the latest response
697 say $engine->rate_limit->requests_remaining
698 if $engine->has_rate_limit;
699  
700 Supported: OpenAI, Groq, Cerebras, OpenRouter, Replicate, HuggingFace
701 (C<x-ratelimit-*>) and Anthropic (C<anthropic-ratelimit-*>).
702  
703 =head2 MCP Tool Calling
704  
705 Integrates with any L<Net::Async::MCP>-compatible client (for example a
706 L<Net::Async::MCP> client as used by the C<langertha-raider> distribution)
707 for automatic multi-round tool calling:
708  
709 my $engine = Langertha::Engine::OpenAI->new(
710 api_key => $ENV{OPENAI_API_KEY},
711 mcp_servers => [$mcp],
712 );
713  
714 my $response = await $engine->chat_with_tools_f('Search for Perl modules');
715  
716 Works with all engines that support tool calling. See L<Langertha::Role::Tools>.
717  
718 =head2 Raider (Autonomous Agent)
719  
720 L<Langertha::Raider> is a stateful agent with conversation history, MCP tool
721 calling, context compression, session history, and a plugin system. It ships
722 in the separate C<langertha-raider> distribution; install it to use the agent
723 and the C<use Langertha qw( Raider )> sugar:
724  
725 my $raider = Langertha::Raider->new(
726 engine => $engine,
727 mission => 'You are a code explorer.',
728 );
729  
730 my $r1 = await $raider->raid_f('What files are in lib/?');
731 my $r2 = await $raider->raid_f('Read the main module.');
732  
733 =head2 Langfuse Observability
734  
735 L<Langfuse|https://langfuse.com/> observability comes in two complementary
736 flavours. Both read C<LANGFUSE_PUBLIC_KEY>, C<LANGFUSE_SECRET_KEY> and the
737 optional C<LANGFUSE_URL> from the environment, and both stay inactive until
738 that key pair is set.
739  
740 =over 4
741  
742 =item * B<Engine level> -- L<Langertha::Role::Langfuse> is composed by
743 L<Langertha::Role::Chat>, so every chat engine carries it. It auto-instruments
744 the synchronous C<simple_chat> call and offers C<langfuse_trace>,
745 C<langfuse_span> and C<langfuse_generation> for instrumenting anything else.
746 L<Langertha::Raider> uses those to trace raids, iterations and tool calls.
747  
748 =item * B<Plugin level> -- L<Langertha::Plugin::Langfuse> attaches to any
749 L<Langertha::Role::PluginHost>, which is what the wrapper classes
750 L<Langertha::Chat>, L<Langertha::Embedder> and L<Langertha::ImageGen> are (as
751 is L<Langertha::Raider>). It needs no engine-level configuration and covers
752 the embedding and image-generation calls the engine role does not see:
753  
754 my $chat = Langertha::Chat->new(
755 engine => $engine,
756 plugins => ['Langfuse'],
757 );
758  
759 =back
760  
761 Transcription-only engines (L<Langertha::Engine::Whisper> and other
762 L<Langertha::Engine::TranscriptionBase> subclasses) compose neither
763 L<Langertha::Role::Chat> nor a plugin host, and so are not instrumented.
764  
765 =head2 Extensions
766  
767 The C<LangerthaX> namespace is reserved for third-party extensions. See
768 L<LangerthaX>.
769  
770 =head1 SUPPORT
771  
772 =head2 Issues
773  
774 Please report bugs and feature requests on GitHub at
775 L<https://github.com/Getty/langertha/issues>.
776  
777 =head2 IRC
778  
779 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
780  
781 =head1 CONTRIBUTING
782  
783 Contributions are welcome! Please fork the repository and submit a pull request.
784  
785 =head1 AUTHOR
786  
787 Torsten Raudssus <getty@cpan.org>
788  
789 =head1 COPYRIGHT AND LICENSE
790  
791 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
792  
793 This is free software; you can redistribute it and/or modify it under
794 the same terms as the Perl 5 programming language system itself.
795  
796 =cut
« blib/lib/Langertha/Moment.pm ↑ Summary blib/lib/Langertha/Engine/HuggingFace.pm »