Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

perplexity.test.ts

955 lines32.4 KB

1import { afterEach, describe, expect, it } from 'vitest'
2​
3import { classifyAndBundle } from '../../ingest/sync.ts'
4import {
5 parsePerplexityModelsPage,
6 parsePerplexityEffortLevels,
7 provider,
8} from './perplexity.ts'
9​
10const MODELS_URL = 'https://api.perplexity.ai/v1/models'
11const DOC_URL = 'https://docs.perplexity.ai/docs/agent-api/models.md'
12const EFFORT_URL = 'https://docs.perplexity.ai/docs/agent-api/effort.md'
13​
14const HEADER = [
15 '| Model | Input (\\$/1M) | Output (\\$/1M) | Cache read (\\$/1M) | Service tiers | Docs |',
16 '| - | - | - | - | - | - |',
18​
19// One quote level more: how a `> [tab]` blockquote holds its card, table
20// and callouts.
21const quote = (lines: Array<string>): Array<string> =>
22 lines.map((line) => (line === '' ? '>' : `> ${line}`))
23​
24// Five tabs of the Agent API models page, as served on 2026-10-07, in the
25// markdown export's shape since 2026-10-30: each tab is one `> [tab] Title`
26// blockquote holding the card as a `> [card] Title` blockquote, the table,
27// and the effort note as a `> [!NOTE]` callout.
28const MODELS_DOC = [
29 '## Available Models',
30 '',
31 '> [tab] xAI',
32 ...quote([
33 '',
34 '> [card] xAI',
35 '>',
36 '> Grok 4.7, 4.6, 4.5, 4.3, and 4.20 variants: flagship, reasoning, non-reasoning, and multi-agent.',
37 '',
38 ...HEADER,
39 '| `xai/grok-4.20-non-reasoning` | 1.25 (\\<200k)<br />2.50 (≥200k) | 2.50 (\\<200k)<br />5.00 (≥200k) | 0.20 | — | [Grok 4.20 Non Reasoning](https://docs.x.ai/developers/models) |',
40 ]),
41 '',
42 '> [tab] Z.AI',
43 ...quote([
44 '',
45 '> [card] Z.AI',
46 '>',
47 '> GLM 5.3 and GLM 5.3 Flash — Z.AI reasoning models.',
48 '',
49 ...HEADER,
50 '| `perplexity/glm-5.3` | 1.40 | 4.40 | 0.26 | — | [GLM](https://docs.z.ai) |',
51 '| `perplexity/glm-5.3-flash` | 0.15 | 0.50 | 0.03 | — | [GLM-5.3 Flash](https://huggingface.co/zai-org/GLM-5.3-Flash) |',
52 ]),
53 '',
54 '> [tab] Moonshot AI',
55 ...quote([
56 '',
57 '> [card] Moonshot AI',
58 '>',
59 "> Kimi K3 — Moonshot AI's flagship reasoning model.",
60 '',
61 ...HEADER,
62 '| `perplexity/kimi-k3` | 3.00 | 15.00 | 0.30 | — | [Kimi K3](https://huggingface.co/moonshotai/Kimi-K3) |',
63 '',
64 '> [!NOTE]',
65 '>',
66 '> Kimi K3 accepts `minimal`, `low`, `medium`, `high`, `xhigh`, and `max` reasoning effort. `minimal` uses low effort, while `xhigh` and `max` use maximum effort. Reasoning tokens are billed at the output-token rate.',
67 ]),
68 '',
69 '> [tab] NVIDIA',
70 ...quote([
71 '',
72 '> [card] NVIDIA',
73 '>',
74 '> Nemotron 3 Ultra is an open-weight reasoning model.',
75 '',
76 ...HEADER,
77 '| `perplexity/nemotron-3-ultra-550b-a55b` | 0.25 | 2.50 | 0.25 | — | [Nemotron 3 Ultra](https://huggingface.co/nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-BF16) |',
78 ]),
79 '',
80 '> [tab] Perplexity',
81 ...quote([
82 '',
83 '> [card] Perplexity',
84 '>',
85 "> Perplexity's grounded search model.",
86 '',
87 ...HEADER,
88 '| `perplexity/sonar` | 0.25 | 2.50 | 0.0625 | — | — |',
89 ]),
90 '',
91 '## Service tiers',
92 '',
93 '> [!WARNING]',
94 '>',
95 '> Not all third-party models support all features (e.g., reasoning, tools). Check model documentation for specific capabilities.',
96].join('\n')
97​
98const KIMI_SENTENCE =
99 'Kimi K3 accepts `minimal`, `low`, `medium`, `high`, `xhigh`, and `max` reasoning effort.'
100​
101describe('parsePerplexityModelsPage', () => {
102 it('reads the effort sentence and the reasoning-model cards', () => {
103 const page = parsePerplexityModelsPage(MODELS_DOC)
104 expect([...page.flags]).toEqual([
105 ['perplexity/glm-5.3', ['reasoning']],
106 ['perplexity/glm-5.3-flash', ['reasoning']],
107 ['perplexity/kimi-k3', ['reasoning', 'reasoning_effort']],
108 ['perplexity/nemotron-3-ultra-550b-a55b', ['reasoning']],
109 ])
110 expect([...page.efforts]).toEqual([
111 [
112 'perplexity/kimi-k3',
113 ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'],
114 ],
115 ])
116 })
117​
118 it('reads a reasoning-model card that goes on to state other facts', () => {
119 // The NVIDIA tab as served on 2026-10-15.
120 const nvidia = MODELS_DOC.replace(
121 /^> > Nemotron 3 Ultra[^]*?(?=> \[tab\] Perplexity)/m,
122 [
123 ...quote([
124 '> Nemotron 3.5 Super is a reasoning model with a 1,048,576-token context window and up to 131,072 output tokens. It accepts text input only.',
125 '',
126 ...HEADER,
127 '| `perplexity/nemotron-3.5-super-120b-a12b` | 0.20 | 0.50 | 0.04 | — | — |',
128 ]),
129 '',
130 '',
131 ].join('\n'),
132 )
133 expect(nvidia).not.toBe(MODELS_DOC)
134 const page = parsePerplexityModelsPage(nvidia)
135 expect(page.flags.get('perplexity/nemotron-3.5-super-120b-a12b')).toEqual([
136 'reasoning',
137 ])
138 expect(page.flags.has('perplexity/nemotron-3-ultra-550b-a55b')).toBe(false)
139 // The same sentence's limits are that model's, and no other row's.
140 expect([...page.limits]).toEqual([
141 [
142 'perplexity/nemotron-3.5-super-120b-a12b',
143 { contextWindow: 1_048_576, maxOutput: 131_072 },
144 ],
145 ])
146 })
147​
148 it('reads a card that states the reasoning model after a comma (#100006)', () => {
149 // The DeepSeek tab as served on 2026-11-18.
150 const deepseek = MODELS_DOC.replace(
151 /^> \[tab\] NVIDIA\n[^]*?(?=> \[tab\] Perplexity)/m,
152 [
153 '> [tab] DeepSeek',
154 ...quote([
155 '',
156 '> [card] DeepSeek',
157 '>',
158 '> DeepSeek V4 Pro, an open-weight reasoning model.',
159 '',
160 ...HEADER,
161 '| `perplexity/deepseek-v4-pro-0813` | 1.32 | 3.96 | 0.044 | — | — |',
162 ]),
163 '',
164 '',
165 ].join('\n'),
166 )
167 expect(deepseek).not.toBe(MODELS_DOC)
168 const page = parsePerplexityModelsPage(deepseek)
169 expect(page.flags.get('perplexity/deepseek-v4-pro-0813')).toEqual([
170 'reasoning',
171 ])
172 expect(page.limits.size).toBe(0)
173 })
174​
175 it('leaves the effort flag off when no tab states an effort', () => {
176 const silent = MODELS_DOC.replace(
177 /^>\n> > \[!NOTE\]\n> >\n> > Kimi K3[^\n]*\n/m,
178 '',
179 )
180 const page = parsePerplexityModelsPage(silent)
181 expect(page.flags.get('perplexity/kimi-k3')).toEqual(['reasoning'])
182 expect(page.efforts.size).toBe(0)
183 })
184​
185 it.each([
186 ['a reworded sentence', 'Kimi K3 accepts', 'Kimi K3 supports'],
187 [
188 'a list with prose in it',
189 '`xhigh`, and `max`',
190 '`xhigh`, and up to `max`',
191 ],
192 ['a name no row carries', 'Kimi K3 accepts', 'Kimi K4 accepts'],
193 [
194 'a second, unread mention',
195 'output-token rate.',
196 'output-token rate.\n> >\n> > GLM takes any reasoning effort.',
197 ],
198 [
199 'a second sentence for the same model',
200 'output-token rate.',
201 'output-token rate.\n> >\n> > Kimi K3 accepts `low` and `high` reasoning effort.',
202 ],
203 [
204 'the sentence moved outside the tabs',
205 /^>\n> > \[!NOTE\]\n> >\n> > Kimi K3 accepts[^\n]*\n([^]*?## Service tiers\n)/m,
206 `$1\n${KIMI_SENTENCE}\n`,
207 ],
208 [
209 'a statement that reasoning cannot be disabled',
210 'reasoning effort. `minimal`',
211 'reasoning effort. Reasoning cannot be disabled. `minimal`',
212 ],
213 [
214 'a statement that the model always thinks',
215 "Kimi K3 — Moonshot AI's flagship reasoning model.",
216 "Kimi K3 — Moonshot AI's flagship always-on reasoning model.",
217 ],
218 [
219 'a card naming fewer models than its tab lists',
220 'GLM 5.3 and GLM 5.3 Flash — Z.AI',
221 'GLM 5.3 — Z.AI',
222 ],
223 [
224 'a card that denies it',
225 'is an open-weight reasoning model',
226 'is not a reasoning model',
227 ],
228 [
229 'a reworded card',
230 'is an open-weight reasoning model.',
231 'ranks among open reasoning models, in our tests.',
232 ],
233 [
234 'a card with a second sentence on reasoning models',
235 'is an open-weight reasoning model.',
236 'is an open-weight reasoning model. It replaces our older reasoning models.',
237 ],
238 [
239 'a second card sentence on thinking',
240 'is an open-weight reasoning model.',
241 'is an open-weight reasoning model. You cannot turn its thinking off.',
242 ],
243 [
244 'a "with" clause on reasoning',
245 'is an open-weight reasoning model.',
246 'is an open-weight reasoning model with reasoning off by default.',
247 ],
248 [
249 'a "with" clause on whether thinking can be skipped',
250 'is an open-weight reasoning model.',
251 'is an open-weight reasoning model with a mandatory chain-of-thought.',
252 ],
253 [
254 'a "with" clause in another shape',
255 'is an open-weight reasoning model.',
256 'is an open-weight reasoning model with a chain-of-thought you cannot skip.',
257 ],
258 [
259 'a card titled for another tab',
260 '> > [card] NVIDIA',
261 '> > [card] Nemotron',
262 ],
263 [
264 'a card with no spacer line',
265 '> > [card] Z.AI\n> >\n',
266 '> > [card] Z.AI\n',
267 ],
268 ['a tab title in another shape', '> [tab] Z.AI\n', '> [tabs] Z.AI\n'],
269 ['a tab with no spacer line', '> [tab] Z.AI\n>\n', '> [tab] Z.AI\n'],
270 [
271 'a card split by a blank line',
272 '> > Nemotron 3 Ultra is',
273 '> > NVIDIA Nemotron.\n>\n> > Nemotron 3 Ultra is',
274 ],
275 ['a card and table outside any tab', '> [tab] xAI\n>\n', ''],
276 [
277 'a callout split from its tab by a blank line',
278 '\n\n> [tab] NVIDIA',
279 '\n\n> > [!NOTE]\n> >\n> > Reasoning cannot be disabled on GLM 5.3.\n\n> [tab] NVIDIA',
280 ],
281 [
282 'prose between tabs',
283 '\n\n> [tab] NVIDIA',
284 '\n\nThinking is always on for Z.AI models.\n\n> [tab] NVIDIA',
285 ],
286 [
287 'a bold tab title and card, as the export wrote them before 2026-10-30',
288 '> [tab] Z.AI\n>\n> > [card] Z.AI',
289 '**Z.AI**\n\n> **Z.AI**',
290 ],
291 [
292 'a card that goes on with a clause other than "with"',
293 'is an open-weight reasoning model.',
294 'is an open-weight reasoning model for agents.',
295 ],
296 ])('throws on %s', (_case, from, to) => {
297 const mutated = MODELS_DOC.replace(from, to)
298 expect(mutated).not.toBe(MODELS_DOC)
299 expect(() => parsePerplexityModelsPage(mutated)).toThrow('unread shape')
300 })
301​
302 it('reads only the Available Models section', () => {
303 const later = [
304 MODELS_DOC,
305 '',
306 '> [tab] Extra',
307 ...quote([
308 '',
309 '> [card] Extra',
310 '>',
311 '> Extra is a reasoning model.',
312 '',
313 ...HEADER,
314 '| `perplexity/extra` | 1 | 1 | 1 | — | — |',
315 ]),
316 ].join('\n')
317 expect(parsePerplexityModelsPage(later).flags.has('perplexity/extra')).toBe(
318 false,
319 )
320 })
321​
322 it('throws on a page with no model table, such as an HTML error page', () => {
323 expect(() => parsePerplexityModelsPage('<html>Not found</html>')).toThrow(
324 'lists no models',
325 )
326 })
327})
328​
329// Three of the five effort levels as served on 2026-10-22, when the
330// presets page became the effort page, in the markdown export's shape since
331// 2026-10-30: each accordion is one `> [accordion] title` blockquote.
332// Bullets are trimmed, and only `fast` keeps its prompt block, cut to one
333// `## ` heading; the real blocks also hold SDK code samples.
334const EFFORT_DOC = [
335 '## Current effort level values',
336 '',
337 '> [accordion] fast — current effort level values',
338 '>',
339 '> Quick factual lookups with minimal latency and inline citations for search-backed claims.',
340 '>',
341 '> * **Model:** `openai/gpt-6-luna`',
342 '> * **Prompt cache key:** `fast`',
343 '> * **Max steps:** 1',
344 '> * **Reasoning effort:** `none`',
345 '> * **Service tier:** `priority`',
346 '> * **Max output tokens:** 8192',
347 '> * **Tools:** `web_search`',
348 '> * **System prompt:** included inline below',
349 '>',
350 '> ```text',
351 '> ## Role',
352 '> ```',
353 '',
354 '> [accordion] low — current effort level values',
355 '>',
356 '> * **Model:** `openai/gpt-6-luna`',
357 '> * **Reasoning effort:** `minimal`',
358 '> * **Tools:** `web_search`, `fetch_url` (`max_urls: 1`)',
359 '',
360 '> [accordion] xhigh — current effort level values',
361 '>',
362 '> * **Model:** `anthropic/claude-opus-5-5`',
363 '> * **Max steps:** 100',
364 '> * **Reasoning effort:** `high`',
365 '> * **Tools:** `web_search`, `finance_search`, `sandbox`',
366 '',
367 '## Next Steps',
368 '',
369 '> **[Agent API Models](/docs/agent-api/models)**',
370].join('\n')
371​
372describe('parsePerplexityEffortLevels', () => {
373 it('reads each effort level model with the effort and tools it runs with', () => {
374 expect([...parsePerplexityEffortLevels(EFFORT_DOC)]).toEqual([
375 ['openai/gpt-6-luna', ['reasoning', 'reasoning_effort', 'tools']],
376 ['anthropic/claude-opus-5-5', ['reasoning', 'reasoning_effort', 'tools']],
377 ])
378 })
379​
380 // The change served on 2026-10-29, trimmed like EFFORT_DOC: `fast` and
381 // `xhigh` name a fallback model, and `ultra-preview` names no model (its
382 // code samples are cut).
383 const FALLBACK_DOC = EFFORT_DOC.replace(
384 '> * **Model:** `openai/gpt-6-luna`\n> * **Prompt cache key:** `fast`',
385 '> * **Models:** `openai/gpt-6-luna`, with `openai/gpt-5.6-luna` as the [fallback model](https://docs.perplexity.ai/docs/agent-api/model-fallback.md)\n> * **Prompt cache key:** `fast`',
386 )
387 .replace(
388 '> * **Model:** `anthropic/claude-opus-5-5`',
389 '> * **Models:** `anthropic/claude-opus-5-5`, with `openai/gpt-6.1-sol` as the [fallback model](https://docs.perplexity.ai/docs/agent-api/model-fallback.md)',
390 )
391 .replace(
392 '\n## Next Steps',
393 [
394 '',
395 '> [accordion] ultra-preview — current effort level values',
396 '>',
397 '> Broad research and data-gathering tasks where coverage matters most.',
398 '>',
399 '> `ultra-preview` has no frozen configuration. Its settings are not all part of the documented request schema, so call it by name.',
400 '',
401 '## Next Steps',
402 ].join('\n'),
403 )
404​
405 // Served by 2026-11-08: `ultra` titles the accordion with a colon, and
406 // names the model it runs on in the no-frozen-configuration sentence.
407 const COLON_DOC = [
408 '## Current effort level values',
409 '',
410 '> [accordion] fast — current effort level values',
411 '>',
412 '> * **Models:** `openai/gpt-6-luna`, with `openai/gpt-5.6-luna` as the [fallback model](https://docs.perplexity.ai/docs/agent-api/model-fallback.md)',
413 '> * **Reasoning effort:** `none`',
414 '> * **Tools:** `web_search`',
415 '',
416 '> [accordion] ultra: current effort level values',
417 '>',
418 '> `ultra` has no frozen configuration. It runs on `anthropic/claude-opus-5-5`, and its settings are not all part of the documented request schema, so call it by name.',
419 '',
420 '## Next Steps',
421 ].join('\n')
422​
423 it('reads a colon-titled accordion and skips a level that names a model only in its no-frozen-configuration sentence', () => {
424 expect([...parsePerplexityEffortLevels(COLON_DOC)]).toEqual([
425 ['openai/gpt-6-luna', ['reasoning', 'reasoning_effort', 'tools']],
426 ])
427 })
428​
429 it("reads the first of a level's models, and skips a level with no frozen configuration", () => {
430 expect(FALLBACK_DOC.match(/\*\*Models:\*\*/g)).toHaveLength(2)
431 expect(FALLBACK_DOC).toContain('ultra-preview')
432 expect([...parsePerplexityEffortLevels(FALLBACK_DOC)]).toEqual([
433 ['openai/gpt-6-luna', ['reasoning', 'reasoning_effort', 'tools']],
434 ['anthropic/claude-opus-5-5', ['reasoning', 'reasoning_effort', 'tools']],
435 ])
436 })
437​
438 // Served since 2026-11-19: xhigh's Model bullet names one id and states
439 // there is no fallback. ultra still has no frozen configuration and names
440 // its runtime model only in that sentence. Trimmed to the bullets the
441 // parser reads, from https://docs.perplexity.ai/docs/agent-api/effort.md.
442 const NO_FALLBACK_DOC = [
443 '## Current effort level values',
444 '',
445 '> [accordion] fast — current effort level values',
446 '>',
447 '> * **Models:** `openai/gpt-6-luna`, with `openai/gpt-5.6-luna` as the [fallback model](https://docs.perplexity.ai/docs/agent-api/model-fallback.md)',
448 '> * **Reasoning effort:** `none`',
449 '> * **Tools:** `web_search`',
450 '',
451 '> [accordion] low — current effort level values',
452 '>',
453 '> * **Model:** `openai/gpt-6-luna`',
454 '> * **Reasoning effort:** `minimal`',
455 '> * **Tools:** `web_search`, `fetch_url` (`max_urls: 1`)',
456 '',
457 '> [accordion] medium — current effort level values',
458 '>',
459 '> * **Model:** `openai/gpt-6-luna`',
460 '> * **Reasoning effort:** `medium`',
461 '> * **Tools:** `web_search`, `fetch_url` (`max_urls: 1`)',
462 '',
463 '> [accordion] high — current effort level values',
464 '>',
465 '> * **Model:** `openai/gpt-6.1-terra`',
466 '> * **Reasoning effort:** `medium`',
467 '> * **Tools:** `web_search`, `fetch_url` (`max_urls: 1`)',
468 '',
469 '> [accordion] xhigh — current effort level values',
470 '>',
471 '> * **Model:** `openai/gpt-6.2-sol` (no fallback model)',
472 '> * **Reasoning effort:** `high`',
473 '> * **Tools:** `web_search`, `finance_search`, `sandbox`',
474 '',
475 '> [accordion] ultra: current effort level values',
476 '>',
477 '> `ultra` has no frozen configuration. It runs on `anthropic/claude-opus-5-5`, and its settings are not all part of the documented request schema, so call it by name.',
478 '',
479 '## Next Steps',
480 ].join('\n')
481​
482 it("reads a Model bullet that states there is no fallback, and skips ultra's runtime model named only in prose", () => {
483 expect(NO_FALLBACK_DOC).toContain('(no fallback model)')
484 expect([...parsePerplexityEffortLevels(NO_FALLBACK_DOC)]).toEqual([
485 ['openai/gpt-6-luna', ['reasoning', 'reasoning_effort', 'tools']],
486 ['openai/gpt-6.1-terra', ['reasoning', 'reasoning_effort', 'tools']],
487 ['openai/gpt-6.2-sol', ['reasoning', 'reasoning_effort', 'tools']],
488 ])
489 })
490​
491 it.each([
492 [
493 'a fallback clause in another shape',
494 'as the [fallback model]',
495 'as backup',
496 ],
497 [
498 'a model-less level that states a setting',
499 '> `ultra-preview` has no',
500 '> * **Max steps:** 300\n>\n> `ultra-preview` has no',
501 ],
502 [
503 'a model-less level that does not say it has no frozen configuration',
504 'has no frozen configuration.',
505 'is in preview.',
506 ],
507 [
508 "a model-less level quoting another level's frozen configuration",
509 '> `ultra-preview` has no',
510 '> `fast` has no',
511 ],
512 [
513 'both a Model and a Models bullet',
514 '> * **Prompt cache key:** `fast`',
515 '> * **Model:** `openai/gpt-6-luna`\n> * **Prompt cache key:** `fast`',
516 ],
517 ])('throws on %s', (_case, from, to) => {
518 const mutated = FALLBACK_DOC.replace(from, to)
519 expect(mutated).not.toBe(FALLBACK_DOC)
520 expect(() => parsePerplexityEffortLevels(mutated)).toThrow(
521 'perplexity: effort level names no model',
522 )
523 })
524​
525 it('gives a level with no tools or effort bullet neither flag', () => {
526 const bare = EFFORT_DOC.replace(
527 '> * **Reasoning effort:** `high`\n> * **Tools:** `web_search`, `finance_search`, `sandbox`\n',
528 '',
529 )
530 expect(
531 parsePerplexityEffortLevels(bare).has('anthropic/claude-opus-5-5'),
532 ).toBe(false)
533 })
534​
535 it.each([
536 [
537 'a level with no model bullet',
538 '* **Model:** `openai',
539 '* **LLM:** `openai',
540 ],
541 ['a model that is prose', '`anthropic/claude-opus-5-5`', 'Claude Opus 5.5'],
542 [
543 'text after a Model id other than (no fallback model)',
544 '`anthropic/claude-opus-5-5`',
545 '`anthropic/claude-opus-5-5` (preview)',
546 ],
547 ['an effort that is prose', '`high`', 'high, or lower on retries'],
548 [
549 'tools that are prose',
550 '`web_search`, `finance_search`, `sandbox`',
551 'none',
552 ],
553 [
554 'a bullet stated twice',
555 '> * **Max steps:** 100',
556 '> * **Model:** `openai/gpt-6-sol`',
557 ],
558 [
559 'a page with no effort level accordions',
560 / — current effort level values/g,
561 '',
562 ],
563 [
564 'the accordion title the presets page used before 2026-10-22',
565 / — current effort level values/g,
566 ' — current preset values',
567 ],
568 [
569 'an accordion split by a blank line',
570 '> * **Reasoning effort:** `high`\n',
571 '> * **Reasoning effort:** `high`\n\n',
572 ],
573 [
574 'an accordion title in another shape',
575 '> [accordion] xhigh — current effort level values',
576 '> [accordion] xhigh — current effort level values (beta)',
577 ],
578 ])('throws on %s', (_case, from, to) => {
579 const mutated = EFFORT_DOC.replace(from, to)
580 expect(mutated).not.toBe(EFFORT_DOC)
581 expect(() => parsePerplexityEffortLevels(mutated)).toThrow(
582 'perplexity: effort',
583 )
584 })
585})
586​
587const originalFetch = globalThis.fetch
588​
589afterEach(() => {
590 globalThis.fetch = originalFetch
591})
592​
593describe('perplexity provider', () => {
594 it('exports seed metadata for the isolation loader', () => {
595 expect(provider.id).toBe('perplexity')
596 expect(provider.displayName).toBe('Perplexity')
597 expect(provider.authEnvVar).toBe('PERPLEXITY_API_KEY')
598 expect(provider.defaultDerivation).toBe('upstream-spec')
599 expect(provider.specSourceUrl).toBe(
600 'https://docs.perplexity.ai/openapi.json',
601 )
602 expect(provider.modelsEndpoint).toBe('https://api.perplexity.ai/v1/models')
603 })
604​
605 it('names the maker the id is namespaced under, and none for hosted ids', () => {
606 expect(
607 provider.upstreamModelIdentity?.('xai/grok-4.20-non-reasoning'),
608 ).toMatchObject({
609 providerNamespace: 'xai',
610 rawId: 'grok-4.20-non-reasoning',
611 source: { derivation: 'listing', path: 'data[].id' },
612 })
613 expect(provider.upstreamModelIdentity?.('perplexity/kimi-k3')).toBeNull()
614 expect(provider.upstreamModelIdentity?.('sonar')).toBeNull()
615 })
616})
617​
618describe('perplexity classify', () => {
619 it('maps generation and search paths and drops async and platform', () => {
620 expect(provider.classify('/v1/sonar', {})).toBe('chat')
621 expect(provider.classify('/v1/agent', {})).toBe('chat')
622 expect(provider.classify('/v1/embeddings', {})).toBe('embeddings')
623 expect(provider.classify('/v1/contextualizedembeddings', {})).toBe(
624 'embeddings',
625 )
626 expect(provider.classify('/search', {})).toBe('search')
627 expect(provider.classify('/v1/async/sonar', {})).toBeNull()
628 expect(provider.classify('/v1/models', {})).toBeNull()
629 expect(provider.classify('/v1/agent/{id}/cancel', {})).toBeNull()
630 expect(provider.classify('/v1/analytics/computer/usage', {})).toBeNull()
631 })
632})
633​
634describe('perplexity listModels', () => {
635 it('skips when the secret is absent', async () => {
636 const result = await provider.listModels({})
637 expect(result.skipped).toBe(
638 'perplexity: PERPLEXITY_API_KEY not set — skipped',
639 )
640 expect(result.models).toEqual([])
641 })
642​
643 it('joins the listing to the flags both docs pages state', async () => {
644 const urls: Array<string> = []
645 globalThis.fetch = ((url: string, init?: RequestInit) => {
646 urls.push(String(url))
647 expect(init?.signal).toBeInstanceOf(AbortSignal)
648 if (String(url) === DOC_URL) {
649 return Promise.resolve(new Response(MODELS_DOC))
650 }
651 if (String(url) === EFFORT_URL) {
652 return Promise.resolve(new Response(EFFORT_DOC))
653 }
654 expect(
655 new Headers(init?.headers).get('Authorization')?.startsWith('Bearer '),
656 ).toBe(true)
657 return Promise.resolve(
658 Response.json({
659 object: 'list',
660 data: [
661 { id: 'perplexity/kimi-k3', created: 1 },
662 { id: 'perplexity/sonar', created: 2 },
663 { id: 'openai/gpt-6-luna', created: 3 },
664 { id: 'xai/grok-4.20-non-reasoning', created: 4 },
665 ],
666 }),
667 )
668 }) as typeof fetch
669​
670 const result = await provider.listModels({
671 PERPLEXITY_API_KEY: 'test-key',
672 })
673 expect(urls.sort()).toEqual([MODELS_URL, EFFORT_URL, DOC_URL])
674 expect(result.skipped).toBeUndefined()
675 const source = (sourceUrl: string, path: string) => ({
676 derivation: 'docs-derived',
677 sourceUrl,
678 sourceHash: expect.stringMatching(/^[0-9a-f]{64}$/) as string,
679 path,
680 })
681 expect(result.models).toEqual([
682 {
683 rawId: 'perplexity/kimi-k3',
684 releasedAt: 1,
685 activity: 'chat',
686 capabilities: ['reasoning', 'reasoning_effort'],
687 // The page publishes the levels and is silent on turning it off.
688 reasoning: {
689 mode: 'effort',
690 mandatory: null,
691 efforts: ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'],
692 },
693 factSources: {
694 reasoning: source(DOC_URL, 'reasoning_effort'),
695 capabilities: {
696 reasoning: source(DOC_URL, 'reasoning'),
697 reasoning_effort: source(DOC_URL, 'reasoning_effort'),
698 },
699 },
700 },
701 { rawId: 'perplexity/sonar', releasedAt: 2, activity: 'chat' },
702 {
703 rawId: 'openai/gpt-6-luna',
704 releasedAt: 3,
705 activity: 'chat',
706 capabilities: ['reasoning', 'reasoning_effort', 'tools'],
707 factSources: {
708 capabilities: {
709 reasoning: source(EFFORT_URL, 'reasoning'),
710 reasoning_effort: source(EFFORT_URL, 'reasoning_effort'),
711 tools: source(EFFORT_URL, 'tools'),
712 },
713 },
714 },
715 { rawId: 'xai/grok-4.20-non-reasoning', releasedAt: 4, activity: 'chat' },
716 ])
717 // Only the row whose effort list the models page states gets `reasoning`.
718 expect(result.models.filter((model) => model.reasoning != null)).toEqual([
719 expect.objectContaining({ rawId: 'perplexity/kimi-k3' }),
720 ])
721 expect(
722 provider.generationEndpointId?.({
723 rawId: 'perplexity/sonar',
724 activity: 'chat',
725 }),
726 ).toBe('v1/agent')
727 })
728​
729 it('puts a card sentence’s limits on its own row only', async () => {
730 const nemotron = 'perplexity/nemotron-3.5-super-120b-a12b'
731 const nvidia = MODELS_DOC.replace(
732 /^> > Nemotron 3 Ultra[^]*?(?=> \[tab\] Perplexity)/m,
733 [
734 ...quote([
735 '> Nemotron 3.5 Super is a reasoning model with a 1,048,576-token context window and up to 131,072 output tokens. It accepts text input only.',
736 '',
737 ...HEADER,
738 `| \`${nemotron}\` | 0.20 | 0.50 | 0.04 | — | — |`,
739 ]),
740 '',
741 '',
742 ].join('\n'),
743 )
744 globalThis.fetch = ((url: string) =>
745 Promise.resolve(
746 String(url) === MODELS_URL
747 ? Response.json({
748 data: [{ id: nemotron }, { id: 'perplexity/sonar' }],
749 })
750 : new Response(String(url) === DOC_URL ? nvidia : EFFORT_DOC),
751 )) as typeof fetch
752 const { models } = await provider.listModels({
753 PERPLEXITY_API_KEY: 'test-key',
754 })
755 const row = models.find((m) => m.rawId === nemotron)
756 expect(row).toMatchObject({
757 contextWindow: 1_048_576,
758 maxOutput: 131_072,
759 factSources: {
760 contextWindow: { derivation: 'docs-derived', sourceUrl: DOC_URL },
761 maxOutput: { derivation: 'docs-derived', sourceUrl: DOC_URL },
762 },
763 })
764 expect(row?.factSources?.contextWindow?.sourceHash).toMatch(
765 /^[0-9a-f]{64}$/,
766 )
767 const sonar = models.find((m) => m.rawId === 'perplexity/sonar')
768 expect(sonar?.contextWindow).toBeUndefined()
769 expect(sonar?.factSources?.contextWindow).toBeUndefined()
770 })
771​
772 it('reads an off value in the published list as "can be turned off"', async () => {
773 const withNone = MODELS_DOC.replace('accepts `minimal`,', 'accepts `none`,')
774 expect(withNone).not.toBe(MODELS_DOC)
775 globalThis.fetch = ((url: string) =>
776 Promise.resolve(
777 String(url) === MODELS_URL
778 ? Response.json({ data: [{ id: 'perplexity/kimi-k3' }] })
779 : new Response(String(url) === DOC_URL ? withNone : EFFORT_DOC),
780 )) as typeof fetch
781 const result = await provider.listModels({ PERPLEXITY_API_KEY: 'test-key' })
782 expect(result.models[0]?.reasoning).toEqual({
783 mode: 'effort',
784 mandatory: false,
785 efforts: ['none', 'low', 'medium', 'high', 'xhigh', 'max'],
786 })
787 })
788​
789 it('still lists, and reports the page, when a docs page is an HTML error page', async () => {
790 globalThis.fetch = ((url: string) =>
791 Promise.resolve(
792 String(url) === MODELS_URL
793 ? Response.json({ data: [{ id: 'perplexity/sonar' }] })
794 : String(url) === DOC_URL
795 ? new Response(MODELS_DOC)
796 : new Response('<html>Not found</html>'),
797 )) as typeof fetch
798 // One page down withholds both pages' flags: half of them would read
799 // as the other half dropped.
800 expect(
801 await provider.listModels({ PERPLEXITY_API_KEY: 'test-key' }),
802 ).toEqual({
803 models: [
804 {
805 rawId: 'perplexity/sonar',
806 releasedAt: null,
807 activity: 'chat',
808 absent: {
809 capabilities: 'unavailable',
810 reasoning: 'unavailable',
811 contextWindow: 'unavailable',
812 maxOutput: 'unavailable',
813 },
814 },
815 ],
816 docsFailures: {
817 failed: 1,
818 skipped: 0,
819 first: [
820 {
821 source: EFFORT_URL,
822 error: 'perplexity: effort page lists no effort levels',
823 elapsedMs: expect.any(Number) as number,
824 },
825 ],
826 },
827 })
828 })
829​
830 it('fails the poll when the listing fails', async () => {
831 globalThis.fetch = ((url: string) =>
832 Promise.resolve(
833 String(url) === MODELS_URL
834 ? new Response('down', { status: 503 })
835 : new Response(String(url) === DOC_URL ? MODELS_DOC : EFFORT_DOC),
836 )) as typeof fetch
837 await expect(
838 provider.listModels({ PERPLEXITY_API_KEY: 'test-key' }),
839 ).rejects.toThrow('503')
840 })
841})
842​
843describe('perplexity fetchSpec', () => {
844 it('loads the published OpenAPI document without a key', async () => {
845 const spec = {
846 openapi: '3.1.0',
847 info: { title: 'Perplexity AI API' },
848 paths: { '/v1/sonar': { post: { summary: 'Create Chat Completion' } } },
849 }
850 globalThis.fetch = ((url: string) => {
851 expect(String(url)).toBe('https://docs.perplexity.ai/openapi.json')
852 return Promise.resolve(new Response(JSON.stringify(spec)))
853 }) as typeof fetch
854​
855 const fetched = await provider.fetchSpec({})
856 expect(fetched.specs).toHaveLength(1)
857 expect(fetched.specs[0]?.info?.title).toBe('Perplexity AI API')
858 expect(fetched.sources[0]?.url).toBe(
859 'https://docs.perplexity.ai/openapi.json',
860 )
861 expect(fetched.sources[0]?.hash).toMatch(/^[0-9a-f]{64}$/)
862 expect(fetched.outputStrategy).toBe('post-200')
863 })
864})
865​
866describe('perplexity Search API', () => {
867 // The upstream shape: the request is an allOf over shared filter schemas.
868 const ref = (name: string) => ({ $ref: `#/components/schemas/${name}` })
869 const json = (schema: object) => ({
870 content: { 'application/json': { schema } },
871 })
872 const spec = {
873 openapi: '3.1.0',
874 paths: {
875 '/search': {
876 post: {
877 requestBody: json(ref('ApiSearchRequest')),
878 responses: { '200': json(ref('ApiSearchResponse')) },
879 },
880 },
881 },
882 components: {
883 schemas: {
884 ApiSearchRequest: {
885 type: 'object',
886 allOf: [
887 {
888 type: 'object',
889 required: ['query'],
890 properties: {
891 query: {
892 anyOf: [
893 { type: 'string' },
894 { type: 'array', items: { type: 'string' } },
895 ],
896 },
897 max_results: { type: 'integer' },
898 },
899 },
900 ref('SearchDomainFilter'),
901 ],
902 },
903 SearchDomainFilter: {
904 type: 'object',
905 properties: {
906 search_domain_filter: { type: 'array', items: { type: 'string' } },
907 },
908 },
909 ApiSearchResponse: {
910 type: 'object',
911 required: ['results', 'id'],
912 properties: {
913 id: { type: 'string' },
914 results: { type: 'array', items: ref('ApiSearchPage') },
915 },
916 },
917 ApiSearchPage: {
918 type: 'object',
919 required: ['title', 'url', 'snippet'],
920 properties: {
921 title: { type: 'string' },
922 url: { type: 'string' },
923 snippet: { type: 'string' },
924 },
925 },
926 },
927 },
928 }
929​
930 it('bundles POST /search with its request and response', () => {
931 const { endpoints } = classifyAndBundle(provider, {
932 specs: [spec],
933 sources: [{ url: 'https://docs.perplexity.ai/openapi.json', hash: 'ab' }],
934 outputStrategy: 'post-200',
935 })
936 expect(endpoints).toHaveLength(1)
937 const [endpoint] = endpoints
938 expect(endpoint).toMatchObject({
939 path: '/search',
940 method: 'POST',
941 activity: 'search',
942 })
943 const text = JSON.stringify([endpoint?.input, endpoint?.output])
944 for (const name of [
945 'query',
946 'search_domain_filter',
947 'results',
948 'snippet',
949 ]) {
950 expect(text).toContain(`"${name}"`)
951 }
952 // Every $ref resolves inside the bundled schema.
953 expect(text).not.toContain('#/components/')
954 })
955})