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