Open History to see the last commit
1import { afterEach, describe, expect, it } from 'vitest'
2
3import {
4 parsePerplexityModelsPage,
5 parsePerplexityPresets,
6 provider,
7} from './perplexity.ts'
8
9const MODELS_URL = 'https://api.perplexity.ai/v1/models'
10const DOC_URL = 'https://docs.perplexity.ai/docs/agent-api/models.md'
11const PRESETS_URL = 'https://docs.perplexity.ai/docs/agent-api/presets.md'
12
13const HEADER = [
14 ' | Model | Input (\\$/1M) | Output (\\$/1M) | Cache read (\\$/1M) | Service tiers | Docs |',
15 ' | - | - | - | - | - | - |',
16]
17
18// Five tabs of the Agent API models page, as served on 2026-10-07.
19const MODELS_DOC = [
20 '## Available Models',
21 '',
22 '<Tabs>',
23 ' <Tab title="xAI">',
24 ' <Card title="xAI">',
25 ' Grok 4.7, 4.6, 4.5, 4.3, and 4.20 variants: flagship, reasoning, non-reasoning, and multi-agent.',
26 ' </Card>',
27 '',
28 ...HEADER,
29 ' | `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) |',
30 ' </Tab>',
31 '',
32 ' <Tab title="Z.AI">',
33 ' <Card title="Z.AI">',
34 ' GLM 5.3 and GLM 5.3 Flash — Z.AI reasoning models.',
35 ' </Card>',
36 '',
37 ...HEADER,
38 ' | `perplexity/glm-5.3` | 1.40 | 4.40 | 0.26 | — | [GLM](https://docs.z.ai) |',
39 ' | `perplexity/glm-5.3-flash` | 0.15 | 0.50 | 0.03 | — | [GLM-5.3 Flash](https://huggingface.co/zai-org/GLM-5.3-Flash) |',
40 ' </Tab>',
41 '',
42 ' <Tab title="Moonshot AI">',
43 ' <Card title="Moonshot AI">',
44 " Kimi K3 — Moonshot AI's flagship reasoning model.",
45 ' </Card>',
46 '',
47 ...HEADER,
48 ' | `perplexity/kimi-k3` | 3.00 | 15.00 | 0.30 | — | [Kimi K3](https://huggingface.co/moonshotai/Kimi-K3) |',
49 '',
50 ' <Info>',
51 ' 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.',
52 ' </Info>',
53 ' </Tab>',
54 '',
55 ' <Tab title="NVIDIA">',
56 ' <Card title="NVIDIA">',
57 ' Nemotron 3 Ultra is an open-weight reasoning model.',
58 ' </Card>',
59 '',
60 ...HEADER,
61 ' | `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) |',
62 ' </Tab>',
63 '',
64 ' <Tab title="Perplexity">',
65 ' <Card title="Perplexity">',
66 " Perplexity's grounded search model.",
67 ' </Card>',
68 '',
69 ...HEADER,
70 ' | `perplexity/sonar` | 0.25 | 2.50 | 0.0625 | — | — |',
71 ' </Tab>',
72 '</Tabs>',
73 '',
74 '<Warning>',
75 ' Not all third-party models support all features (e.g., reasoning, tools). Check model documentation for specific capabilities.',
76 '</Warning>',
77].join('\n')
78
79const KIMI_SENTENCE =
80 'Kimi K3 accepts `minimal`, `low`, `medium`, `high`, `xhigh`, and `max` reasoning effort.'
81
82describe('parsePerplexityModelsPage', () => {
83 it('reads the effort sentence and the reasoning-model cards', () => {
84 const page = parsePerplexityModelsPage(MODELS_DOC)
85 expect([...page.flags]).toEqual([
86 ['perplexity/glm-5.3', ['reasoning']],
87 ['perplexity/glm-5.3-flash', ['reasoning']],
88 ['perplexity/kimi-k3', ['reasoning', 'reasoning_effort']],
89 ['perplexity/nemotron-3-ultra-550b-a55b', ['reasoning']],
90 ])
91 expect([...page.efforts]).toEqual([
92 [
93 'perplexity/kimi-k3',
94 ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'],
95 ],
96 ])
97 })
98
99 it('leaves the effort flag off when no tab states an effort', () => {
100 const silent = MODELS_DOC.replace(/ {4}<Info>[^]*?<\/Info>\n/, '')
101 const page = parsePerplexityModelsPage(silent)
102 expect(page.flags.get('perplexity/kimi-k3')).toEqual(['reasoning'])
103 expect(page.efforts.size).toBe(0)
104 })
105
106 it.each([
107 ['a reworded sentence', 'Kimi K3 accepts', 'Kimi K3 supports'],
108 [
109 'a list with prose in it',
110 '`xhigh`, and `max`',
111 '`xhigh`, and up to `max`',
112 ],
113 ['a name no row carries', 'Kimi K3 accepts', 'Kimi K4 accepts'],
114 [
115 'a second, unread mention',
116 '</Info>',
117 'GLM takes any reasoning effort.\n</Info>',
118 ],
119 [
120 'a second sentence for the same model',
121 ' </Info>',
122 ' Kimi K3 accepts `low` and `high` reasoning effort.\n </Info>',
123 ],
124 [
125 'the sentence moved outside the tabs',
126 /^ {6}Kimi K3 accepts[^]*?(<Warning>)/m,
127 ` </Info>\n </Tab>\n</Tabs>\n\n${KIMI_SENTENCE}\n\n$1`,
128 ],
129 [
130 'a statement that reasoning cannot be disabled',
131 'reasoning effort. `minimal`',
132 'reasoning effort. Reasoning cannot be disabled. `minimal`',
133 ],
134 [
135 'a statement that the model always thinks',
136 "Kimi K3 — Moonshot AI's flagship reasoning model.",
137 "Kimi K3 — Moonshot AI's flagship always-on reasoning model.",
138 ],
139 [
140 'a card naming fewer models than its tab lists',
141 'GLM 5.3 and GLM 5.3 Flash — Z.AI',
142 'GLM 5.3 — Z.AI',
143 ],
144 [
145 'a card that denies it',
146 'is an open-weight reasoning model',
147 'is not a reasoning model',
148 ],
149 [
150 'a reworded card',
151 'is an open-weight reasoning model.',
152 'ranks among open reasoning models, in our tests.',
153 ],
154 ])('throws on %s', (_case, from, to) => {
155 const mutated = MODELS_DOC.replace(from, to)
156 expect(mutated).not.toBe(MODELS_DOC)
157 expect(() => parsePerplexityModelsPage(mutated)).toThrow('unread shape')
158 })
159
160 it('throws on a page with no model table, such as an HTML error page', () => {
161 expect(() => parsePerplexityModelsPage('<html>Not found</html>')).toThrow(
162 'lists no models',
163 )
164 })
165})
166
167// Three of the five presets, bullets as served on 2026-10-07. The prompt
168// blocks are cut to one line each; the real ones hold `## ` headings.
169const PRESETS_DOC = [
170 '## Current preset values',
171 '',
172 '<AccordionGroup>',
173 ' <Accordion title="fast — current preset values">',
174 ' Quick factual lookups with minimal latency and inline citations for search-backed claims.',
175 '',
176 ' * **Model:** `openai/gpt-6-luna`',
177 ' * **Prompt cache key:** `fast`',
178 ' * **Max steps:** 1',
179 ' * **Reasoning effort:** `none`',
180 ' * **Service tier:** `priority`',
181 ' * **Max output tokens:** 8192',
182 ' * **Tools:** `web_search`',
183 ' * **System prompt:** included inline below',
184 '',
185 ' ```text',
186 ' ## Role',
187 ' ```',
188 ' </Accordion>',
189 '',
190 ' <Accordion title="low — current preset values">',
191 ' * **Model:** `openai/gpt-6-luna`',
192 ' * **Reasoning effort:** `minimal`',
193 ' * **Tools:** `web_search`, `fetch_url` (`max_urls: 1`)',
194 ' </Accordion>',
195 '',
196 ' <Accordion title="xhigh — current preset values">',
197 ' * **Model:** `anthropic/claude-opus-5-5`',
198 ' * **Max steps:** 100',
199 ' * **Reasoning effort:** `high`',
200 ' * **Tools:** `web_search`, `finance_search`, `sandbox`',
201 ' </Accordion>',
202 '</AccordionGroup>',
203 '',
204 '## Next Steps',
205].join('\n')
206
207describe('parsePerplexityPresets', () => {
208 it('reads each preset model with the effort and tools it runs with', () => {
209 expect([...parsePerplexityPresets(PRESETS_DOC)]).toEqual([
210 ['openai/gpt-6-luna', ['reasoning', 'reasoning_effort', 'tools']],
211 ['anthropic/claude-opus-5-5', ['reasoning', 'reasoning_effort', 'tools']],
212 ])
213 })
214
215 it('gives a preset with no tools or effort bullet neither flag', () => {
216 const bare = PRESETS_DOC.replace(
217 ' * **Reasoning effort:** `high`\n * **Tools:** `web_search`, `finance_search`, `sandbox`\n',
218 '',
219 )
220 expect(parsePerplexityPresets(bare).has('anthropic/claude-opus-5-5')).toBe(
221 false,
222 )
223 })
224
225 it.each([
226 [
227 'a preset with no model bullet',
228 '* **Model:** `openai',
229 '* **LLM:** `openai',
230 ],
231 ['a model that is prose', '`anthropic/claude-opus-5-5`', 'Claude Opus 5.5'],
232 ['an effort that is prose', '`high`', 'high, or lower on retries'],
233 [
234 'tools that are prose',
235 '`web_search`, `finance_search`, `sandbox`',
236 'none',
237 ],
238 [
239 'a bullet stated twice',
240 ' * **Max steps:** 100',
241 ' * **Model:** `openai/gpt-6-sol`',
242 ],
243 ['a page with no preset accordions', / — current preset values/g, ''],
244 ])('throws on %s', (_case, from, to) => {
245 const mutated = PRESETS_DOC.replace(from, to)
246 expect(mutated).not.toBe(PRESETS_DOC)
247 expect(() => parsePerplexityPresets(mutated)).toThrow('perplexity: preset')
248 })
249})
250
251const originalFetch = globalThis.fetch
252
253afterEach(() => {
254 globalThis.fetch = originalFetch
255})
256
257describe('perplexity provider', () => {
258 it('exports seed metadata for the isolation loader', () => {
259 expect(provider.id).toBe('perplexity')
260 expect(provider.displayName).toBe('Perplexity')
261 expect(provider.authEnvVar).toBe('PERPLEXITY_API_KEY')
262 expect(provider.defaultDerivation).toBe('upstream-spec')
263 expect(provider.specSourceUrl).toBe(
264 'https://docs.perplexity.ai/openapi.json',
265 )
266 expect(provider.modelsEndpoint).toBe('https://api.perplexity.ai/v1/models')
267 })
268
269 it('names the maker the id is namespaced under, and none for hosted ids', () => {
270 expect(
271 provider.upstreamModelIdentity?.('xai/grok-4.20-non-reasoning'),
272 ).toMatchObject({
273 providerNamespace: 'xai',
274 rawId: 'grok-4.20-non-reasoning',
275 source: { derivation: 'listing', path: 'data[].id' },
276 })
277 expect(provider.upstreamModelIdentity?.('perplexity/kimi-k3')).toBeNull()
278 expect(provider.upstreamModelIdentity?.('sonar')).toBeNull()
279 })
280})
281
282describe('perplexity classify', () => {
283 it('maps generation paths and drops search, async, and platform', () => {
284 expect(provider.classify('/v1/sonar', {})).toBe('chat')
285 expect(provider.classify('/v1/agent', {})).toBe('chat')
286 expect(provider.classify('/v1/embeddings', {})).toBe('embeddings')
287 expect(provider.classify('/v1/contextualizedembeddings', {})).toBe(
288 'embeddings',
289 )
290 expect(provider.classify('/search', {})).toBeNull()
291 expect(provider.classify('/v1/async/sonar', {})).toBeNull()
292 expect(provider.classify('/v1/models', {})).toBeNull()
293 expect(provider.classify('/v1/agent/{id}/cancel', {})).toBeNull()
294 expect(provider.classify('/v1/analytics/computer/usage', {})).toBeNull()
295 })
296})
297
298describe('perplexity listModels', () => {
299 it('skips when the secret is absent', async () => {
300 const result = await provider.listModels({})
301 expect(result.skipped).toBe(
302 'perplexity: PERPLEXITY_API_KEY not set — skipped',
303 )
304 expect(result.models).toEqual([])
305 })
306
307 it('joins the listing to the flags both docs pages state', async () => {
308 const urls: Array<string> = []
309 globalThis.fetch = ((url: string, init?: RequestInit) => {
310 urls.push(String(url))
311 expect(init?.signal).toBeInstanceOf(AbortSignal)
312 if (String(url) === DOC_URL) {
313 return Promise.resolve(new Response(MODELS_DOC))
314 }
315 if (String(url) === PRESETS_URL) {
316 return Promise.resolve(new Response(PRESETS_DOC))
317 }
318 expect(
319 new Headers(init?.headers).get('Authorization')?.startsWith('Bearer '),
320 ).toBe(true)
321 return Promise.resolve(
322 Response.json({
323 object: 'list',
324 data: [
325 { id: 'perplexity/kimi-k3', created: 1 },
326 { id: 'perplexity/sonar', created: 2 },
327 { id: 'openai/gpt-6-luna', created: 3 },
328 { id: 'xai/grok-4.20-non-reasoning', created: 4 },
329 ],
330 }),
331 )
332 }) as typeof fetch
333
334 const result = await provider.listModels({
335 PERPLEXITY_API_KEY: 'test-key',
336 })
337 expect(urls.sort()).toEqual([MODELS_URL, DOC_URL, PRESETS_URL])
338 expect(result.skipped).toBeUndefined()
339 const source = (sourceUrl: string, path: string) => ({
340 derivation: 'docs-derived',
341 sourceUrl,
342 sourceHash: expect.stringMatching(/^[0-9a-f]{64}$/) as string,
343 path,
344 })
345 expect(result.models).toEqual([
346 {
347 rawId: 'perplexity/kimi-k3',
348 releasedAt: 1,
349 activity: 'chat',
350 capabilities: ['reasoning', 'reasoning_effort'],
351 // The page publishes the levels and is silent on turning it off.
352 reasoning: {
353 mode: 'effort',
354 mandatory: null,
355 efforts: ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'],
356 },
357 factSources: {
358 reasoning: source(DOC_URL, 'reasoning_effort'),
359 capabilities: {
360 reasoning: source(DOC_URL, 'reasoning'),
361 reasoning_effort: source(DOC_URL, 'reasoning_effort'),
362 },
363 },
364 },
365 { rawId: 'perplexity/sonar', releasedAt: 2, activity: 'chat' },
366 {
367 rawId: 'openai/gpt-6-luna',
368 releasedAt: 3,
369 activity: 'chat',
370 capabilities: ['reasoning', 'reasoning_effort', 'tools'],
371 factSources: {
372 capabilities: {
373 reasoning: source(PRESETS_URL, 'reasoning'),
374 reasoning_effort: source(PRESETS_URL, 'reasoning_effort'),
375 tools: source(PRESETS_URL, 'tools'),
376 },
377 },
378 },
379 { rawId: 'xai/grok-4.20-non-reasoning', releasedAt: 4, activity: 'chat' },
380 ])
381 // Only the row whose effort list the models page states gets `reasoning`.
382 expect(result.models.filter((model) => model.reasoning != null)).toEqual([
383 expect.objectContaining({ rawId: 'perplexity/kimi-k3' }),
384 ])
385 expect(
386 provider.generationEndpointId?.({
387 rawId: 'perplexity/sonar',
388 activity: 'chat',
389 }),
390 ).toBe('v1/agent')
391 })
392
393 it('reads an off value in the published list as "can be turned off"', async () => {
394 const withNone = MODELS_DOC.replace('accepts `minimal`,', 'accepts `none`,')
395 expect(withNone).not.toBe(MODELS_DOC)
396 globalThis.fetch = ((url: string) =>
397 Promise.resolve(
398 String(url) === MODELS_URL
399 ? Response.json({ data: [{ id: 'perplexity/kimi-k3' }] })
400 : new Response(String(url) === DOC_URL ? withNone : PRESETS_DOC),
401 )) as typeof fetch
402 const result = await provider.listModels({ PERPLEXITY_API_KEY: 'test-key' })
403 expect(result.models[0]?.reasoning).toEqual({
404 mode: 'effort',
405 mandatory: false,
406 efforts: ['none', 'low', 'medium', 'high', 'xhigh', 'max'],
407 })
408 })
409
410 it('still lists, and reports the page, when a docs page is an HTML error page', async () => {
411 globalThis.fetch = ((url: string) =>
412 Promise.resolve(
413 String(url) === MODELS_URL
414 ? Response.json({ data: [{ id: 'perplexity/sonar' }] })
415 : String(url) === DOC_URL
416 ? new Response(MODELS_DOC)
417 : new Response('<html>Not found</html>'),
418 )) as typeof fetch
419 // One page down withholds both pages' flags: half of them would read
420 // as the other half dropped.
421 expect(
422 await provider.listModels({ PERPLEXITY_API_KEY: 'test-key' }),
423 ).toEqual({
424 models: [
425 {
426 rawId: 'perplexity/sonar',
427 releasedAt: null,
428 activity: 'chat',
429 absent: { capabilities: 'unavailable', reasoning: 'unavailable' },
430 },
431 ],
432 docsFailures: {
433 failed: 1,
434 skipped: 0,
435 first: [
436 {
437 source: PRESETS_URL,
438 error: 'perplexity: presets page lists no preset models',
439 elapsedMs: expect.any(Number) as number,
440 },
441 ],
442 },
443 })
444 })
445
446 it('fails the poll when the listing fails', async () => {
447 globalThis.fetch = ((url: string) =>
448 Promise.resolve(
449 String(url) === MODELS_URL
450 ? new Response('down', { status: 503 })
451 : new Response(String(url) === DOC_URL ? MODELS_DOC : PRESETS_DOC),
452 )) as typeof fetch
453 await expect(
454 provider.listModels({ PERPLEXITY_API_KEY: 'test-key' }),
455 ).rejects.toThrow('503')
456 })
457})
458
459describe('perplexity fetchSpec', () => {
460 it('loads the published OpenAPI document without a key', async () => {
461 const spec = {
462 openapi: '3.1.0',
463 info: { title: 'Perplexity AI API' },
464 paths: { '/v1/sonar': { post: { summary: 'Create Chat Completion' } } },
465 }
466 globalThis.fetch = ((url: string) => {
467 expect(String(url)).toBe('https://docs.perplexity.ai/openapi.json')
468 return Promise.resolve(new Response(JSON.stringify(spec)))
469 }) as typeof fetch
470
471 const fetched = await provider.fetchSpec({})
472 expect(fetched.specs).toHaveLength(1)
473 expect(fetched.specs[0]?.info?.title).toBe('Perplexity AI API')
474 expect(fetched.sources[0]?.url).toBe(
475 'https://docs.perplexity.ai/openapi.json',
476 )
477 expect(fetched.sources[0]?.hash).toMatch(/^[0-9a-f]{64}$/)
478 expect(fetched.outputStrategy).toBe('post-200')
479 })
480})