Open History to see the last commit
1/**
2 * Perplexity — public OpenAPI 3.1 spec at docs.perplexity.ai/openapi.json.
3 * Generation is Sonar (`/v1/sonar`) and the Agent API (`/v1/agent`), plus
4 * embeddings and the Search API (`/search`, which takes no model). Async
5 * jobs, files/cancel, and analytics are platform.
6 */
7import type { Activity } from '#/db/schema.ts'
8import { perplexityListingCard } from '../catalog-prices.ts'
9import {
10 cachedDocs,
11 docsReport,
12 docsRun,
13 markdownTableRows,
14 tokenCount,
15 tryDocs,
16 unavailable,
17} from '../model-facts.ts'
18import {
19 fetchJson,
20 fetchOpenApi,
21 fetchText,
22 sha256Text,
23 skippedResult,
24} from '../types.ts'
25import { bearerConnect } from '../connect.ts'
26import type {
27 FactSource,
28 ListModelsResult,
29 ModelInfo,
30 ProviderConfig,
31 ProviderSecrets,
32 SpecFetchResult,
33} from '../types.ts'
34import { namespacedUpstreamIdentity } from '../upstream-model.ts'
35
36const PERPLEXITY_OPENAPI_URL = 'https://docs.perplexity.ai/openapi.json'
37const PERPLEXITY_MODELS_URL = 'https://api.perplexity.ai/v1/models'
38const PERPLEXITY_MODELS_DOC_URL =
39 'https://docs.perplexity.ai/docs/agent-api/models.md'
40const PERPLEXITY_EFFORT_DOC_URL =
41 'https://docs.perplexity.ai/docs/agent-api/effort.md'
42const FETCH_TIMEOUT_MS = 20_000
43
44function classify(path: string): Activity | null {
45 if (path === '/v1/sonar' || path === '/v1/agent') return 'chat'
46 if (path === '/v1/embeddings' || path === '/v1/contextualizedembeddings') {
47 return 'embeddings'
48 }
49 if (path === '/search') return 'search'
50 return null
51}
52
53async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
54 const { spec, hash } = await fetchOpenApi(PERPLEXITY_OPENAPI_URL)
55 return {
56 specs: [spec],
57 sources: [{ url: PERPLEXITY_OPENAPI_URL, hash }],
58 outputStrategy: 'post-200',
59 }
60}
61
62/** Model id → the capability flags one docs page states for it. */
63type StatedFlags = Map<string, Array<string>>
64
65/** A reasoning card's "N-token context window and up to N output tokens". */
66interface StatedLimits {
67 contextWindow: number
68 maxOutput: number | null
69}
70
71function addFlags(out: StatedFlags, id: string, flags: Array<string>): void {
72 out.set(id, [...new Set([...(out.get(id) ?? []), ...flags])])
73}
74
75/**
76 * The markdown export renders cards, callouts and accordions as `>`
77 * blockquotes; unquoted, their sentences and bullets start the line.
78 */
79function unquote(text: string): string {
80 return text.replace(/^> ?/gm, '')
81}
82
83/**
84 * Flags the Agent API models page states, per model id. Under "Available
85 * Models" each provider tab is one `> [tab] Title` blockquote (the
86 * markdown export's shape since 2026-10-30) holding a `> [card] Title`
87 * card, a model table and, for some, `> [!NOTE]`/`> [!WARNING]` callouts.
88 * A tab with no card, a second card, any other blockquote in a tab, a
89 * table or card outside a tab, or any block between or after the tabs
90 * throws.
91 *
92 * - "Kimi K3 accepts `minimal`, … and `max` reasoning effort." gives
93 * `reasoning` and `reasoning_effort` to the row whose link text is the
94 * name, and its list is the row's `efforts`. A list that holds `none`
95 * or `off` says reasoning can be turned off; any other list leaves
96 * `mandatory` null.
97 * - A card sentence "<names> — …", "<names> is …" or "<names>, a(n) …"
98 * that ends "… reasoning model(s)." or "… reasoning model
99 * with a N-token context window[ and up to N output tokens]." gives
100 * `reasoning` to every row of its tab, and only when it names as many
101 * models as the tab lists. Its context window and output tokens, when
102 * stated, are those rows' `contextWindow` and `maxOutput` (#408). The
103 * card's other sentences are not read, so
104 * one speaking of reasoning or thinking throws.
105 *
106 * Any other wording of either statement throws, as does an effort sentence
107 * outside the tabs or a second one for the same model. So does tab prose
108 * that speaks of turning reasoning off ("cannot be disabled", "always on"):
109 * no such sentence is on the page today, and one must be read, not dropped.
110 */
111export function parsePerplexityModelsPage(markdown: string): {
112 flags: StatedFlags
113 efforts: Map<string, Array<string>>
114 limits: Map<string, StatedLimits>
115} {
116 const stated: StatedFlags = new Map()
117 const levels = new Map<string, Array<string>>()
118 const limits = new Map<string, StatedLimits>()
119 const unread = (what: string) =>
120 new Error(`perplexity: models page states ${what} in an unread shape`)
121 let rows = 0
122 let sentences = 0
123 const section = /^## Available Models\n([^]*?)(?=^## |(?![^]))/m.exec(
124 markdown,
125 )?.[1]
126 let tabs = 0
127 for (const block of (section ?? '').trim().split(/\n\n+/)) {
128 const [, title, quotedTab] =
129 /^> \[tab\] ([^\n]+)\n>\n((?:>.*(?:\n|$))+)$/.exec(block) ?? []
130 if (title === undefined || quotedTab === undefined) {
131 // Prose and callouts before the first tab are the section's intro.
132 // Anything between or after tabs would be unread tab content.
133 if (tabs > 0 || /^(?:> ?)*(?:\||\[(?:tab|card)\])/m.test(block)) {
134 throw unread('a tab with no title')
135 }
136 continue
137 }
138 tabs += 1
139 // The tab's body with its own quote level removed; its card and
140 // callouts are still quoted.
141 const chunk = unquote(quotedTab)
142 const tab = unquote(chunk)
143 const table = markdownTableRows(tab).filter((row) =>
144 /^`[^`]+`$/.test(row[0] ?? ''),
145 )
146 const ids = table.map((row) => (row[0] ?? '').slice(1, -1))
147 rows += ids.length
148
149 // Blank-line-separated blocks: the one card, then only callouts quote.
150 const quotes = chunk.split(/\n\n+/).filter((b) => b.startsWith('>'))
151 const cards = quotes.filter((b) => !b.startsWith('> [!'))
152 const quoted = /^> \[card\] ([^\n]+)\n>\n((?:>.*(?:\n|$))+)$/.exec(
153 cards[0] ?? '',
154 )
155 if (cards.length !== 1 || !quoted) throw unread('a card')
156 if (quoted[1] !== title) throw unread('a card for another tab')
157 const card = unquote(quoted[2] ?? '').trim()
158 if (/reasoning models?\b/i.test(card)) {
159 const parts = card.split(/(?<=\.)\s+/)
160 const said = parts.filter((s) => /reasoning models?\b/i.test(s))
161 const rest = parts.filter((s) => !said.includes(s))
162 const sentence =
163 said.length === 1 && !rest.some((s) => /reason|think/i.test(s))
164 ? /^(.+?)(?: (?:—|is) |, an? ).*\breasoning models?(?: with an? ([\d,]+)-token context window(?: and up to ([\d,]+) output tokens)?)?\.$/.exec(
165 said[0] ?? '',
166 )
167 : null
168 const subject = sentence?.[1] ?? ''
169 const names = subject.split(/, and |, | and /)
170 if (
171 subject === '' ||
172 names.length !== ids.length ||
173 /\b(?:not|no|non)\b/i.test(card)
174 ) {
175 throw unread('a reasoning model')
176 }
177 const contextWindow = tokenCount(sentence?.[2])
178 const maxOutput = tokenCount(sentence?.[3])
179 for (const id of ids) {
180 addFlags(stated, id, ['reasoning'])
181 // The sentence's limits belong to the models it names: every row
182 // of this tab, as checked above.
183 if (contextWindow !== null) limits.set(id, { contextWindow, maxOutput })
184 }
185 }
186
187 const efforts = [
188 ...tab.matchAll(
189 /^(\S.*?) accepts ((?:`[a-z]+`(?:, and |, | and )?)+) reasoning effort\./gm,
190 ),
191 ]
192 sentences += efforts.length
193 const prose = tab.split('\n').filter((line) => !line.startsWith('|'))
194 if (
195 prose.some(
196 (line) =>
197 /reasoning|thinking/i.test(line) &&
198 /disabl|always[- ]on|(?:turn|switch)\w* off|cannot be|can['’]t be/i.test(
199 line,
200 ),
201 )
202 ) {
203 throw unread('whether reasoning can be turned off')
204 }
205 const seen = new Set<string>()
206 for (const [, name, list] of efforts) {
207 const named = table.filter((cells) =>
208 cells.at(-1)?.startsWith(`[${name ?? ''}](`),
209 )
210 const id = named.length === 1 ? named[0]?.[0]?.slice(1, -1) : undefined
211 if (!id || seen.has(id)) throw unread('reasoning effort')
212 seen.add(id)
213 addFlags(stated, id, ['reasoning', 'reasoning_effort'])
214 levels.set(id, (list ?? '').match(/(?<=`)[a-z]+(?=`)/g) ?? [])
215 }
216 }
217 if (rows === 0) throw new Error('perplexity: models page lists no models')
218 if (sentences !== (markdown.match(/reasoning effort/gi) ?? []).length) {
219 throw unread('reasoning effort')
220 }
221 return { flags: stated, efforts: levels, limits }
222}
223
224/**
225 * Flags the effort page (named "presets" before 2026-10-22) states in its
226 * "current effort level values" accordions: each effort level names its
227 * model, the `reasoning.effort` it sends, and its tools, except a level
228 * that says it has no frozen configuration, which states no Model bullet. The title
229 * separator is an em dash, or a colon (`ultra` since 2026-10-29). A model a
230 * level runs with an effort takes `reasoning.effort`; one it runs with
231 * tools takes `tools`. The page says nothing of `tool_choice`. A level's
232 * fallback model gets no flags: the frozen request sends it the level's
233 * settings, but the page never says the fallback accepts them.
234 */
235export function parsePerplexityEffortLevels(markdown: string): StatedFlags {
236 const stated: StatedFlags = new Map()
237 // Each accordion is one `> [accordion] name — current effort level values`
238 // blockquote (the markdown export's shape since 2026-10-30). `ultra`
239 // titles the same block with a colon and no space before it. They run
240 // back to back up to the next unquoted `## ` heading (the prompts' own
241 // `## ` headings stay inside the quote). Any other block in that run, or
242 // a blank line splitting an accordion, throws.
243 const start = markdown.search(
244 /^> \[accordion\] [^\n]*current effort level values/m,
245 )
246 const run = start < 0 ? '' : (markdown.slice(start).split(/^## /m)[0] ?? '')
247 for (const block of run === '' ? [] : run.trim().split(/\n\n+/)) {
248 const [, level, quoted] =
249 /^> \[accordion\] ([^\s:—]+)(?: — |: )current effort level values\n((?:>.*(?:\n|$))*)$/.exec(
250 block,
251 ) ?? []
252 if (level === undefined || quoted === undefined) {
253 throw new Error(
254 'perplexity: effort level accordion is in an unread shape',
255 )
256 }
257 const body = unquote(quoted)
258 const bullet = (label: string): string | null => {
259 const lines = [
260 ...body.matchAll(new RegExp(`^\\* \\*\\*${label}:\\*\\* (.*)$`, 'gm')),
261 ]
262 if (lines.length > 1) {
263 throw new Error(`perplexity: effort level states ${label} twice`)
264 }
265 return lines[0]?.[1] ?? null
266 }
267 const effort = bullet('Reasoning effort')
268 const tools = bullet('Tools')
269 const single = bullet('Model')
270 const several = bullet('Models')
271 // `Model:` is a bare backticked id, or that id plus `(no fallback model)`
272 // (xhigh since 2026-11-19). That note states there is no fallback; any
273 // other text after the id is unread. `Models:` names the level's model,
274 // then the fallback the request carries. Only the first is the model
275 // the level is stated to run on.
276 const model =
277 single !== null && several !== null
278 ? undefined
279 : single !== null
280 ? /^`([^`\s]+)`(?: \(no fallback model\))?$/.exec(single)?.[1]
281 : /^`([^`\s]+)`, with `[^`\s]+` as the \[fallback model\]\([^)\s]+\)$/.exec(
282 several ?? '',
283 )?.[1]
284 if (!model) {
285 // A level that says it has no frozen configuration (`ultra-preview`)
286 // names no model. Any bullet on it is a setting this does not read.
287 if (
288 !/^\* \*\*/m.test(body) &&
289 body.includes(`\`${level}\` has no frozen configuration.`)
290 ) {
291 continue
292 }
293 throw new Error('perplexity: effort level names no model')
294 }
295 if (effort !== null) {
296 if (!/^`[a-z]+`$/.test(effort)) {
297 throw new Error(
298 "perplexity: effort level's reasoning effort is in an unread shape",
299 )
300 }
301 addFlags(stated, model, ['reasoning', 'reasoning_effort'])
302 }
303 if (tools !== null) {
304 if (!/^`[a-z_]+`/.test(tools)) {
305 throw new Error('perplexity: effort level tools are in an unread shape')
306 }
307 addFlags(stated, model, ['tools'])
308 }
309 }
310 if (stated.size === 0) {
311 throw new Error('perplexity: effort page lists no effort levels')
312 }
313 return stated
314}
315
316interface StatedDoc {
317 hash: string
318 flags: Array<[string, Array<string>]>
319 /** Absent on the effort page, and on an entry cached before efforts were kept. */
320 efforts?: Array<[string, Array<string>]>
321 /** Absent on the effort page, and on an entry cached before limits were kept. */
322 limits?: Array<[string, StatedLimits]>
323}
324
325function statedDoc(
326 kv: KVNamespace | undefined,
327 url: string,
328 parse: (markdown: string) => {
329 flags: StatedFlags
330 efforts?: Map<string, Array<string>>
331 limits?: Map<string, StatedLimits>
332 },
333): Promise<StatedDoc> {
334 return cachedDocs(kv, url, async () => {
335 const text = await fetchText(url, {
336 signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
337 })
338 const { flags, efforts, limits } = parse(text)
339 return {
340 hash: await sha256Text(text),
341 flags: [...flags],
342 ...(efforts ? { efforts: [...efforts] } : {}),
343 ...(limits ? { limits: [...limits] } : {}),
344 }
345 })
346}
347
348/**
349 * The flags both pages state for one model, each with its page, and the
350 * effort list the models page states for it.
351 */
352function statedFacts(
353 id: string,
354 docs: Array<{ url: string; doc: StatedDoc }>,
355): Pick<
356 ModelInfo,
357 'capabilities' | 'reasoning' | 'contextWindow' | 'maxOutput' | 'factSources'
358> {
359 const sources: Record<string, FactSource> = {}
360 let reasoning: Pick<ModelInfo, 'reasoning' | 'factSources'> = {}
361 for (const { url, doc } of docs) {
362 const efforts = new Map(doc.efforts).get(id)
363 if (efforts) {
364 reasoning = {
365 reasoning: {
366 mode: 'effort',
367 // The sentence is this model's own list: an off value in it is a
368 // statement. Without one the page does not say.
369 mandatory: efforts.some((e) => e === 'none' || e === 'off')
370 ? false
371 : null,
372 efforts,
373 },
374 factSources: {
375 reasoning: {
376 derivation: 'docs-derived',
377 sourceUrl: url,
378 sourceHash: doc.hash,
379 path: 'reasoning_effort',
380 },
381 },
382 }
383 }
384 for (const flag of new Map(doc.flags).get(id) ?? []) {
385 sources[flag] ??= {
386 derivation: 'docs-derived',
387 sourceUrl: url,
388 sourceHash: doc.hash,
389 path: flag,
390 }
391 }
392 }
393 const limited = docs.flatMap(({ url, doc }) => {
394 const stated = new Map(doc.limits).get(id)
395 return stated ? [{ url, hash: doc.hash, ...stated }] : []
396 })[0]
397 const limitSource = (path: string): FactSource => ({
398 derivation: 'docs-derived',
399 sourceUrl: limited?.url,
400 sourceHash: limited?.hash,
401 path,
402 })
403 const limits: Pick<ModelInfo, 'contextWindow' | 'maxOutput' | 'factSources'> =
404 limited
405 ? {
406 contextWindow: limited.contextWindow,
407 maxOutput: limited.maxOutput,
408 factSources: {
409 contextWindow: limitSource('contextWindow'),
410 ...(limited.maxOutput !== null
411 ? { maxOutput: limitSource('maxOutput') }
412 : {}),
413 },
414 }
415 : {}
416 const capabilities = Object.keys(sources)
417 if (capabilities.length === 0) return limits
418 return {
419 capabilities,
420 ...reasoning,
421 ...limits,
422 factSources: {
423 ...reasoning.factSources,
424 ...limits.factSources,
425 capabilities: sources,
426 },
427 }
428}
429
430type StatedFact = Exclude<keyof ReturnType<typeof statedFacts>, 'factSources'>
431
432/**
433 * Every fact `statedFacts` supplies; all are withheld when a page fails.
434 * Keyed by its return type, so a fact added there fails to compile here
435 * instead of going null on a docs failure.
436 */
437const STATED_FACTS: Record<StatedFact, true> = {
438 capabilities: true,
439 reasoning: true,
440 contextWindow: true,
441 maxOutput: true,
442}
443
444interface PerplexityModelList {
445 data?: Array<{ id: string; created?: number; pricing?: unknown }>
446}
447
448async function listModels(
449 env: ProviderSecrets,
450 kv?: KVNamespace,
451): Promise<ListModelsResult> {
452 const key = env.PERPLEXITY_API_KEY
453 if (!key) {
454 return { models: [], ...skippedResult('perplexity', 'PERPLEXITY_API_KEY') }
455 }
456 const run = docsRun()
457 const [body, modelsPage, effortPage] = await Promise.all([
458 fetchJson(PERPLEXITY_MODELS_URL, {
459 headers: { Authorization: `Bearer ${key}` },
460 signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
461 }) as Promise<PerplexityModelList>,
462 tryDocs(run, PERPLEXITY_MODELS_DOC_URL, () =>
463 statedDoc(kv, PERPLEXITY_MODELS_DOC_URL, parsePerplexityModelsPage),
464 ),
465 tryDocs(run, PERPLEXITY_EFFORT_DOC_URL, () =>
466 statedDoc(kv, PERPLEXITY_EFFORT_DOC_URL, (text) => ({
467 flags: parsePerplexityEffortLevels(text),
468 })),
469 ),
470 ])
471 // Both pages or neither: one page's flags alone would drop the other's.
472 const docs =
473 modelsPage && effortPage
474 ? [
475 { url: PERPLEXITY_MODELS_DOC_URL, doc: modelsPage },
476 { url: PERPLEXITY_EFFORT_DOC_URL, doc: effortPage },
477 ]
478 : null
479 const models: Array<ModelInfo> = []
480 for (const m of body.data ?? []) {
481 const pricing = await perplexityListingCard(
482 m.pricing,
483 PERPLEXITY_MODELS_URL,
484 )
485 models.push({
486 rawId: m.id,
487 releasedAt: m.created ?? null,
488 activity: 'chat' as const,
489 ...(pricing ? { pricing } : {}),
490 ...(docs
491 ? statedFacts(m.id, docs)
492 : unavailable(...(Object.keys(STATED_FACTS) as Array<StatedFact>))),
493 })
494 }
495 return { models, docsFailures: docsReport(run) }
496}
497
498export const provider: ProviderConfig = {
499 id: 'perplexity',
500 // The listing names the maker in the id's namespace, and `owned_by`
501 // repeats it on every row. A `perplexity/…` id is hosted by Perplexity
502 // and the listing names no maker for it. The models page does, as the
503 // title of the tab the row sits in (`Z.AI`, `Moonshot AI`, `NVIDIA`):
504 // that is not readable from an id, so those rows carry no evidence.
505 upstreamModelIdentity: (rawId) =>
506 rawId.startsWith('perplexity/')
507 ? null
508 : namespacedUpstreamIdentity(rawId, {
509 derivation: 'listing',
510 sourceUrl: PERPLEXITY_MODELS_URL,
511 path: 'data[].id',
512 }),
513 displayName: 'Perplexity',
514 authEnvVar: 'PERPLEXITY_API_KEY',
515 specSourceUrl: PERPLEXITY_OPENAPI_URL,
516 modelsEndpoint: PERPLEXITY_MODELS_URL,
517 defaultDerivation: 'upstream-spec',
518 connect: bearerConnect('https://api.perplexity.ai'),
519 fetchSpec,
520 listModels,
521 classify,
522 // /v1/models lists Agent API ids; /v1/sonar answers 400 "Invalid model"
523 // to `perplexity/sonar` and its spec enum holds only the bare Sonar ids.
524 generationEndpointId: () => 'v1/agent',
525 // "Not all third-party models support all features (e.g., reasoning,
526 // tools)" — docs.perplexity.ai/docs/agent-api/models. These four are the
527 // flags that sentence names; a row gets one back only from a docs page
528 // that states it. Of the flags the walk keeps, only `max_tokens` is
529 // stated as shared ("a shared Agent API parameter"). `temperature`,
530 // `top_p`, `response_format` and `structured_outputs` are kept on
531 // judgement: the sentence's "e.g." is open-ended and does not name them.
532 perModelSchemaFlags: [
533 'reasoning',
534 'reasoning_effort',
535 'tools',
536 'tool_choice',
537 ],
538}