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

perplexity.ts

485 lines16.8 KB

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