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