Langertha.pm

filter: Statementstmt 97.2% 106 / 109 Branchbran 75.0% 24 / 32 Conditioncond 31.5% 6 / 19 MC/DCmcdc 0.0% 0 / 12 Subroutinesub 95.2% 20 / 21 Podpod 80.0% 4 / 5 totaltotal 80.8% 160 / 198 CC 27 SCAR 14.5
CC
27
Cov
85%
resolve_engine_class
8.2
import
6.0
discover_modules_in_scope
5.9
CRAP 4.3
« Langertha/Response.pm ↑ Summary Langertha/Role/ContextSize.pm »
1 package Langertha;
2 # ABSTRACT: The clan of fierce vikings with 🪓 and 🛡️ to AId your rAId
3 4 our $VERSION = '0.502';
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 Raider => sub {
17 5 ▶ my ( $caller ) = @_;
Subroutine __ANON__: called CC=1 SCAR=0.1
18 5 Moose->import::into($caller);
19 5 Future::AsyncAwait->import::into($caller);
20 5 $caller->meta->superclasses('Langertha::Raider');
21 5 $_sugar_plugins{$caller} = [];
22 4 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
23 5 *{"${caller}::plugin"} = sub {
24 5 ▶ push @{$_sugar_plugins{$caller}}, @_;
Subroutine __ANON__: called CC=1 SCAR=0.0
25 5 };
26 $caller->meta->add_method('_sugar_plugins' => sub {
27 0 ▶ return [@{$_sugar_plugins{$caller} // []}];
Subroutine __ANON__: not called CC=2 SCAR=10.9
Subroutine _sugar_plugins: called CC=2 SCAR=10.9
Condition25%1/4
$_sugar_plugins{$caller} // []
l!l
00
$_sugar_plugins{$caller} // []
l!l
40
MC/DC0%0/1
$_sugar_plugins{$caller} // []
$_sugar_plugins{$caller}
MC/DC0%0/1
$_sugar_plugins{$caller} // []
$_sugar_plugins{$caller}
Truth table0%0/2
A
A= $_sugar_plugins{$caller}
Aresult
11
00
Truth table50%1/2
A
A= $_sugar_plugins{$caller}
Aresult
11
00
28 5 });
29 },
30 Plugin => sub {
31 1 ▶ my ( $caller ) = @_;
Subroutine __ANON__: called CC=1 SCAR=0.0
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 sub import {
39 8 ▶ my ( $class, @args ) = @_;
Subroutine import: called CC=6 SCAR=17.9
40 8 ▶ return unless @args;
Branch: 1 branch
BranchTrueFalseTotal
unless @args 1 7 8
41 7 my $caller = caller;
42 7 for my $arg (@args) {
43 7 ▶ 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 6 7
44 or Carp::croak("Unknown Langertha import '$arg' (known: ".join(', ', sort keys %setup).")");
45 6 require Moose;
46 6 require Future::AsyncAwait;
47 6 ▶ use_module('Langertha::Raider') if $arg eq 'Raider';
Branch: 1 branch
BranchTrueFalseTotal
if $arg eq "Raider" 5 1 6
48 6 ▶ use_module('Langertha::Plugin') if $arg eq 'Plugin';
Branch: 1 branch
BranchTrueFalseTotal
if $arg eq "Plugin" 1 5 6
49 6 $setup->($caller);
50 }
51 }
52  
53 sub _module_path {
54 2 ▶ my ($module) = @_;
Subroutine _module_path: called CC=1 SCAR=0.0
55 2 my $path = $module;
56 2 $path =~ s{::}{/}g;
57 2 return $path . '.pm';
58 }
59  
60 sub _is_missing_module_error {
61 2 ▶ my ($err, $module) = @_;
Subroutine _is_missing_module_error: called CC=4 SCAR=15.6
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 sub discover_modules_in_scope {
68 7 ▶ my ($class, %args) = @_;
Subroutine discover_modules_in_scope: called CC=5 SCAR=17.8
Pod undocumented
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;
Branch: 1 branch
BranchTrueFalseTotal
defined $_ and length $_ and not $seen{$_}++ 231 0 231
Condition33%1/3
defined $_ and length $_
!ll&&!rl&&r
00231
MC/DC0%0/2
defined $_ and length $_
defined $_ length $_
Truth table33%1/3
A and B
A= defined $_B= length $_
ABresult
0X0
100
111
81 7 return [ sort @modules ];
82 }
83  
84 sub available_engine_classes {
85 7 ▶ my ($class) = @_;
Subroutine available_engine_classes: called CC=1 SCAR=0.0
Pod documented
86 7 return $class->discover_modules_in_scope(
87 search_path => ['Langertha::Engine', 'LangerthaX::Engine'],
88 );
89 }
90  
91 sub available_engine_ids {
92 1 ▶ my ($class) = @_;
Subroutine available_engine_ids: called CC=3 SCAR=11.0
Pod documented
93 1 my %ids;
94 1 for my $module (@{$class->available_engine_classes}) {
95 33 ▶ next unless $module =~ /::([^:]+)\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $module =~ /::([^:]+)\z/ 0 33 33
96 33 $ids{lc($1)} = 1;
97 }
98 1 return [ sort keys %ids ];
99 }
100  
101 sub resolve_engine_class {
102 6 ▶ my ($class, $engine) = @_;
Subroutine resolve_engine_class: called CC=8 SCAR=21.0
Pod documented
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 sub new_engine {
135 3 ▶ my ($class, $engine, @args) = @_;
Subroutine new_engine: called CC=4 SCAR=14.5
Pod documented
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.502
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 => 'llama3.1',
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 => 'gpt-4o-mini',
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 => 'claude-sonnet-4-6',
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 => 'gemini-2.5-flash',
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<24 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 via L<Net::Async::MCP>
221  
222 =item * B<Raider> -- autonomous agent with history, compression, and plugins
223  
224 =item * B<Response metadata> -- token usage, model, timing, rate limits
225  
226 =item * B<Async/await> via L<Future::AsyncAwait>, sync via L<LWP::UserAgent>
227  
228 =item * B<Langfuse observability> -- traces, generations, and tool spans
229  
230 =item * B<Dynamic model discovery> -- query provider APIs with caching
231  
232 =item * B<Chain-of-thought> -- native extraction and C<E<lt>thinkE<gt>> tag filtering
233  
234 =item * B<Plugin system> for extending Raider, Chat, Embedder, and ImageGen
235  
236 =back
237  
238 =head2 Class Sugar
239  
240 Langertha can set up your package as a Raider subclass or Plugin role:
241  
242 # Build a custom Raider agent
243 package MyAgent;
244 use Langertha qw( Raider );
245 plugin 'Langfuse';
246  
247 around plugin_before_llm_call => async sub {
248 my ($orig, $self, $conversation, $iteration) = @_;
249 $conversation = await $self->$orig($conversation, $iteration);
250 # ... custom logic ...
251 return $conversation;
252 };
253  
254 __PACKAGE__->meta->make_immutable;
255  
256 # Build a custom Plugin
257 package MyApp::Guardrails;
258 use Langertha qw( Plugin );
259  
260 around plugin_before_tool_call => async sub {
261 my ($orig, $self, $name, $input) = @_;
262 my @result = await $self->$orig($name, $input);
263 return unless @result;
264 return if $name eq 'dangerous_tool';
265 return @result;
266 };
267  
268 C<use Langertha qw( Raider )> imports L<Moose> and L<Future::AsyncAwait>,
269 sets L<Langertha::Raider> as superclass, and provides the C<plugin>
270 function for applying plugins by short name.
271  
272 C<use Langertha qw( Plugin )> imports L<Moose> and
273 L<Future::AsyncAwait>, and sets L<Langertha::Plugin> as superclass.
274  
275 =head2 Engine Discovery
276  
277 Langertha discovers engine modules in scope via L<Module::Pluggable> across
278 both namespaces:
279  
280 =over 4
281  
282 =item * C<Langertha::Engine::*>
283  
284 =item * C<LangerthaX::Engine::*>
285  
286 =back
287  
288 Useful class methods:
289  
290 =over 4
291  
292 =item * C<< Langertha->available_engine_classes >>
293  
294 Returns discovered fully-qualified engine class names.
295  
296 =item * C<< Langertha->available_engine_ids >>
297  
298 Returns discovered engine IDs (lowercased short names).
299  
300 =item * C<< Langertha->resolve_engine_class($name_or_class) >>
301  
302 Resolves short names (for example C<OpenAI>) with core-first lookup,
303 or accepts fully-qualified class names.
304  
305 =item * C<< Langertha->new_engine($name_or_class, %args) >>
306  
307 Resolves and constructs an engine instance in one call.
308  
309 =back
310  
311 =head2 Engine Modules
312  
313 =over 4
314  
315 =item * L<Langertha::Engine::Anthropic> - Claude models (Sonnet, Opus, Haiku)
316  
317 =item * L<Langertha::Engine::OpenAI> - GPT-4, GPT-4o, GPT-3.5, o1, embeddings
318  
319 =item * L<Langertha::Engine::Ollama> - Local LLM hosting via L<https://ollama.com/>
320  
321 =item * L<Langertha::Engine::Groq> - Fast inference API
322  
323 =item * L<Langertha::Engine::Mistral> - Mistral AI models
324  
325 =item * L<Langertha::Engine::DeepSeek> - DeepSeek models
326  
327 =item * L<Langertha::Engine::MiniMax> - MiniMax AI models (M2.7, M2.5, M2.1) via OpenAI-compatible endpoint
328  
329 =item * L<Langertha::Engine::MiniMaxAnthropic> - MiniMax via legacy Anthropic-compatible endpoint
330  
331 =item * L<Langertha::Engine::Gemini> - Google Gemini models (Flash, Pro)
332  
333 =item * L<Langertha::Engine::vLLM> - vLLM inference server
334  
335 =item * L<Langertha::Engine::SGLang> - SGLang inference server
336  
337 =item * L<Langertha::Engine::HuggingFace> - HuggingFace Inference Providers
338  
339 =item * L<Langertha::Engine::Perplexity> - Perplexity AI models
340  
341 =item * L<Langertha::Engine::NousResearch> - Nous Research (Hermes models)
342  
343 =item * L<Langertha::Engine::Cerebras> - Cerebras (wafer-scale, fastest inference)
344  
345 =item * L<Langertha::Engine::OpenRouter> - OpenRouter (300+ models, meta-provider)
346  
347 =item * L<Langertha::Engine::Replicate> - Replicate (thousands of open-source models)
348  
349 =item * L<Langertha::Engine::OllamaOpenAI> - Ollama via OpenAI-compatible API
350  
351 =item * L<Langertha::Engine::LlamaCpp> - llama.cpp server (chat, embeddings)
352  
353 =item * L<Langertha::Engine::LMStudio> - LM Studio native local REST API
354  
355 =item * L<Langertha::Engine::LMStudioOpenAI> - LM Studio via OpenAI-compatible API
356  
357 =item * L<Langertha::Engine::LMStudioAnthropic> - LM Studio via Anthropic-compatible API
358  
359 =item * L<Langertha::Engine::AKI> - AKI.IO native API (EU/Germany)
360  
361 =item * L<Langertha::Engine::AKIOpenAI> - AKI.IO via OpenAI-compatible API
362  
363 =item * L<Langertha::Engine::TSystems> - T-Systems AI Foundation Services / LLM Hub (EU/Germany)
364  
365 =item * L<Langertha::Engine::Scaleway> - Scaleway Generative APIs (EU)
366  
367 =item * L<Langertha::Engine::TranscriptionBase> - Slim base for OpenAI-shape
368 transcription-only engines (no chat / tools / embeddings / image generation).
369 L<Langertha::Engine::OpenAI> exposes a C<whisper> attribute returning an
370 instance of this class bound to the parent's C<api_key> / C<url>.
371  
372 =item * L<Langertha::Engine::Whisper> - Self-hosted Whisper-compatible
373 transcription server (extends TranscriptionBase)
374  
375 =back
376  
377 =head2 Roles
378  
379 Roles provide composable functionality to engines:
380  
381 =over 4
382  
383 =item * L<Langertha::Role::Capabilities> - C<engine_capabilities> registry
384 plus C<supports($cap)> helper, composed by L<Langertha::Role::Chat>
385  
386 =item * L<Langertha::Role::Chat> - Synchronous and async chat methods,
387 including C<chat_f(messages =E<gt> [...], tools =E<gt> [...], tool_choice
388 =E<gt> ..., response_format =E<gt> ...)> for single-turn structured
389 calls and C<aggregate_tool_calls(\@chunks)> for streaming
390  
391 =item * L<Langertha::Role::HTTP> - HTTP request/response handling
392  
393 =item * L<Langertha::Role::Streaming> - Streaming response processing
394  
395 =item * L<Langertha::Role::JSON> - JSON encode/decode
396  
397 =item * L<Langertha::Role::OpenAICompatible> - OpenAI-compatible API behaviour
398  
399 =item * L<Langertha::Role::SystemPrompt> - System prompt attribute
400  
401 =item * L<Langertha::Role::Temperature> - Temperature parameter
402  
403 =item * L<Langertha::Role::ResponseSize> - Max response size parameter
404  
405 =item * L<Langertha::Role::ResponseFormat> - Response format (JSON mode)
406  
407 =item * L<Langertha::Role::ContextSize> - Context window size parameter
408  
409 =item * L<Langertha::Role::Seed> - Deterministic seed parameter
410  
411 =item * L<Langertha::Role::Models> - Model listing
412  
413 =item * L<Langertha::Role::Embedding> - Embedding generation
414  
415 =item * L<Langertha::Role::Transcription> - Audio transcription
416  
417 =item * L<Langertha::Role::Tools> - Tool/function calling
418  
419 =item * L<Langertha::Role::HermesTools> - Hermes-style tool calling via
420 C<E<lt>tool_callE<gt>> XML tags for models without native API tool support
421  
422 =item * L<Langertha::Role::ImageGeneration> - Image generation
423  
424 =item * L<Langertha::Role::KeepAlive> - Keep-alive duration for local models
425  
426 =item * L<Langertha::Role::PluginHost> - Plugin system for wrapper classes and Raider
427  
428 =item * L<Langertha::Role::Langfuse> - Langfuse observability integration (engine-level)
429  
430 =item * L<Langertha::Role::OpenAPI> - OpenAPI spec support
431  
432 =back
433  
434 =head2 Wrapper Classes
435  
436 These classes wrap an engine with optional overrides and plugin lifecycle hooks:
437  
438 =over 4
439  
440 =item * L<Langertha::Chat> - Chat wrapper with system prompt, model, and temperature overrides
441  
442 =item * L<Langertha::Embedder> - Embedding wrapper with optional model override
443  
444 =item * L<Langertha::ImageGen> - Image generation wrapper with model, size, and quality overrides
445  
446 =back
447  
448 =head2 Plugins
449  
450 =over 4
451  
452 =item * L<Langertha::Plugin> - Base class for all plugins
453  
454 =item * L<Langertha::Plugin::Langfuse> - Langfuse observability (traces, generations, spans)
455  
456 =back
457  
458 =head2 Data Objects
459  
460 =over 4
461  
462 =item * L<Langertha::Response> - LLM response with content, usage, and rate
463 limit metadata; C<tool_calls> is an ArrayRef of L<Langertha::ToolCall> and
464 the single source of truth for both native and synthesized tool calls
465  
466 =item * L<Langertha::ToolCall> - Canonical tool invocation produced by an
467 LLM, with C<synthetic> flag for forced-tool fallbacks
468  
469 =item * L<Langertha::ToolChoice> - Canonical tool-selection policy with
470 per-provider serializers (C<to_openai>, C<to_anthropic>, C<to_gemini>,
471 C<to_perplexity>)
472  
473 =item * L<Langertha::Tool> - Canonical tool definition with cross-provider
474 serializers (C<to_openai>, C<to_anthropic>, C<to_gemini>, C<to_mcp>,
475 C<to_json_schema>) and accepting constructors (C<from_openai>,
476 C<from_anthropic>, C<from_mcp>, C<from_gemini>, C<from_hash>)
477  
478 =item * L<Langertha::Content> / L<Langertha::Content::Image> -
479 Provider-agnostic vision input
480  
481 =item * L<Langertha::RateLimit> - Normalized rate limit data from HTTP response headers
482  
483 =item * L<Langertha::Stream> - Iterator over streaming chunks
484  
485 =item * L<Langertha::Stream::Chunk> - A single chunk from a streaming
486 response (with optional C<tool_calls> for engines that emit them mid-stream)
487  
488 =item * L<Langertha::Raider> - Autonomous agent with history and tool calling
489  
490 =item * L<Langertha::Raider::Result> - Typed raid result (final, question, pause, abort)
491  
492 =item * L<Langertha::Request::HTTP> - Internal HTTP request object
493  
494 =back
495  
496 =head2 Streaming
497  
498 All engines that implement L<Langertha::Role::Chat> support streaming. There
499 are several ways to consume a stream:
500  
501 B<Synchronous with callback:>
502  
503 $engine->simple_chat_stream(sub {
504 my ($chunk) = @_;
505 print $chunk->content;
506 }, 'Tell me a story');
507  
508 B<Synchronous with iterator (L<Langertha::Stream>):>
509  
510 my $stream = $engine->simple_chat_stream_iterator('Tell me a story');
511 while (my $chunk = $stream->next) {
512 print $chunk->content;
513 }
514  
515 B<Async with Future (traditional):>
516  
517 my $future = $engine->simple_chat_f('Hello');
518 my $response = $future->get;
519  
520 my $future = $engine->simple_chat_stream_f('Tell me a story');
521 my ($content, $chunks) = $future->get;
522  
523 B<Async with Future::AsyncAwait (recommended):>
524  
525 use Future::AsyncAwait;
526  
527 async sub chat_with_ai {
528 my ($engine) = @_;
529 my $response = await $engine->simple_chat_f('Hello');
530 say "AI says: $response";
531 return $response;
532 }
533  
534 async sub stream_chat {
535 my ($engine) = @_;
536 my ($content, $chunks) = await $engine->simple_chat_stream_realtime_f(
537 sub { print shift->content },
538 'Tell me a story',
539 );
540 say "\nReceived ", scalar(@$chunks), " chunks";
541 return $content;
542 }
543  
544 chat_with_ai($engine)->get;
545 stream_chat($engine)->get;
546  
547 The C<_f> methods use L<IO::Async> and L<Net::Async::HTTP> internally, loaded
548 lazily only when you call them. See C<examples/async_await_example.pl> for
549 complete working examples.
550  
551 B<Using with Mojolicious:>
552  
553 use Mojo::Base -strict;
554 use Future::Mojo;
555 use Langertha::Engine::OpenAI;
556  
557 my $openai = Langertha::Engine::OpenAI->new(
558 api_key => $ENV{OPENAI_API_KEY},
559 model => 'gpt-4o-mini',
560 );
561  
562 my $future = $openai->simple_chat_stream_realtime_f(
563 sub { print shift->content },
564 'Hello!',
565 );
566 $future->on_done(sub {
567 my ($content, $chunks) = @_;
568 say "Done: $content";
569 });
570 Mojo::IOLoop->start;
571  
572 =head2 Response Metadata
573  
574 C<simple_chat> returns L<Langertha::Response> objects that stringify to text
575 content (backward compatible) but carry full metadata:
576  
577 my $r = $engine->simple_chat('Hello!');
578 print $r; # prints the text
579 say $r->model; # actual model used
580 say $r->prompt_tokens; # input tokens
581 say $r->completion_tokens; # output tokens
582 say $r->total_tokens; # total
583 say $r->finish_reason; # stop, end_turn, tool_calls, ...
584 say $r->thinking; # chain-of-thought (if available)
585  
586 =head2 Rate Limiting
587  
588 Rate limit information from HTTP response headers is extracted automatically
589 into L<Langertha::RateLimit> objects. Available per-response and on the engine:
590  
591 if ($r->has_rate_limit) {
592 say $r->requests_remaining;
593 say $r->tokens_remaining;
594 say $r->rate_limit->requests_reset;
595 }
596  
597 # Engine always reflects the latest response
598 say $engine->rate_limit->requests_remaining
599 if $engine->has_rate_limit;
600  
601 Supported: OpenAI, Groq, Cerebras, OpenRouter, Replicate, HuggingFace
602 (C<x-ratelimit-*>) and Anthropic (C<anthropic-ratelimit-*>).
603  
604 =head2 MCP Tool Calling
605  
606 Integrates with L<Net::Async::MCP> for automatic multi-round tool calling:
607  
608 my $engine = Langertha::Engine::OpenAI->new(
609 api_key => $ENV{OPENAI_API_KEY},
610 mcp_servers => [$mcp],
611 );
612  
613 my $response = await $engine->chat_with_tools_f('Search for Perl modules');
614  
615 Works with all engines that support tool calling. See L<Langertha::Role::Tools>.
616  
617 =head2 Raider (Autonomous Agent)
618  
619 L<Langertha::Raider> is a stateful agent with conversation history, MCP tool
620 calling, context compression, session history, and a plugin system:
621  
622 my $raider = Langertha::Raider->new(
623 engine => $engine,
624 mission => 'You are a code explorer.',
625 );
626  
627 my $r1 = await $raider->raid_f('What files are in lib/?');
628 my $r2 = await $raider->raid_f('Read the main module.');
629  
630 =head2 Langfuse Observability
631  
632 Every engine has L<Langfuse|https://langfuse.com/> observability built in.
633 Set C<LANGFUSE_PUBLIC_KEY> and C<LANGFUSE_SECRET_KEY> env vars to enable
634 auto-instrumented traces and generations. See L<Langertha::Role::Langfuse>.
635  
636 =head2 Extensions
637  
638 The C<LangerthaX> namespace is reserved for third-party extensions. See
639 L<LangerthaX>.
640  
641 =head1 SUPPORT
642  
643 =head2 Issues
644  
645 Please report bugs and feature requests on GitHub at
646 L<https://github.com/Getty/langertha/issues>.
647  
648 =head2 IRC
649  
650 Join C<#langertha> on C<irc.perl.org> or message Getty directly.
651  
652 =head1 CONTRIBUTING
653  
654 Contributions are welcome! Please fork the repository and submit a pull request.
655  
656 =head1 AUTHOR
657  
658 Torsten Raudssus <getty@cpan.org>
659  
660 =head1 COPYRIGHT AND LICENSE
661  
662 This software is copyright (c) 2026 by Torsten Raudssus L<https://raudssus.de/>.
663  
664 This is free software; you can redistribute it and/or modify it under
665 the same terms as the Perl 5 programming language system itself.
666  
667 =cut
« Langertha/Response.pm ↑ Summary Langertha/Role/ContextSize.pm »