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

perplexity.test.ts

870 lines29.1 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('leaves the effort flag off when no tab states an effort', () => {
149 const silent = MODELS_DOC.replace(
150 /^>\n> > \[!NOTE\]\n> >\n> > Kimi K3[^\n]*\n/m,
151 '',
152 )
153 const page = parsePerplexityModelsPage(silent)
154 expect(page.flags.get('perplexity/kimi-k3')).toEqual(['reasoning'])
155 expect(page.efforts.size).toBe(0)
156 })
157​
158 it.each([
159 ['a reworded sentence', 'Kimi K3 accepts', 'Kimi K3 supports'],
160 [
161 'a list with prose in it',
162 '`xhigh`, and `max`',
163 '`xhigh`, and up to `max`',
164 ],
165 ['a name no row carries', 'Kimi K3 accepts', 'Kimi K4 accepts'],
166 [
167 'a second, unread mention',
168 'output-token rate.',
169 'output-token rate.\n> >\n> > GLM takes any reasoning effort.',
170 ],
171 [
172 'a second sentence for the same model',
173 'output-token rate.',
174 'output-token rate.\n> >\n> > Kimi K3 accepts `low` and `high` reasoning effort.',
175 ],
176 [
177 'the sentence moved outside the tabs',
178 /^>\n> > \[!NOTE\]\n> >\n> > Kimi K3 accepts[^\n]*\n([^]*?## Service tiers\n)/m,
179 `$1\n${KIMI_SENTENCE}\n`,
180 ],
181 [
182 'a statement that reasoning cannot be disabled',
183 'reasoning effort. `minimal`',
184 'reasoning effort. Reasoning cannot be disabled. `minimal`',
185 ],
186 [
187 'a statement that the model always thinks',
188 "Kimi K3 — Moonshot AI's flagship reasoning model.",
189 "Kimi K3 — Moonshot AI's flagship always-on reasoning model.",
190 ],
191 [
192 'a card naming fewer models than its tab lists',
193 'GLM 5.3 and GLM 5.3 Flash — Z.AI',
194 'GLM 5.3 — Z.AI',
195 ],
196 [
197 'a card that denies it',
198 'is an open-weight reasoning model',
199 'is not a reasoning model',
200 ],
201 [
202 'a reworded card',
203 'is an open-weight reasoning model.',
204 'ranks among open reasoning models, in our tests.',
205 ],
206 [
207 'a card with a second sentence on reasoning models',
208 'is an open-weight reasoning model.',
209 'is an open-weight reasoning model. It replaces our older reasoning models.',
210 ],
211 [
212 'a second card sentence on thinking',
213 'is an open-weight reasoning model.',
214 'is an open-weight reasoning model. You cannot turn its thinking off.',
215 ],
216 [
217 'a "with" clause on reasoning',
218 'is an open-weight reasoning model.',
219 'is an open-weight reasoning model with reasoning off by default.',
220 ],
221 [
222 'a "with" clause on whether thinking can be skipped',
223 'is an open-weight reasoning model.',
224 'is an open-weight reasoning model with a mandatory chain-of-thought.',
225 ],
226 [
227 'a "with" clause in another shape',
228 'is an open-weight reasoning model.',
229 'is an open-weight reasoning model with a chain-of-thought you cannot skip.',
230 ],
231 [
232 'a card titled for another tab',
233 '> > [card] NVIDIA',
234 '> > [card] Nemotron',
235 ],
236 [
237 'a card with no spacer line',
238 '> > [card] Z.AI\n> >\n',
239 '> > [card] Z.AI\n',
240 ],
241 ['a tab title in another shape', '> [tab] Z.AI\n', '> [tabs] Z.AI\n'],
242 ['a tab with no spacer line', '> [tab] Z.AI\n>\n', '> [tab] Z.AI\n'],
243 [
244 'a card split by a blank line',
245 '> > Nemotron 3 Ultra is',
246 '> > NVIDIA Nemotron.\n>\n> > Nemotron 3 Ultra is',
247 ],
248 ['a card and table outside any tab', '> [tab] xAI\n>\n', ''],
249 [
250 'a callout split from its tab by a blank line',
251 '\n\n> [tab] NVIDIA',
252 '\n\n> > [!NOTE]\n> >\n> > Reasoning cannot be disabled on GLM 5.3.\n\n> [tab] NVIDIA',
253 ],
254 [
255 'prose between tabs',
256 '\n\n> [tab] NVIDIA',
257 '\n\nThinking is always on for Z.AI models.\n\n> [tab] NVIDIA',
258 ],
259 [
260 'a bold tab title and card, as the export wrote them before 2026-10-30',
261 '> [tab] Z.AI\n>\n> > [card] Z.AI',
262 '**Z.AI**\n\n> **Z.AI**',
263 ],
264 [
265 'a card that goes on with a clause other than "with"',
266 'is an open-weight reasoning model.',
267 'is an open-weight reasoning model for agents.',
268 ],
269 ])('throws on %s', (_case, from, to) => {
270 const mutated = MODELS_DOC.replace(from, to)
271 expect(mutated).not.toBe(MODELS_DOC)
272 expect(() => parsePerplexityModelsPage(mutated)).toThrow('unread shape')
273 })
274​
275 it('reads only the Available Models section', () => {
276 const later = [
277 MODELS_DOC,
278 '',
279 '> [tab] Extra',
280 ...quote([
281 '',
282 '> [card] Extra',
283 '>',
284 '> Extra is a reasoning model.',
285 '',
286 ...HEADER,
287 '| `perplexity/extra` | 1 | 1 | 1 | — | — |',
288 ]),
289 ].join('\n')
290 expect(parsePerplexityModelsPage(later).flags.has('perplexity/extra')).toBe(
291 false,
292 )
293 })
294​
295 it('throws on a page with no model table, such as an HTML error page', () => {
296 expect(() => parsePerplexityModelsPage('<html>Not found</html>')).toThrow(
297 'lists no models',
298 )
299 })
300})
301​
302// Three of the five effort levels as served on 2026-10-22, when the
303// presets page became the effort page, in the markdown export's shape since
304// 2026-10-30: each accordion is one `> [accordion] title` blockquote.
305// Bullets are trimmed, and only `fast` keeps its prompt block, cut to one
306// `## ` heading; the real blocks also hold SDK code samples.
307const EFFORT_DOC = [
308 '## Current effort level values',
309 '',
310 '> [accordion] fast — current effort level values',
311 '>',
312 '> Quick factual lookups with minimal latency and inline citations for search-backed claims.',
313 '>',
314 '> * **Model:** `openai/gpt-6-luna`',
315 '> * **Prompt cache key:** `fast`',
316 '> * **Max steps:** 1',
317 '> * **Reasoning effort:** `none`',
318 '> * **Service tier:** `priority`',
319 '> * **Max output tokens:** 8192',
320 '> * **Tools:** `web_search`',
321 '> * **System prompt:** included inline below',
322 '>',
323 '> ```text',
324 '> ## Role',
325 '> ```',
326 '',
327 '> [accordion] low — current effort level values',
328 '>',
329 '> * **Model:** `openai/gpt-6-luna`',
330 '> * **Reasoning effort:** `minimal`',
331 '> * **Tools:** `web_search`, `fetch_url` (`max_urls: 1`)',
332 '',
333 '> [accordion] xhigh — current effort level values',
334 '>',
335 '> * **Model:** `anthropic/claude-opus-5-5`',
336 '> * **Max steps:** 100',
337 '> * **Reasoning effort:** `high`',
338 '> * **Tools:** `web_search`, `finance_search`, `sandbox`',
339 '',
340 '## Next Steps',
341 '',
342 '> **[Agent API Models](/docs/agent-api/models)**',
343].join('\n')
344​
345describe('parsePerplexityEffortLevels', () => {
346 it('reads each effort level model with the effort and tools it runs with', () => {
347 expect([...parsePerplexityEffortLevels(EFFORT_DOC)]).toEqual([
348 ['openai/gpt-6-luna', ['reasoning', 'reasoning_effort', 'tools']],
349 ['anthropic/claude-opus-5-5', ['reasoning', 'reasoning_effort', 'tools']],
350 ])
351 })
352​
353 // The change served on 2026-10-29, trimmed like EFFORT_DOC: `fast` and
354 // `xhigh` name a fallback model, and `ultra-preview` names no model (its
355 // code samples are cut).
356 const FALLBACK_DOC = EFFORT_DOC.replace(
357 '> * **Model:** `openai/gpt-6-luna`\n> * **Prompt cache key:** `fast`',
358 '> * **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`',
359 )
360 .replace(
361 '> * **Model:** `anthropic/claude-opus-5-5`',
362 '> * **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)',
363 )
364 .replace(
365 '\n## Next Steps',
366 [
367 '',
368 '> [accordion] ultra-preview — current effort level values',
369 '>',
370 '> Broad research and data-gathering tasks where coverage matters most.',
371 '>',
372 '> `ultra-preview` has no frozen configuration. Its settings are not all part of the documented request schema, so call it by name.',
373 '',
374 '## Next Steps',
375 ].join('\n'),
376 )
377​
378 // Served by 2026-11-08: `ultra` titles the accordion with a colon, and
379 // names the model it runs on in the no-frozen-configuration sentence.
380 const COLON_DOC = [
381 '## Current effort level values',
382 '',
383 '> [accordion] fast — current effort level values',
384 '>',
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)',
386 '> * **Reasoning effort:** `none`',
387 '> * **Tools:** `web_search`',
388 '',
389 '> [accordion] ultra: current effort level values',
390 '>',
391 '> `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.',
392 '',
393 '## Next Steps',
394 ].join('\n')
395​
396 it('reads a colon-titled accordion and skips a level that names a model only in its no-frozen-configuration sentence', () => {
397 expect([...parsePerplexityEffortLevels(COLON_DOC)]).toEqual([
398 ['openai/gpt-6-luna', ['reasoning', 'reasoning_effort', 'tools']],
399 ])
400 })
401​
402 it("reads the first of a level's models, and skips a level with no frozen configuration", () => {
403 expect(FALLBACK_DOC.match(/\*\*Models:\*\*/g)).toHaveLength(2)
404 expect(FALLBACK_DOC).toContain('ultra-preview')
405 expect([...parsePerplexityEffortLevels(FALLBACK_DOC)]).toEqual([
406 ['openai/gpt-6-luna', ['reasoning', 'reasoning_effort', 'tools']],
407 ['anthropic/claude-opus-5-5', ['reasoning', 'reasoning_effort', 'tools']],
408 ])
409 })
410​
411 it.each([
412 [
413 'a fallback clause in another shape',
414 'as the [fallback model]',
415 'as backup',
416 ],
417 [
418 'a model-less level that states a setting',
419 '> `ultra-preview` has no',
420 '> * **Max steps:** 300\n>\n> `ultra-preview` has no',
421 ],
422 [
423 'a model-less level that does not say it has no frozen configuration',
424 'has no frozen configuration.',
425 'is in preview.',
426 ],
427 [
428 "a model-less level quoting another level's frozen configuration",
429 '> `ultra-preview` has no',
430 '> `fast` has no',
431 ],
432 [
433 'both a Model and a Models bullet',
434 '> * **Prompt cache key:** `fast`',
435 '> * **Model:** `openai/gpt-6-luna`\n> * **Prompt cache key:** `fast`',
436 ],
437 ])('throws on %s', (_case, from, to) => {
438 const mutated = FALLBACK_DOC.replace(from, to)
439 expect(mutated).not.toBe(FALLBACK_DOC)
440 expect(() => parsePerplexityEffortLevels(mutated)).toThrow(
441 'perplexity: effort level names no model',
442 )
443 })
444​
445 it('gives a level with no tools or effort bullet neither flag', () => {
446 const bare = EFFORT_DOC.replace(
447 '> * **Reasoning effort:** `high`\n> * **Tools:** `web_search`, `finance_search`, `sandbox`\n',
448 '',
449 )
450 expect(
451 parsePerplexityEffortLevels(bare).has('anthropic/claude-opus-5-5'),
452 ).toBe(false)
453 })
454​
455 it.each([
456 [
457 'a level with no model bullet',
458 '* **Model:** `openai',
459 '* **LLM:** `openai',
460 ],
461 ['a model that is prose', '`anthropic/claude-opus-5-5`', 'Claude Opus 5.5'],
462 ['an effort that is prose', '`high`', 'high, or lower on retries'],
463 [
464 'tools that are prose',
465 '`web_search`, `finance_search`, `sandbox`',
466 'none',
467 ],
468 [
469 'a bullet stated twice',
470 '> * **Max steps:** 100',
471 '> * **Model:** `openai/gpt-6-sol`',
472 ],
473 [
474 'a page with no effort level accordions',
475 / — current effort level values/g,
476 '',
477 ],
478 [
479 'the accordion title the presets page used before 2026-10-22',
480 / — current effort level values/g,
481 ' — current preset values',
482 ],
483 [
484 'an accordion split by a blank line',
485 '> * **Reasoning effort:** `high`\n',
486 '> * **Reasoning effort:** `high`\n\n',
487 ],
488 [
489 'an accordion title in another shape',
490 '> [accordion] xhigh — current effort level values',
491 '> [accordion] xhigh — current effort level values (beta)',
492 ],
493 ])('throws on %s', (_case, from, to) => {
494 const mutated = EFFORT_DOC.replace(from, to)
495 expect(mutated).not.toBe(EFFORT_DOC)
496 expect(() => parsePerplexityEffortLevels(mutated)).toThrow(
497 'perplexity: effort',
498 )
499 })
500})
501​
502const originalFetch = globalThis.fetch
503​
504afterEach(() => {
505 globalThis.fetch = originalFetch
506})
507​
508describe('perplexity provider', () => {
509 it('exports seed metadata for the isolation loader', () => {
510 expect(provider.id).toBe('perplexity')
511 expect(provider.displayName).toBe('Perplexity')
512 expect(provider.authEnvVar).toBe('PERPLEXITY_API_KEY')
513 expect(provider.defaultDerivation).toBe('upstream-spec')
514 expect(provider.specSourceUrl).toBe(
515 'https://docs.perplexity.ai/openapi.json',
516 )
517 expect(provider.modelsEndpoint).toBe('https://api.perplexity.ai/v1/models')
518 })
519​
520 it('names the maker the id is namespaced under, and none for hosted ids', () => {
521 expect(
522 provider.upstreamModelIdentity?.('xai/grok-4.20-non-reasoning'),
523 ).toMatchObject({
524 providerNamespace: 'xai',
525 rawId: 'grok-4.20-non-reasoning',
526 source: { derivation: 'listing', path: 'data[].id' },
527 })
528 expect(provider.upstreamModelIdentity?.('perplexity/kimi-k3')).toBeNull()
529 expect(provider.upstreamModelIdentity?.('sonar')).toBeNull()
530 })
531})
532​
533describe('perplexity classify', () => {
534 it('maps generation and search paths and drops async and platform', () => {
535 expect(provider.classify('/v1/sonar', {})).toBe('chat')
536 expect(provider.classify('/v1/agent', {})).toBe('chat')
537 expect(provider.classify('/v1/embeddings', {})).toBe('embeddings')
538 expect(provider.classify('/v1/contextualizedembeddings', {})).toBe(
539 'embeddings',
540 )
541 expect(provider.classify('/search', {})).toBe('search')
542 expect(provider.classify('/v1/async/sonar', {})).toBeNull()
543 expect(provider.classify('/v1/models', {})).toBeNull()
544 expect(provider.classify('/v1/agent/{id}/cancel', {})).toBeNull()
545 expect(provider.classify('/v1/analytics/computer/usage', {})).toBeNull()
546 })
547})
548​
549describe('perplexity listModels', () => {
550 it('skips when the secret is absent', async () => {
551 const result = await provider.listModels({})
552 expect(result.skipped).toBe(
553 'perplexity: PERPLEXITY_API_KEY not set — skipped',
554 )
555 expect(result.models).toEqual([])
556 })
557​
558 it('joins the listing to the flags both docs pages state', async () => {
559 const urls: Array<string> = []
560 globalThis.fetch = ((url: string, init?: RequestInit) => {
561 urls.push(String(url))
562 expect(init?.signal).toBeInstanceOf(AbortSignal)
563 if (String(url) === DOC_URL) {
564 return Promise.resolve(new Response(MODELS_DOC))
565 }
566 if (String(url) === EFFORT_URL) {
567 return Promise.resolve(new Response(EFFORT_DOC))
568 }
569 expect(
570 new Headers(init?.headers).get('Authorization')?.startsWith('Bearer '),
571 ).toBe(true)
572 return Promise.resolve(
573 Response.json({
574 object: 'list',
575 data: [
576 { id: 'perplexity/kimi-k3', created: 1 },
577 { id: 'perplexity/sonar', created: 2 },
578 { id: 'openai/gpt-6-luna', created: 3 },
579 { id: 'xai/grok-4.20-non-reasoning', created: 4 },
580 ],
581 }),
582 )
583 }) as typeof fetch
584​
585 const result = await provider.listModels({
586 PERPLEXITY_API_KEY: 'test-key',
587 })
588 expect(urls.sort()).toEqual([MODELS_URL, EFFORT_URL, DOC_URL])
589 expect(result.skipped).toBeUndefined()
590 const source = (sourceUrl: string, path: string) => ({
591 derivation: 'docs-derived',
592 sourceUrl,
593 sourceHash: expect.stringMatching(/^[0-9a-f]{64}$/) as string,
594 path,
595 })
596 expect(result.models).toEqual([
597 {
598 rawId: 'perplexity/kimi-k3',
599 releasedAt: 1,
600 activity: 'chat',
601 capabilities: ['reasoning', 'reasoning_effort'],
602 // The page publishes the levels and is silent on turning it off.
603 reasoning: {
604 mode: 'effort',
605 mandatory: null,
606 efforts: ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'],
607 },
608 factSources: {
609 reasoning: source(DOC_URL, 'reasoning_effort'),
610 capabilities: {
611 reasoning: source(DOC_URL, 'reasoning'),
612 reasoning_effort: source(DOC_URL, 'reasoning_effort'),
613 },
614 },
615 },
616 { rawId: 'perplexity/sonar', releasedAt: 2, activity: 'chat' },
617 {
618 rawId: 'openai/gpt-6-luna',
619 releasedAt: 3,
620 activity: 'chat',
621 capabilities: ['reasoning', 'reasoning_effort', 'tools'],
622 factSources: {
623 capabilities: {
624 reasoning: source(EFFORT_URL, 'reasoning'),
625 reasoning_effort: source(EFFORT_URL, 'reasoning_effort'),
626 tools: source(EFFORT_URL, 'tools'),
627 },
628 },
629 },
630 { rawId: 'xai/grok-4.20-non-reasoning', releasedAt: 4, activity: 'chat' },
631 ])
632 // Only the row whose effort list the models page states gets `reasoning`.
633 expect(result.models.filter((model) => model.reasoning != null)).toEqual([
634 expect.objectContaining({ rawId: 'perplexity/kimi-k3' }),
635 ])
636 expect(
637 provider.generationEndpointId?.({
638 rawId: 'perplexity/sonar',
639 activity: 'chat',
640 }),
641 ).toBe('v1/agent')
642 })
643​
644 it('puts a card sentence’s limits on its own row only', async () => {
645 const nemotron = 'perplexity/nemotron-3.5-super-120b-a12b'
646 const nvidia = MODELS_DOC.replace(
647 /^> > Nemotron 3 Ultra[^]*?(?=> \[tab\] Perplexity)/m,
648 [
649 ...quote([
650 '> 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.',
651 '',
652 ...HEADER,
653 `| \`${nemotron}\` | 0.20 | 0.50 | 0.04 | — | — |`,
654 ]),
655 '',
656 '',
657 ].join('\n'),
658 )
659 globalThis.fetch = ((url: string) =>
660 Promise.resolve(
661 String(url) === MODELS_URL
662 ? Response.json({
663 data: [{ id: nemotron }, { id: 'perplexity/sonar' }],
664 })
665 : new Response(String(url) === DOC_URL ? nvidia : EFFORT_DOC),
666 )) as typeof fetch
667 const { models } = await provider.listModels({
668 PERPLEXITY_API_KEY: 'test-key',
669 })
670 const row = models.find((m) => m.rawId === nemotron)
671 expect(row).toMatchObject({
672 contextWindow: 1_048_576,
673 maxOutput: 131_072,
674 factSources: {
675 contextWindow: { derivation: 'docs-derived', sourceUrl: DOC_URL },
676 maxOutput: { derivation: 'docs-derived', sourceUrl: DOC_URL },
677 },
678 })
679 expect(row?.factSources?.contextWindow?.sourceHash).toMatch(
680 /^[0-9a-f]{64}$/,
681 )
682 const sonar = models.find((m) => m.rawId === 'perplexity/sonar')
683 expect(sonar?.contextWindow).toBeUndefined()
684 expect(sonar?.factSources?.contextWindow).toBeUndefined()
685 })
686​
687 it('reads an off value in the published list as "can be turned off"', async () => {
688 const withNone = MODELS_DOC.replace('accepts `minimal`,', 'accepts `none`,')
689 expect(withNone).not.toBe(MODELS_DOC)
690 globalThis.fetch = ((url: string) =>
691 Promise.resolve(
692 String(url) === MODELS_URL
693 ? Response.json({ data: [{ id: 'perplexity/kimi-k3' }] })
694 : new Response(String(url) === DOC_URL ? withNone : EFFORT_DOC),
695 )) as typeof fetch
696 const result = await provider.listModels({ PERPLEXITY_API_KEY: 'test-key' })
697 expect(result.models[0]?.reasoning).toEqual({
698 mode: 'effort',
699 mandatory: false,
700 efforts: ['none', 'low', 'medium', 'high', 'xhigh', 'max'],
701 })
702 })
703​
704 it('still lists, and reports the page, when a docs page is an HTML error page', async () => {
705 globalThis.fetch = ((url: string) =>
706 Promise.resolve(
707 String(url) === MODELS_URL
708 ? Response.json({ data: [{ id: 'perplexity/sonar' }] })
709 : String(url) === DOC_URL
710 ? new Response(MODELS_DOC)
711 : new Response('<html>Not found</html>'),
712 )) as typeof fetch
713 // One page down withholds both pages' flags: half of them would read
714 // as the other half dropped.
715 expect(
716 await provider.listModels({ PERPLEXITY_API_KEY: 'test-key' }),
717 ).toEqual({
718 models: [
719 {
720 rawId: 'perplexity/sonar',
721 releasedAt: null,
722 activity: 'chat',
723 absent: {
724 capabilities: 'unavailable',
725 reasoning: 'unavailable',
726 contextWindow: 'unavailable',
727 maxOutput: 'unavailable',
728 },
729 },
730 ],
731 docsFailures: {
732 failed: 1,
733 skipped: 0,
734 first: [
735 {
736 source: EFFORT_URL,
737 error: 'perplexity: effort page lists no effort levels',
738 elapsedMs: expect.any(Number) as number,
739 },
740 ],
741 },
742 })
743 })
744​
745 it('fails the poll when the listing fails', async () => {
746 globalThis.fetch = ((url: string) =>
747 Promise.resolve(
748 String(url) === MODELS_URL
749 ? new Response('down', { status: 503 })
750 : new Response(String(url) === DOC_URL ? MODELS_DOC : EFFORT_DOC),
751 )) as typeof fetch
752 await expect(
753 provider.listModels({ PERPLEXITY_API_KEY: 'test-key' }),
754 ).rejects.toThrow('503')
755 })
756})
757​
758describe('perplexity fetchSpec', () => {
759 it('loads the published OpenAPI document without a key', async () => {
760 const spec = {
761 openapi: '3.1.0',
762 info: { title: 'Perplexity AI API' },
763 paths: { '/v1/sonar': { post: { summary: 'Create Chat Completion' } } },
764 }
765 globalThis.fetch = ((url: string) => {
766 expect(String(url)).toBe('https://docs.perplexity.ai/openapi.json')
767 return Promise.resolve(new Response(JSON.stringify(spec)))
768 }) as typeof fetch
769​
770 const fetched = await provider.fetchSpec({})
771 expect(fetched.specs).toHaveLength(1)
772 expect(fetched.specs[0]?.info?.title).toBe('Perplexity AI API')
773 expect(fetched.sources[0]?.url).toBe(
774 'https://docs.perplexity.ai/openapi.json',
775 )
776 expect(fetched.sources[0]?.hash).toMatch(/^[0-9a-f]{64}$/)
777 expect(fetched.outputStrategy).toBe('post-200')
778 })
779})
780​
781describe('perplexity Search API', () => {
782 // The upstream shape: the request is an allOf over shared filter schemas.
783 const ref = (name: string) => ({ $ref: `#/components/schemas/${name}` })
784 const json = (schema: object) => ({
785 content: { 'application/json': { schema } },
786 })
787 const spec = {
788 openapi: '3.1.0',
789 paths: {
790 '/search': {
791 post: {
792 requestBody: json(ref('ApiSearchRequest')),
793 responses: { '200': json(ref('ApiSearchResponse')) },
794 },
795 },
796 },
797 components: {
798 schemas: {
799 ApiSearchRequest: {
800 type: 'object',
801 allOf: [
802 {
803 type: 'object',
804 required: ['query'],
805 properties: {
806 query: {
807 anyOf: [
808 { type: 'string' },
809 { type: 'array', items: { type: 'string' } },
810 ],
811 },
812 max_results: { type: 'integer' },
813 },
814 },
815 ref('SearchDomainFilter'),
816 ],
817 },
818 SearchDomainFilter: {
819 type: 'object',
820 properties: {
821 search_domain_filter: { type: 'array', items: { type: 'string' } },
822 },
823 },
824 ApiSearchResponse: {
825 type: 'object',
826 required: ['results', 'id'],
827 properties: {
828 id: { type: 'string' },
829 results: { type: 'array', items: ref('ApiSearchPage') },
830 },
831 },
832 ApiSearchPage: {
833 type: 'object',
834 required: ['title', 'url', 'snippet'],
835 properties: {
836 title: { type: 'string' },
837 url: { type: 'string' },
838 snippet: { type: 'string' },
839 },
840 },
841 },
842 },
843 }
844​
845 it('bundles POST /search with its request and response', () => {
846 const { endpoints } = classifyAndBundle(provider, {
847 specs: [spec],
848 sources: [{ url: 'https://docs.perplexity.ai/openapi.json', hash: 'ab' }],
849 outputStrategy: 'post-200',
850 })
851 expect(endpoints).toHaveLength(1)
852 const [endpoint] = endpoints
853 expect(endpoint).toMatchObject({
854 path: '/search',
855 method: 'POST',
856 activity: 'search',
857 })
858 const text = JSON.stringify([endpoint?.input, endpoint?.output])
859 for (const name of [
860 'query',
861 'search_domain_filter',
862 'results',
863 'snippet',
864 ]) {
865 expect(text).toContain(`"${name}"`)
866 }
867 // Every $ref resolves inside the bundled schema.
868 expect(text).not.toContain('#/components/')
869 })
870})