blib/lib/Langertha/Engine/Perplexity.pm

filter: Statementstmt 100% 68 / 68 Branchbran 71.4% 20 / 28 Conditioncond 51.5% 17 / 33 MC/DCmcdc 17.6% 3 / 17 Subroutinesub 100% 16 / 16 Podpod 33.3% 1 / 3 totaltotal 75.7% 125 / 165 CC 31 SCAR 20.8
CC
31
Cov
81%
_responses_echo_item
16.9
__ANON__
8.9
_responses_extra_fields
8.2
CRAP 8.0
« blib/lib/Langertha/VLLMHook/Config.pm ↑ Summary blib/lib/Langertha/Manifest.pm »
1 package Langertha::Engine::Perplexity;
2 # ABSTRACT: Perplexity Agent API (search-augmented)
3 24 our $VERSION = '0.505';
4 24 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 24 ▶use Carp qw( croak );
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 24 extends 'Langertha::Engine::Remote';
8  
9 # Lean Agent-API engine (ADR 0016): parent = Remote for auth + HTTP + JSON only,
10 # NOT OpenAIBase — the Agent API is the Open-Responses envelope, not
11 # /chat/completions, so composing the OpenAI dialect (and its embeddings /
12 # whisper / model-list baggage, plus the inherited-but-wrong capability flags
13 # k138 catalogued) would be dishonest. The envelope lives in
14 # Role::ResponsesCompatible, composed here exactly as AnthropicBase composes
15 # Role::AnthropicCompatible. Role::ReasoningEffort::_build_reasoning_wire_format
16 # and Role::Tools::_build_tool_wire_format default to 'openai';
17 # ResponsesCompatible (composed last) supplies 'responses' for both (ADR 0015
18 # -excludes canon). Role::Tools: the Agent API takes client-executed
19 # type:function tools (karr k213); its built-in tools are not modelled here.
20 24 with 'Langertha::Role::Models',
21 'Langertha::Role::Temperature',
22 'Langertha::Role::ReasoningEffort' => { -excludes => ['_build_reasoning_wire_format'] },
23 'Langertha::Role::Tools' => { -excludes => ['_build_tool_wire_format'] },
24 'Langertha::Role::ResponseSize',
25 'Langertha::Role::SystemPrompt',
26 'Langertha::Role::ResponseFormat',
27 'Langertha::Role::Streaming',
28 # Role::Chat::content_format defaults to 'openai'; ResponsesCompatible supplies 'responses'.
29 'Langertha::Role::Chat' => { -excludes => ['content_format'] },
30 'Langertha::Role::StaticModels',
31 'Langertha::Role::ImageInput',
32 'Langertha::Role::ToolResultImages',
33 'Langertha::Role::ResponsesCompatible';
34  
35  
36 has '+url' => (
37 lazy => 1,
38 69 ▶ default => sub { 'https://api.perplexity.ai' },
Subroutine __ANON__: called CC=1 SCAR=0.0
39 24 );
40  
41 24 has api_key => (
42 is => 'ro',
43 lazy_build => 1,
44 );
45 1 ▶sub _build_api_key {
Subroutine _build_api_key: called CC=2 SCAR=7.2
46 1 my ( $self ) = @_;
47 return $ENV{LANGERTHA_PERPLEXITY_API_KEY}
48 1 ▶ || croak "".(ref $self)." requires LANGERTHA_PERPLEXITY_API_KEY or api_key set";
Condition50%1/2
$ENV{'LANGERTHA_PERPLEXITY_API_KEY'} || croak('' . ref($self) . ' requires LANGERTHA_PERPLEXITY_API_KEY or api_key set')
l!l
10
MC/DC0%0/1
$ENV{'LANGERTHA_PERPLEXITY_API_KEY'} || croak('' . ref($self) . ' requires LANGERTHA_PERPLEXITY_API_KEY or api_key set')
$ENV{'LANGERTHA_PERPLEXITY_API_KEY'}
Truth table50%1/2
A
A= $ENV{'LANGERTHA_PERPLEXITY_API_KEY'}
Aresult
11
00
49 }
50  
51  
52 102 ▶sub update_request {
Subroutine update_request: called CC=2 SCAR=7.1
Pod documented
53 102 my ( $self, $request ) = @_;
54 102 my $key = $self->api_key;
55 102 ▶ $request->header('Authorization', 'Bearer '.$key) if defined $key;
Branch: 1 branch
BranchTrueFalseTotal
if defined $key 102 0 102
56 }
57  
58  
59 39 ▶sub default_model { 'sonar' }
Subroutine default_model: called CC=1 SCAR=0.0
Pod undocumented
60  
61 # The four user-facing model ids, unchanged from the Sonar lineup. They are
62 # selectors only: _responses_model_kwargs maps each onto a preset for the wire.
63 1 ▶sub _build_static_models {[
Subroutine _build_static_models: called CC=1 SCAR=0.0
64 1 { id => 'sonar' },
65 { id => 'sonar-pro' },
66 { id => 'sonar-reasoning-pro' },
67 { id => 'sonar-deep-research' },
68 ]}
69  
70 # Doc-recommended model -> preset mapping (migrate-from-sonar guide 2026-09-10;
71 # live-confirmed k147, 2026-09-14). A preset is a routing label, not a model id:
72 # fast, low and medium all resolved to openai/gpt-5.6-luna on the wire, so the
73 # base model behind a preset is Perplexity's to change -- which is why the engine
74 # reports whatever $response->model returns rather than mapping it back (by
75 # 2026-09-29, k232, fast already resolved to openai/gpt-6-luna). high
76 # (sonar-deep-research) was not exercised (cost). reasoning.effort on the
77 # fast/low presets is ACCEPTED (HTTP 200, echoed as reasoning:{effort}) but
78 # spends no reasoning tokens there -- honored-as-accepted, a no-op on the
79 # non-reasoning presets, never a 400.
80 24 my %MODEL_TO_PRESET = (
81 'sonar' => 'fast',
82 'sonar-pro' => 'low',
83 'sonar-reasoning-pro' => 'medium',
84 'sonar-deep-research' => 'high',
85 );
86  
87 # Exactly one of model / models / preset is required. Emit the preset for a
88 # known sonar id (presets bundle web_search + citations); pass anything else
89 # straight through as `model` so a caller can target an explicit Agent
90 # model/preset by name.
91 106 ▶sub _responses_model_kwargs {
Subroutine _responses_model_kwargs: called CC=3 SCAR=11.2
92 106 my ( $self ) = @_;
93 106 ▶ my $model = $self->chat_model // $self->default_model;
Condition33%1/3
$self->chat_model // $self->default_model
l!l&&r!l&&!r
10600
MC/DC0%0/2
$self->chat_model // $self->default_model
$self->chat_model $self->default_model
Truth table33%1/3
A // B
A= $self->chat_modelB= $self->default_model
ABresult
1X1
011
000
94 106 ▶ if ( my $preset = $MODEL_TO_PRESET{$model} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $preset = $MODEL_TO_PRESET{$model}) 104 2 106
95 104 return ( preset => $preset );
96 }
97 2 return ( model => $model );
98 }
99  
100 # Structured output stays in the Chat-Completions shape at the TOP level of the
101 # body ({type:json_schema,json_schema:{name,schema,strict?}}) — NOT under
102 # text.format the way OpenAI's Responses engine wants it.
103 # Live-confirmed (k147): the top-level response_format=json_schema slot is
104 # honored, `strict` is enforced (the reply is exactly the schema, no extra
105 # keys), structured JSON is returned, and search still runs alongside it. The
106 # response_format.type enum is {json_schema,text} (see the json_object
107 # correction below).
108 9 ▶sub _responses_format_kwargs {
Subroutine _responses_format_kwargs: called CC=1 SCAR=0.0
109 9 my ( $self, $rf ) = @_;
110 9 return ( response_format => $rf );
111 }
112  
113 # Agent API input items are typed {type:"message",role,content}. Live-confirmed
114 # (k147): a bare {role,content} item (no type) is ALSO accepted (HTTP 200), so
115 # type:message is a safe superset rather than a hard requirement — stamp it
116 # anyway, the explicit form the docs show.
117 122 ▶sub _normalize_input_item {
Subroutine _normalize_input_item: called CC=1 SCAR=0.0
118 122 my ( $self, $msg ) = @_;
119 122 return { type => 'message', %$msg };
120 }
121  
122 # The Agent API is not an OpenAPI-spec engine here: POST the built body straight
123 # to /v1/agent (Remote's generate_http_request), rather than resolving an
124 # operation id against a spec the way OpenAIResponses does.
125 # Live-confirmed (k147): creation is POST /v1/agent (HTTP 200). The reply is an
126 # object:"response" with a resp_ id, store:true and background:false — the
127 # Open-Responses store shape — so retrieval would follow /v1/responses/{id},
128 # not /v1/agent/{id}. Retrieve/background is not implemented here and was not
129 # exercised (stateful; no cheap probe).
130 102 ▶sub _responses_dispatch {
Subroutine _responses_dispatch: called CC=1 SCAR=0.0
131 102 my ( $self, $response_call, @request_args ) = @_;
132 102 return $self->generate_http_request(
133 POST => $self->url.'/v1/agent',
134 $response_call,
135 @request_args,
136 );
137 }
138  
139 # Citations. The classic Sonar top-level citations[] is gone; the Agent API
140 # carries sources in an output[] item of type search_results, each result a
141 # {id,url,title,snippet,date,last_updated,source} hash. Lift them onto
142 # Response.citations.
143 # Live-confirmed (k147): inline markers are [1] (NOT [web:1]); the message
144 # output_text part carries an annotations[] that came back empty, so the
145 # search_results block is the authoritative source list, exactly as assumed
146 # here. A structured (json_schema) reply still emits the search_results block.
147 49 ▶sub _responses_extra_fields {
Subroutine _responses_extra_fields: called CC=8 SCAR=21.0
148 49 my ( $self, $data ) = @_;
149 49 my @citations;
150 49 ▶ for my $item ( @{ $data->{output} // [] } ) {
Condition100%2/2
$$data{"output"} // []
l!l
463
MC/DC100%1/1
$$data{"output"} // []
$$data{"output"}
Truth table100%2/2
A
A= $$data{"output"}
Aresult
11
00
151 62 ▶ next unless ref($item) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $item eq "HASH" 0 62 62
152 62 ▶ next unless ( $item->{type} // '' ) eq 'search_results';
Branch: 1 branch
BranchTrueFalseTotal
unless ($$item{"type"} // "") eq "search_results" 51 11 62
Condition50%1/2
$$item{"type"} // ""
l!l
620
MC/DC0%0/1
$$item{"type"} // ""
$$item{"type"}
Truth table50%1/2
A
A= $$item{"type"}
Aresult
11
00
153 11 ▶ push @citations, @{ $item->{results} // [] };
Condition50%1/2
$$item{"results"} // []
l!l
110
MC/DC0%0/1
$$item{"results"} // []
$$item{"results"}
Truth table50%1/2
A
A= $$item{"results"}
Aresult
11
00
154 }
155 49 ▶ return @citations ? ( citations => \@citations ) : ();
Branch: 1 branch
BranchTrueFalseTotal
@citations ? : 11 38 49
156 }
157  
158 # Agent API echo filter (karr k213, ADR 0020 k213 Update). The Agent input is
159 # a closed oneOf of message | function_call | function_call_output, and a
160 # message part is only input_text / input_image (OpenAPI for POST /v1/agent,
161 # fetched 2026-09-25). Live-confirmed (k232, 2026-09-29): the echo this builds
162 # -- the call verbatim with its fc_ id and status, a preamble flattened to
163 # string content, search_results left out -- is accepted (HTTP 200); captures in
164 # t/data/perplexity_agent_*. The Responses echo replays every
165 # output[] item, which on a preset turn includes search_results /
166 # fetch_url_results / *_results / mcp_* items and an assistant message of
167 # output_text parts -- all off-schema as input. Keep the calls (thought_signature
168 # included, as Perplexity's own sample replays them), flatten an assistant
169 # message to its text, drop everything else.
170 22 ▶sub _responses_echo_item {
Subroutine _responses_echo_item: called CC=12 SCAR=28.3
171 22 my ( $self, $item ) = @_;
172 22 ▶ my $type = $item->{type} // '';
Condition50%1/2
$$item{"type"} // ""
l!l
220
MC/DC0%0/1
$$item{"type"} // ""
$$item{"type"}
Truth table50%1/2
A
A= $$item{"type"}
Aresult
11
00
173 22 ▶ return $item if $type eq 'function_call' || $type eq 'function_call_output';
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "function_call" or $type eq "function_call_output" 11 11 22
Condition66%2/3
$type eq "function_call" or $type eq "function_call_output"
l!l&&r!l&&!r
11011
MC/DC50%1/2
$type eq "function_call" or $type eq "function_call_output"
$type eq "function_call" $type eq "function_call_output"
Truth table66%2/3
A or B
A= $type eq "function_call"B= $type eq "function_call_output"
ABresult
1X1
011
000
174 11 ▶ return () unless $type eq 'message';
Branch: 1 branch
BranchTrueFalseTotal
unless $type eq "message" 8 3 11
175 3 my $content = $item->{content};
176 my $text = ref $content eq 'ARRAY'
177 3 ▶ ? join( '', map { $_->{text} // '' }
Condition50%1/2
$$_{"text"} // ""
l!l
30
MC/DC0%0/1
$$_{"text"} // ""
$$_{"text"}
Truth table50%1/2
A
A= $$_{"text"}
Aresult
11
00
178 3 ▶ grep { ref $_ eq 'HASH' && ( $_->{type} // '' ) eq 'output_text' } @$content )
Branch: 1 branch
BranchTrueFalseTotal
ref $content eq 'ARRAY' ? : 3 0 3
Condition28%2/7
ref $_ eq 'HASH' && ($$_{'type'} // '') eq 'output_text'
!ll&&!rl&&r
003
$$_{"type"} // ""
l!l
30
$content // ""
l!l
00
MC/DC0%0/2
ref $_ eq 'HASH' && ($$_{'type'} // '') eq 'output_text'
ref $_ eq 'HASH' $$_{"type"}
MC/DC0%0/1
$content // ""
$content
Truth table33%1/3
A && B
A= ref $_ eq 'HASH'B= $$_{"type"}
ABresult
0X0
100
111
Truth table0%0/2
A
A= $content
Aresult
11
00
179 : ( $content // '' );
180 3 ▶ return () unless length $text;
Branch: 1 branch
BranchTrueFalseTotal
unless length $text 0 3 3
181 3 ▶ return { type => 'message', role => ( $item->{role} // 'assistant' ), content => $text };
Condition50%1/2
$$item{"role"} // "assistant"
l!l
30
MC/DC0%0/1
$$item{"role"} // "assistant"
$$item{"role"}
Truth table50%1/2
A
A= $$item{"role"}
Aresult
11
00
182 }
183  
184 # The Agent API's response_format enum is {json_schema,text} — no json_object
185 # (live-confirmed k147: a json_object body -> HTTP 400 "validation failed:
186 # response_format.type must be one of json_schema, text"), so clear the flag
187 # Role::ResponseFormat advertises by default. The Agent request schema has no
188 # tool_choice and no parallel_tool_calls field (karr k213, docs only), so clear
189 # every tool_choice_* flag and parallel_tool_use that Role::Tools brings: the
190 # envelope then never sends either field, and with tool_choice_named off chat_f
191 # still reroutes a forced tool through json_schema (Perplexity stays the ADR
192 # 0005 direction-1 exemplar). Everything else is honest by composition: no
193 # Role::PromptCache (prompt_cache / prompt_cache_key stay off — caching is
194 # automatic), no Role::ServerTools, Role::ReasoningEffort composed so
195 # reasoning_effort is on (wire reasoning.effort via the responses format).
196 426 ▶around engine_capabilities => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
197 426 my ( $orig, $self, @rest ) = @_;
198 426 my $caps = $self->$orig(@rest);
199 426 delete $caps->{$_} for qw(
200 response_format_json_object
201 tool_choice_auto tool_choice_any tool_choice_none tool_choice_named
202 parallel_tool_use
203 );
204 426 return $caps;
205 24 };
206  
207 # image_input (k266, ADR 0019 k266 Update): the Agent API takes input_image
208 # parts (k267), but a sonar id is a preset whose base model is Perplexity's to
209 # change, so only an explicit third-party id from an all-vision family claims
210 # (llm-advisor, docs only, 2026-09-25). Open-weight gpt-oss is text-only.
211 394 ▶sub model_capability_corrections {
Subroutine model_capability_corrections: called CC=1 SCAR=0.0
Pod undocumented
212 return (
213 394 qr/\A/ => { image_input => 0 },
214 qr{\A(?:openai|anthropic|google)/} => { image_input => 1 },
215 qr{\Aopenai/gpt-oss} => { image_input => 0 },
216 );
217 }
218  
219 # Tool-result PDFs (karr k361): the Agent API's FunctionCallOutputInput.output
220 # is "a JSON string or an array of input_text and input_image content parts",
221 # and no input schema lists input_file (docs.perplexity.ai/api-reference/
222 # agent-post, fetched 2026-09-30), so a PDF stays the k336 placeholder while
223 # OpenAIResponses sends it as input_file. So this engine composes
224 # Role::ToolResultImages (input_image is documented there) but not
225 # Role::ToolResultPDF: this is where the shared Responses envelope diverges
226 # (ADR 0039, k380).
227  
228 # Rate limit (karr k356, ADR 0022): the Agent API sends x-ratelimit-limit /
229 # -remaining / -reset / -used with no -requests / -tokens suffix, and the Remote
230 # fallback reads only Retry-After. Read here, not in a shared parser: on
231 # Perplexity -reset is an epoch-seconds instant (the k232 captures put it one
232 # second after their own Date header), while other senders of the same names use
233 # other kinds (OpenRouter an epoch-ms, the IETF RateLimit draft delta-seconds),
234 # and ADR 0022 declines guessing the kind by magnitude. used=1 after one request
235 # makes it the requests bucket. -used stays in raw; retry_after is derived from
236 # raw as on every engine.
237 44 ▶around _parse_rate_limit_headers => sub {
Subroutine __ANON__: called CC=8 SCAR=21.8
238 44 my ( $orig, $self, $http_response ) = @_;
239 44 require Langertha::RateLimit;
240 44 require Langertha::Moment;
241 44 my %raw = Langertha::RateLimit::_collect_headers($http_response);
242 44 my ( $limit, $remaining, $reset ) = @raw{ map { "x-ratelimit-$_" } qw( limit remaining reset ) };
243 44 ▶ return $self->$orig($http_response) unless defined $limit || defined $remaining || defined $reset;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $limit or defined $remaining or defined $reset 30 14 44
Condition66%4/6
defined $limit or defined $remaining or defined $reset
l!l&&r!l&&!r
14030
defined $limit or defined $remaining
l!l&&r!l&&!r
14030
MC/DC33%1/3
defined $limit or defined $remaining or defined $reset
defined $limit defined $remaining defined $reset
Truth table50%2/4
A or B or C
A= defined $limitB= defined $remainingC= defined $reset
ABCresult
1XX1
01X1
0011
0000
244 14 my $reset_at = Langertha::Moment->from_wire($reset);
245 14 ▶ return Langertha::RateLimit->new(
Branch: 4 branches
BranchTrueFalseTotal
defined $limit ? : 14 0 14
defined $remaining ? : 14 0 14
defined $reset ? : 14 0 14
defined $reset_at ? : 14 0 14
246 received => Langertha::Moment->now_utc,
247 ( defined $limit ? ( requests_limit => $limit + 0 ) : () ),
248 ( defined $remaining ? ( requests_remaining => $remaining + 0 ) : () ),
249 ( defined $reset ? ( requests_reset => $reset ) : () ),
250 ( defined $reset_at ? ( requests_reset_at => $reset_at ) : () ),
251 raw => \%raw,
252 );
253 24 };
254  
255 24 __PACKAGE__->meta->make_immutable;
256  
257  
258 24 1;
259  
260 __END__
« blib/lib/Langertha/VLLMHook/Config.pm ↑ Summary blib/lib/Langertha/Manifest.pm »