Open History to see the last commit
1/** Meta's current hosted Model API documentation; no comparison catalogs. */
2import { compileTokenCard } from '@modelschemas/rate-card'
3import type { RateCard } from '@modelschemas/rate-card'
4import type { ModelInfo } from './types.ts'
5
6export const META_MODELS = 'https://dev.meta.ai/docs/models'
7export const META_PRICING = 'https://dev.meta.ai/docs/pricing-rate-limits'
8export const META_PROTOCOLS = 'https://dev.meta.ai/docs/protocols'
9export const META_REASONING = 'https://dev.meta.ai/docs/reasoning'
10export const META_REFERENCE = 'https://dev.meta.ai/docs/api-reference/'
11function fail(message: string): never {
12 throw new Error(`meta docs: ${message}`)
13}
14export function plain(text: string): string {
15 return text
16 .replace(/<script\b[\s\S]*?<\/script>/gi, '')
17 .replace(/<[^>]*>/g, '')
18 .replace(/"/g, '"')
19 .replace(/'|'/g, "'")
20 .replace(/&/g, '&')
21 .replace(/</g, '<')
22 .replace(/>/g, '>')
23 .replace(/ /g, ' ')
24 .replace(/\s+/g, ' ')
25 .trim()
26}
27/** Only server-rendered article content, excluding navigation and hydration. */
28export function article(html: string): string {
29 const start = html.indexOf('<h1')
30 if (start < 0) fail('missing article heading')
31 return html.slice(start).split('<script')[0] ?? ''
32}
33export function tables(html: string): Array<Array<Array<string>>> {
34 return [...html.matchAll(/<table\b[\s\S]*?<\/table>/gi)].map((table) =>
35 [...table[0].matchAll(/<tr\b[\s\S]*?<\/tr>/gi)].map((row) =>
36 [...row[0].matchAll(/<t[dh]\b[^>]*>([\s\S]*?)<\/t[dh]>/gi)].map((cell) =>
37 plain(cell[1] ?? ''),
38 ),
39 ),
40 )
41}
42function sections(
43 html: string,
44 level: number,
45): Array<{ name: string; id: string; body: string }> {
46 const source = article(html)
47 const heads = [
48 ...source.matchAll(
49 new RegExp(
50 `<h${level}\\b[^>]*id="([^"]+)"[^>]*>([\\s\\S]*?)<\\/h${level}>`,
51 'gi',
52 ),
53 ),
54 ]
55 return heads.map((head, i) => ({
56 name: plain(head[2] ?? ''),
57 id: head[1] ?? '',
58 body: source.slice(
59 head.index + head[0].length,
60 heads[i + 1]?.index ?? source.length,
61 ),
62 }))
63}
64const csv = (value: string) =>
65 value.split(',').map((x) =>
66 x
67 .trim()
68 .replace(/\*$/, '')
69 .toLowerCase()
70 .replace(/^text (?:prompt|transcript)$/, 'text'),
71 )
72const ID = /[a-z0-9][a-z0-9.-]*[a-z0-9]/g
73export const list = (value: string) =>
74 value.split(/,\s*(?:and\s+)?|\s+and\s+/).map((x) => x.trim().toLowerCase())
75const capabilityLinks = (html: string) =>
76 [
77 ...new Set(
78 [
79 ...html.matchAll(
80 /href="\/docs\/(tool-calling|structured-output|reasoning)"/g,
81 ),
82 ].map((m) => m[1]),
83 ),
84 ].map((page) =>
85 page === 'tool-calling'
86 ? 'tools'
87 : page === 'structured-output'
88 ? 'structured_outputs'
89 : 'reasoning',
90 )
91const isChatTable = (head: Array<string>) =>
92 head[0] === 'Model ID' && head.includes('Context window')
93/** Chat lines list only their Standard IDs on the models page; each has its own page. */
94export function metaChatFamilies(html: string): Array<string> {
95 return sections(html, 2)
96 .filter((s) => tables(s.body).some((rows) => isChatTable(rows[0] ?? [])))
97 .map((s) => s.id)
98}
99export const metaFamilyUrl = (id: string) => `https://dev.meta.ai/docs/${id}`
100/** A chat line's own page: its at-a-glance facts and every hosted ID with its mode. */
101function parseMetaFamily(html: string, family: string): Array<ModelInfo> {
102 const source = article(html)
103 const all = tables(source)
104 const glance = new Map(
105 (all.find((rows) => rows.some((row) => row[0] === 'Context window')) ?? [])
106 .filter((row) => row.length === 2)
107 .map((row) => [row[0] ?? '', row[1] ?? '']),
108 )
109 const input = glance.get('Input')
110 const output = glance.get('Output')
111 if (!input || !output) fail('missing model modalities')
112 const context = Number(
113 (glance.get('Context window') ?? '')
114 .replace(/ tokens$/, '')
115 .replace(/,/g, ''),
116 )
117 if (!Number.isSafeInteger(context) || context <= 0)
118 fail('unreadable model context')
119 const rows = all.find((t) => ['Variant', 'Version'].includes(t[0]?.[0] ?? ''))
120 if (!rows) fail('missing model availability table')
121 const head = rows[0] ?? []
122 if (head[1] !== 'Model API (pay-as-you-go)')
123 fail('model availability headers changed')
124 const capabilities = capabilityLinks(source)
125 const out: Array<ModelInfo> = []
126 for (const row of rows.slice(1)) {
127 if (row.length !== head.length) fail('invalid or duplicate model row')
128 if (row[1] === 'Not available') continue
129 const id = /^(.+) \(([a-z0-9][a-z0-9.-]*)\)$/.exec(row[0] ?? '')
130 const tier =
131 /^(?:Available \()?(Standard|Contributor) mode(?: only\))?$/.exec(
132 row[1] ?? '',
133 )?.[1]
134 if (!id?.[1] || !id[2]) fail('invalid or duplicate model row')
135 if (!tier) fail('unreadable model availability')
136 out.push({
137 rawId: id[2],
138 displayName: id[1],
139 activity: 'chat',
140 modalities: { input: list(input), output: list(output) },
141 contextWindow: context,
142 maxOutput: null,
143 capabilities,
144 pricing: null,
145 reasoning: null,
146 providerMetadata: { family, tier },
147 })
148 }
149 return out
150}
151/** `families` maps each `metaChatFamilies` section id to that line's page. */
152export function parseMetaModels(
153 html: string,
154 families: Record<string, string>,
155): Array<ModelInfo> {
156 const out: Array<ModelInfo> = []
157 const seen = new Set<string>()
158 const add = (model: ModelInfo) => {
159 if (seen.has(model.rawId)) fail('invalid or duplicate model row')
160 seen.add(model.rawId)
161 out.push(model)
162 }
163 for (const section of sections(html, 2)) {
164 const capabilities = capabilityLinks(section.body)
165 for (const rows of tables(section.body)) {
166 const head = rows[0] ?? []
167 if (head[0] !== 'Model ID') continue
168 const ids = rows.slice(1).flatMap((row) => {
169 const cell = (row[0] ?? '').split(/,\s*/)
170 if (
171 row.length !== head.length ||
172 cell.some((id) => !/^[a-z0-9][a-z0-9.-]*$/.test(id))
173 )
174 fail('invalid or duplicate model row')
175 return cell
176 })
177 if (isChatTable(head)) {
178 const page = families[section.id]
179 if (page === undefined) fail(`missing model page ${section.id}`)
180 const models = parseMetaFamily(page, section.name)
181 // The models page lists exactly the Standard IDs its line's page has.
182 const standard = models
183 .filter((m) => m.providerMetadata?.tier === 'Standard')
184 .map((m) => m.rawId)
185 if ([...standard].sort().join() !== [...ids].sort().join())
186 fail(`${section.name} page disagrees with the model table`)
187 models.forEach(add)
188 continue
189 }
190 const inputCol = head.findIndex(
191 (h) => h === 'Input modalities' || h === 'Input',
192 )
193 const outputCol = head.findIndex(
194 (h) => h === 'Output modalities' || h === 'Output',
195 )
196 if (inputCol < 0 || outputCol < 0) fail('model modality headers changed')
197 for (const row of rows.slice(1)) {
198 if ((row[0] ?? '').includes(',')) fail('invalid or duplicate model row')
199 const rawId = row[0] ?? ''
200 const input = row[inputCol]
201 const output = row[outputCol]
202 if (!input || !output) fail('missing model modalities')
203 const activity =
204 output === 'Image'
205 ? 'image'
206 : section.name === 'Muse Voice Transcribe'
207 ? 'audio'
208 : null
209 add({
210 rawId,
211 // One-row tables sit under the heading that names their line.
212 displayName: head.includes('Family')
213 ? (row[1] ?? null)
214 : rows.length === 2
215 ? section.name
216 : null,
217 activity,
218 modalities: { input: csv(input), output: csv(output) },
219 contextWindow: null,
220 maxOutput: null,
221 capabilities,
222 pricing: null,
223 reasoning: null,
224 providerMetadata: { family: section.name },
225 })
226 }
227 }
228 }
229 if (!out.length) fail('model table listed no models')
230 // A layout change that hides the chat tables must not read as removals.
231 if (!out.some((model) => model.activity === 'chat'))
232 fail('model page listed no chat models')
233 return out
234}
235type TokenMode = 'Standard' | 'Contributor'
236/** Mode columns are named. Meta publishes them in either order. */
237function tokenModeColumns(
238 head: Array<string>,
239): Record<TokenMode, number> | undefined {
240 if (head[0] !== 'Usage' || head.length !== 3) return
241 const found = new Map<TokenMode, number>()
242 for (let index = 1; index < head.length; index++) {
243 const cell = head[index]
244 const mode: TokenMode | undefined =
245 cell === 'Standard mode (per 1M tokens)'
246 ? 'Standard'
247 : cell === 'Contributor mode (per 1M tokens)'
248 ? 'Contributor'
249 : undefined
250 if (!mode || found.has(mode)) return
251 found.set(mode, index)
252 }
253 const standard = found.get('Standard')
254 const contributor = found.get('Contributor')
255 if (standard === undefined || contributor === undefined) return
256 return { Standard: standard, Contributor: contributor }
257}
258/**
259 * Muse Ember prices the whole request from its input size, cached tokens
260 * included. The two headers name the same threshold: at or below is the
261 * base column, over it is the long-context column.
262 */
263function promptSizeColumns(
264 head: Array<string>,
265): { threshold: number; upTo: number; over: number } | undefined {
266 if (head[0] !== 'Usage' || head.length !== 3) return
267 const attempt = /^(?:Up to|Over)\b.*\binput tokens \(per 1M tokens\)$/
268 const exact = /^(Up to|Over) (\d+)K input tokens \(per 1M tokens\)$/
269 const cells = [head[1] ?? '', head[2] ?? '']
270 if (!cells.some((cell) => attempt.test(cell))) return
271 const found = new Map<'Up to' | 'Over', { index: number; tokens: number }>()
272 for (let index = 0; index < cells.length; index++) {
273 const match = exact.exec(cells[index] ?? '')
274 if (!match) fail('unreadable prompt-size threshold')
275 const label = match[1] === 'Over' ? 'Over' : 'Up to'
276 if (found.has(label)) fail('unreadable prompt-size threshold')
277 found.set(label, { index: index + 1, tokens: Number(match[2]) })
278 }
279 const upTo = found.get('Up to')
280 const over = found.get('Over')
281 if (!upTo || !over || upTo.tokens === 0)
282 fail('unreadable prompt-size threshold')
283 if (upTo.tokens !== over.tokens) fail('prompt-size thresholds disagree')
284 const threshold = upTo.tokens * 1000
285 if (!Number.isSafeInteger(threshold)) fail('unreadable prompt-size threshold')
286 return { threshold, upTo: upTo.index, over: over.index }
287}
288export function parseMetaPricing(
289 html: string,
290 models: Array<ModelInfo>,
291 source: RateCard['source'],
292): Map<string, RateCard> {
293 const cards = new Map<string, RateCard>()
294 const tiers = new Map(
295 models.map((model) => [
296 model.rawId,
297 (model.providerMetadata as { tier?: string } | undefined)?.tier,
298 ]),
299 )
300 for (const section of sections(html, 3)) {
301 const rows = tables(section.body)[0]
302 const head = rows?.[0] ?? []
303 const tokenCols = tokenModeColumns(head)
304 const sizeCols = tokenCols ? undefined : promptSizeColumns(head)
305 if (rows && (tokenCols || sizeCols)) {
306 // "Models: a, b in Standard mode; c in Contributor mode." A section
307 // that names no mode must have only one priced column.
308 const columns = new Map<string, TokenMode | undefined>()
309 for (const clause of plain(section.body.split(/<table\b/)[0] ?? '').split(
310 ';',
311 )) {
312 const modes = [
313 ...new Set(
314 [...clause.matchAll(/\bin (Standard|Contributor) mode\b/g)].map(
315 (m) => m[1],
316 ),
317 ),
318 ]
319 if (modes.length > 1) fail('ambiguous token price mode')
320 for (const id of clause.match(ID) ?? []) {
321 if (!tiers.has(id)) continue
322 if (columns.has(id)) fail('duplicate model price')
323 columns.set(
324 id,
325 modes[0] === 'Contributor' || modes[0] === 'Standard'
326 ? modes[0]
327 : undefined,
328 )
329 }
330 }
331 if (!columns.size) fail('token pricing has no native model IDs')
332 const meters: Record<string, string> = {
333 'Cached input': 'cache_read_tokens',
334 Input: 'input_tokens',
335 Output: 'output_tokens',
336 }
337 const columnRates = (index: number) => {
338 const rates: Record<string, number> = {}
339 for (const row of rows.slice(1)) {
340 const key = meters[row[0] ?? '']
341 if (!key || row.length !== 3) fail('unreadable token price')
342 const cell = row[index] ?? ''
343 if (cell === 'Not available') continue
344 const price = /^\$(\d+(?:\.\d+)?)$/.exec(cell)
345 if (!price) fail('unreadable token price')
346 rates[key] = Number(price[1]) / 1e6
347 }
348 return rates
349 }
350 const rates: Record<TokenMode, Record<string, number>> = {
351 Standard: {},
352 Contributor: {},
353 }
354 if (tokenCols)
355 for (const mode of ['Standard', 'Contributor'] as const)
356 rates[mode] = columnRates(tokenCols[mode])
357 const base = sizeCols ? columnRates(sizeCols.upTo) : {}
358 const over = sizeCols ? columnRates(sizeCols.over) : {}
359 const priced = (['Standard', 'Contributor'] as const).filter(
360 (mode) => Object.keys(rates[mode]).length,
361 )
362 for (const [id, stated] of columns) {
363 const mode = sizeCols
364 ? stated
365 : (stated ?? (priced.length === 1 ? priced[0] : undefined))
366 if (!mode) fail('token price mode unstated')
367 const tier = tiers.get(id)
368 if (tier && mode !== tier)
369 fail('token price mode disagrees with model tier')
370 const colRates = sizeCols ? base : rates[mode]
371 if (!('input_tokens' in colRates) || !('output_tokens' in colRates))
372 fail('incomplete token pricing')
373 // A lever the long-context column leaves out would bill at the base
374 // rate (compileTokenCard tiers fall back), so both columns must
375 // price the same levers.
376 if (
377 sizeCols &&
378 Object.keys(over).sort().join() !== Object.keys(base).sort().join()
379 )
380 fail('prompt-size columns price different levers')
381 if (cards.has(id)) fail('duplicate model price')
382 const card = sizeCols
383 ? compileTokenCard(
384 colRates,
385 [{ minPromptTokens: sizeCols.threshold, rates: over }],
386 source,
387 )
388 : compileTokenCard(colRates, [], source)
389 if (!card) fail('uncompilable token price')
390 cards.set(id, card)
391 }
392 } else {
393 const matches = models.filter((model) => {
394 const metadata = model.providerMetadata as { family?: string }
395 return section.name.includes(metadata.family ?? '\u0000')
396 })
397 if (!matches.length) continue
398 const rates: Record<string, number> = {}
399 const text = plain(section.body)
400 if (rows?.[0]?.join('|') === 'Usage|Price')
401 for (const row of rows.slice(1)) {
402 const value = row[1] ?? ''
403 if (row[0] === 'Audio processed') {
404 const p = /^\$(\d+(?:\.\d+)?) per hour$/.exec(value)
405 if (!p) fail('unreadable audio price')
406 rates.audio_seconds = Number(p[1]) / 3600
407 } else if (row[0] === 'Generated image') {
408 const p = /^\$(\d+(?:\.\d+)?) per image$/.exec(value)
409 if (!p) fail('unreadable image price')
410 rates.generated_images = Number(p[1])
411 } else if (
412 row[0] === 'Image segmentation' ||
413 row[0] === 'Video segmentation'
414 ) {
415 const p = /^\$(\d+(?:\.\d+)?) per ([\d,]+) (images|frames)$/.exec(
416 value,
417 )
418 if (!p) fail('unreadable segmentation price')
419 rates[p[3] === 'images' ? 'segmented_images' : 'video_frames'] =
420 Number(p[1]) / Number(p[2]?.replace(/,/g, ''))
421 } else fail('unknown priced usage')
422 }
423 else if (section.name.includes('Image generation')) {
424 const p = /flat \$(\d+(?:\.\d+)?) per generated image/.exec(text)
425 if (!p) fail('unreadable image price')
426 rates.generated_images = Number(p[1])
427 } else if (rows?.[0]?.[0] === 'Usage')
428 fail(`unknown pricing table in ${section.name}`)
429 else continue
430 const card = compileTokenCard(rates, [], source)
431 if (!card) fail('uncompilable unit pricing')
432 for (const model of matches) cards.set(model.rawId, card)
433 }
434 }
435 if (!cards.size) fail('pricing parsed no rates')
436 // Every pay-as-you-go chat ID is token priced; a missing card is a misread.
437 for (const [id, tier] of tiers)
438 if (tier && !cards.has(id)) fail('token-priced model has no price')
439 return cards
440}
441
442// A mechanical translation of Meta's own schema tables. Unknown types throw.
443type Schema = Record<string, unknown>
444const nameKey = (s: string) => s.replace(/[^a-z0-9]/gi, '').toLowerCase()
445export function parseMetaSchemas(html: string): Record<string, Schema> {
446 const blocks = sections(html, 3)
447 const names = new Map(blocks.map((b) => [nameKey(b.name), b.id]))
448 const out: Record<string, Schema> = {}
449 const typeOf = (text: string): Schema => {
450 if (text === '') return { 'x-source-type': null }
451 const union = text.split(/\s*\|\s*/)
452 if (union.length > 1) return { anyOf: union.map(typeOf) }
453 if (text.startsWith('array of '))
454 return { type: 'array', items: typeOf(text.slice(9)) }
455 if (text.startsWith('enum (')) {
456 const values = [...text.matchAll(/'([^']*)'/g)].map((m) => m[1])
457 if (!values.length) fail('unreadable enum')
458 return { type: 'string', enum: values }
459 }
460 const primitive =
461 /^(string|integer|number|boolean|object|null)(?: \((uri|unixtime|binary|int64|int32)\))?$/.exec(
462 text,
463 )
464 if (primitive)
465 return {
466 type: primitive[1],
467 ...(primitive[2] && primitive[2] !== 'unixtime'
468 ? { format: primitive[2] }
469 : {}),
470 }
471 const id = names.get(nameKey(text))
472 if (!id) fail(`unknown schema type ${text}`)
473 return { $ref: `#/components/schemas/${id}` }
474 }
475 for (const block of blocks) {
476 const rows = tables(block.body)[0]
477 if (rows?.[0]?.join('|') === 'Field|Type|Required|Description') {
478 const schema: Schema = { type: 'object', properties: {} }
479 const nodes = new Map<string, Schema>([['', schema]])
480 for (const row of rows.slice(1)) {
481 if (row.length !== 4 || !['Yes', 'No'].includes(row[2] ?? ''))
482 fail('schema field row changed')
483 const field = row[0] ?? ''
484 const pieces = field.split('.')
485 const leaf = pieces.pop()
486 const parentPath = pieces.join('.')
487 let parent = nodes.get(parentPath)
488 if (!parent || !leaf) fail(`unresolved nested field ${field}`)
489 // A nullable object has its object branch in anyOf.
490 if (Array.isArray(parent.anyOf)) {
491 parent = (parent.anyOf as Array<Schema>).find(
492 (s) => s.type === 'object',
493 )
494 if (!parent) fail(`non-object parent ${field}`)
495 }
496 if (parent.type === 'array') parent = parent.items as Schema
497 if (parent.type !== 'object') fail(`non-object field parent ${field}`)
498 const node = typeOf(row[1] ?? '')
499 const description = row[3] ?? ''
500 node.description = description
501 for (const m of description.matchAll(
502 /\b(minimum|maximum|minItems|maxItems|minLength|maxLength): (-?\d+(?:\.\d+)?)/g,
503 ))
504 node[m[1] ?? ''] = Number(m[2])
505 const def = description.match(
506 /\bdefault: (true|false|-?\d+(?:\.\d+)?)/,
507 )?.[1]
508 if (def !== undefined)
509 node.default =
510 def === 'true' ? true : def === 'false' ? false : Number(def)
511 const properties = (parent.properties ??= {}) as Record<string, Schema>
512 properties[leaf.replace(/\[\]$/, '')] = node
513 if (row[2] === 'Yes') {
514 const required = (parent.required ??= []) as Array<string>
515 required.push(leaf.replace(/\[\]$/, ''))
516 }
517 nodes.set(field, node)
518 if (node.type === 'array') nodes.set(`${field}[]`, node)
519 if (leaf.endsWith('[]')) nodes.set(field.replace(/\[\]$/, ''), node)
520 }
521 out[block.id] = schema
522 } else {
523 const alias = [...block.body.matchAll(/<p\b[^>]*>([\s\S]*?)<\/p>/g)]
524 .map((p) => plain(p[1] ?? ''))
525 .find((p) => p.startsWith('Type: '))
526 if (!alias) fail(`schema ${block.name} has no table or type`)
527 out[block.id] = typeOf(alias.slice(6))
528 }
529 }
530 if (!Object.keys(out).length) fail('no native schema definitions')
531 return out
532}
533export function metaOperation(
534 html: string,
535 schemas: Record<string, Schema>,
536): { path: string; operation: Schema } {
537 const source = article(html)
538 const text = plain(source)
539 const endpoint = text.match(/\bPOST (\/[^ ]+)/)?.[1]
540 if (!endpoint) fail('missing native POST endpoint')
541 const request = source
542 .split('id="request-body"')[1]
543 ?.split('id="response"')[0]
544 const response = source.split('id="response"')[1]
545 const content = (block: string | undefined): Record<string, unknown> => {
546 if (!block) fail('missing native content block')
547 const contentHeads = [...block.matchAll(/<h4\b[^>]*>[\s\S]*?<\/h4>/g)]
548 const out: Record<string, unknown> = {}
549 for (const [i, heading] of contentHeads.entries()) {
550 const media = plain(heading[0]).match(/^Content Type: ([\w/+.-]+)$/)?.[1]
551 if (!media) fail('unreadable native content type')
552 const body =
553 block
554 .slice(
555 heading.index + heading[0].length,
556 contentHeads[i + 1]?.index ?? block.length,
557 )
558 .split(/<h3\b/)[0] ?? ''
559 // Usually `<resource>/schemas#id`; Messages links the same ids on its own page.
560 const id = body.match(/href="\/docs\/api-reference\/[^"#]+#([^"]+)"/)?.[1]
561 let schema: Schema
562 if (id) {
563 if (!schemas[id]) fail('missing native schema reference')
564 schema = { $ref: `#/components/schemas/${id}` }
565 } else {
566 // ASR publishes an inline `object`, without a field/type table. Keep
567 // that exact declared shape unconstrained; do not invent multipart fields.
568 const inline = [...body.matchAll(/<p\b[^>]*>([\s\S]*?)<\/p>/g)]
569 .map((p) => plain(p[1] ?? ''))
570 .find((p) => p === 'object')
571 if (!inline) fail('missing native schema reference')
572 schema = { type: 'object', 'x-source-fields': null }
573 }
574 out[media] = { schema }
575 }
576 if (!Object.keys(out).length) fail('missing native content types')
577 return out
578 }
579 if (!plain(response ?? '').includes('HTTP 200'))
580 fail('missing native successful response')
581 return {
582 path: `/v1${endpoint}`,
583 operation: {
584 requestBody: { required: true, content: content(request) },
585 responses: {
586 '200': {
587 description: 'Native documented response',
588 content: content(response),
589 },
590 },
591 },
592 }
593}