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

meta-docs.ts

499 lines18.6 KB

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}`)
14export function plain(text: string): string {
15 return text
16 .replace(/<script\b[\s\S]*?<\/script>/gi, '')
17 .replace(/<[^>]*>/g, '')
18 .replace(/&quot;/g, '"')
19 .replace(/&#x27;|&#39;/g, "'")
20 .replace(/&amp;/g, '&')
21 .replace(/&lt;/g, '<')
22 .replace(/&gt;/g, '>')
23 .replace(/&nbsp;/g, ' ')
24 .replace(/\s+/g, ' ')
25 .trim()
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] ?? ''
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 )
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 }))
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())
75export function parseMetaModels(html: string): Array<ModelInfo> {
76 const out: Array<ModelInfo> = []
77 const seen = new Set<string>()
78 const add = (model: ModelInfo) => {
79 if (seen.has(model.rawId)) fail('invalid or duplicate model row')
80 seen.add(model.rawId)
81 out.push(model)
82 }
83 for (const section of sections(html, 2)) {
84 const capabilities = [
85 ...section.body.matchAll(
86 /href="(\/docs\/(?:tool-calling|structured-output|reasoning))"/g,
87 ),
88 ]
89 .map((m) =>
90 m[1] === '/docs/tool-calling'
91 ? 'tools'
92 : m[1] === '/docs/structured-output'
93 ? 'structured_outputs'
94 : 'reasoning',
95 )
96 .filter((flag, i, all) => all.indexOf(flag) === i)
97 const text = plain(section.body)
98 const chatRows = out.length
99 for (const rows of tables(section.body)) {
100 const head = rows[0] ?? []
101 // Chat lines list their hosted IDs in an availability table and state
102 // modalities and context once, in the section prose.
103 if (['Variant', 'Version'].includes(head[0] ?? '')) {
104 if (head[1] !== 'Model API (pay-as-you-go)')
105 fail('model availability headers changed')
106 const io = /\btakes? ([^.]+?) input, returns? ([^,.]+)/.exec(text)
107 const contexts = [
108 ...new Set(
109 [...text.matchAll(/\b([\d,]+)-token context window\b/g)].map(
110 (m) => m[1] ?? '',
111 ),
112 ),
113 ]
114 const context = Number(contexts[0]?.replace(/,/g, ''))
115 if (!io?.[1] || !io[2]) fail('missing model modalities')
116 if (
117 contexts.length !== 1 ||
118 !Number.isSafeInteger(context) ||
119 context <= 0
120 )
121 fail('unreadable model context')
122 for (const row of rows.slice(1)) {
123 if (row.length !== head.length) fail('invalid or duplicate model row')
124 if (row[1] === 'Not available') continue
125 const id = /^(.+) \(([a-z0-9][a-z0-9.-]*)\)$/.exec(row[0] ?? '')
126 const tier =
127 /^(?:Available \()?(Standard|Contributor) mode(?: only\))?$/.exec(
128 row[1] ?? '',
129 )?.[1]
130 if (!id?.[1] || !id[2]) fail('invalid or duplicate model row')
131 if (!tier) fail('unreadable model availability')
132 add({
133 rawId: id[2],
134 displayName: id[1],
135 activity: 'chat',
136 modalities: { input: list(io[1]), output: list(io[2]) },
137 contextWindow: context,
138 maxOutput: null,
139 capabilities,
140 pricing: null,
141 reasoning: null,
142 providerMetadata: { family: section.name, tier },
143 })
144 }
145 continue
146 }
147 if (head[0] !== 'Model ID') continue
148 const inputCol = head.findIndex(
149 (h) => h === 'Input modalities' || h === 'Input',
150 )
151 const outputCol = head.findIndex(
152 (h) => h === 'Output modalities' || h === 'Output',
153 )
154 if (inputCol < 0 || outputCol < 0) fail('model modality headers changed')
155 for (const row of rows.slice(1)) {
156 const rawId = row[0] ?? ''
157 if (
158 row.length !== head.length ||
159 !rawId ||
160 !/^[a-z0-9][a-z0-9.-]*$/.test(rawId)
161 )
162 fail('invalid or duplicate model row')
163 const input = row[inputCol]
164 const output = row[outputCol]
165 if (!input || !output) fail('missing model modalities')
166 const contextCol = head.indexOf('Context window')
167 const context =
168 contextCol < 0
169 ? null
170 : Number(
171 (row[contextCol] ?? '')
172 .replace(/ tokens$/, '')
173 .replace(/,/g, ''),
174 )
175 if (
176 context !== null &&
177 (!Number.isSafeInteger(context) || context <= 0)
178 )
179 fail('unreadable model context')
180 const activity = head.includes('Tier')
181 ? 'chat'
182 : output === 'Image'
183 ? 'image'
184 : section.name === 'Muse Voice Transcribe'
185 ? 'audio'
186 : null
187 add({
188 rawId,
189 // One-row tables sit under the heading that names their line.
190 displayName: head.includes('Family')
191 ? (row[1] ?? null)
192 : rows.length === 2
193 ? section.name
194 : null,
195 activity,
196 modalities: { input: csv(input), output: csv(output) },
197 contextWindow: context,
198 maxOutput: null,
199 capabilities,
200 pricing: null,
201 reasoning: null,
202 providerMetadata: {
203 family: section.name,
204 ...(head.includes('Tier')
205 ? { tier: row[head.indexOf('Tier')] }
206 : {}),
207 },
208 })
209 }
210 }
211 if (
212 /-token context window\b/.test(text) &&
213 !out.slice(chatRows).some((model) => model.activity === 'chat')
214 )
215 fail('chat section listed no models')
216 }
217 if (!out.length) fail('model table listed no models')
218 // A layout change that hides the chat tables must not read as removals.
219 if (!out.some((model) => model.activity === 'chat'))
220 fail('model page listed no chat models')
221 return out
223export function parseMetaPricing(
224 html: string,
225 models: Array<ModelInfo>,
226 source: RateCard['source'],
227): Map<string, RateCard> {
228 const cards = new Map<string, RateCard>()
229 const tiers = new Map(
230 models.map((model) => [
231 model.rawId,
232 (model.providerMetadata as { tier?: string } | undefined)?.tier,
233 ]),
234 )
235 for (const section of sections(html, 3)) {
236 const rows = tables(section.body)[0]
237 if (
238 rows?.[0]?.join('|') ===
239 'Usage|Standard mode (per 1M tokens)|Contributor mode (per 1M tokens)'
240 ) {
241 // "Models: a, b in Standard mode; c in Contributor mode." A section
242 // that names no mode must have only one priced column.
243 const columns = new Map<string, number>()
244 for (const clause of plain(section.body.split(/<table\b/)[0] ?? '').split(
245 ';',
246 )) {
247 const modes = [
248 ...new Set(
249 [...clause.matchAll(/\bin (Standard|Contributor) mode\b/g)].map(
250 (m) => m[1],
251 ),
252 ),
253 ]
254 if (modes.length > 1) fail('ambiguous token price mode')
255 for (const id of clause.match(ID) ?? []) {
256 if (!tiers.has(id)) continue
257 if (columns.has(id)) fail('duplicate model price')
258 columns.set(
259 id,
260 modes[0] === 'Contributor' ? 2 : modes[0] === 'Standard' ? 1 : 0,
261 )
262 }
263 }
264 if (!columns.size) fail('token pricing has no native model IDs')
265 const meters: Record<string, string> = {
266 'Cached input': 'cache_read_tokens',
267 Input: 'input_tokens',
268 Output: 'output_tokens',
269 }
270 const rates: Record<number, Record<string, number>> = { 1: {}, 2: {} }
271 for (const row of rows.slice(1)) {
272 const key = meters[row[0] ?? '']
273 if (!key || row.length !== 3) fail('unreadable token price')
274 for (const col of [1, 2]) {
275 const cell = row[col] ?? ''
276 if (cell === 'Not available') continue
277 const price = /^\$(\d+(?:\.\d+)?)$/.exec(cell)
278 if (!price) fail('unreadable token price')
279 const target = rates[col]
280 if (target) target[key] = Number(price[1]) / 1e6
281 }
282 }
283 const priced = [1, 2].filter(
284 (col) => Object.keys(rates[col] ?? {}).length,
285 )
286 for (const [id, stated] of columns) {
287 const col = stated || (priced.length === 1 ? priced[0] : undefined)
288 if (!col) fail('token price mode unstated')
289 const tier = tiers.get(id)
290 if (tier && col !== (tier === 'Contributor' ? 2 : 1))
291 fail('token price mode disagrees with model tier')
292 const colRates = rates[col] ?? {}
293 if (!('input_tokens' in colRates) || !('output_tokens' in colRates))
294 fail('incomplete token pricing')
295 if (cards.has(id)) fail('duplicate model price')
296 const card = compileTokenCard(colRates, [], source)
297 if (!card) fail('uncompilable token price')
298 cards.set(id, card)
299 }
300 } else {
301 const matches = models.filter((model) => {
302 const metadata = model.providerMetadata as { family?: string }
303 return section.name.includes(metadata.family ?? '\u0000')
304 })
305 if (!matches.length) continue
306 const rates: Record<string, number> = {}
307 const text = plain(section.body)
308 if (rows?.[0]?.join('|') === 'Usage|Price')
309 for (const row of rows.slice(1)) {
310 const value = row[1] ?? ''
311 if (row[0] === 'Audio processed') {
312 const p = /^\$(\d+(?:\.\d+)?) per hour$/.exec(value)
313 if (!p) fail('unreadable audio price')
314 rates.audio_seconds = Number(p[1]) / 3600
315 } else if (row[0] === 'Generated image') {
316 const p = /^\$(\d+(?:\.\d+)?) per image$/.exec(value)
317 if (!p) fail('unreadable image price')
318 rates.generated_images = Number(p[1])
319 } else if (
320 row[0] === 'Image segmentation' ||
321 row[0] === 'Video segmentation'
322 ) {
323 const p = /^\$(\d+(?:\.\d+)?) per ([\d,]+) (images|frames)$/.exec(
324 value,
325 )
326 if (!p) fail('unreadable segmentation price')
327 rates[p[3] === 'images' ? 'segmented_images' : 'video_frames'] =
328 Number(p[1]) / Number(p[2]?.replace(/,/g, ''))
329 } else fail('unknown priced usage')
330 }
331 else if (section.name.includes('Image generation')) {
332 const p = /flat \$(\d+(?:\.\d+)?) per generated image/.exec(text)
333 if (!p) fail('unreadable image price')
334 rates.generated_images = Number(p[1])
335 } else if (rows?.[0]?.[0] === 'Usage') fail('unknown pricing table')
336 else continue
337 const card = compileTokenCard(rates, [], source)
338 if (!card) fail('uncompilable unit pricing')
339 for (const model of matches) cards.set(model.rawId, card)
340 }
341 }
342 if (!cards.size) fail('pricing parsed no rates')
343 // Every pay-as-you-go chat ID is token priced; a missing card is a misread.
344 for (const [id, tier] of tiers)
345 if (tier && !cards.has(id)) fail('token-priced model has no price')
346 return cards
348​
349// A mechanical translation of Meta's own schema tables. Unknown types throw.
350type Schema = Record<string, unknown>
351const nameKey = (s: string) => s.replace(/[^a-z0-9]/gi, '').toLowerCase()
352export function parseMetaSchemas(html: string): Record<string, Schema> {
353 const blocks = sections(html, 3)
354 const names = new Map(blocks.map((b) => [nameKey(b.name), b.id]))
355 const out: Record<string, Schema> = {}
356 const typeOf = (text: string): Schema => {
357 if (text === '') return { 'x-source-type': null }
358 const union = text.split(/\s*\|\s*/)
359 if (union.length > 1) return { anyOf: union.map(typeOf) }
360 if (text.startsWith('array of '))
361 return { type: 'array', items: typeOf(text.slice(9)) }
362 if (text.startsWith('enum (')) {
363 const values = [...text.matchAll(/'([^']*)'/g)].map((m) => m[1])
364 if (!values.length) fail('unreadable enum')
365 return { type: 'string', enum: values }
366 }
367 const primitive =
368 /^(string|integer|number|boolean|object|null)(?: \((uri|unixtime|binary|int64|int32)\))?$/.exec(
369 text,
370 )
371 if (primitive)
372 return {
373 type: primitive[1],
374 ...(primitive[2] && primitive[2] !== 'unixtime'
375 ? { format: primitive[2] }
376 : {}),
377 }
378 const id = names.get(nameKey(text))
379 if (!id) fail(`unknown schema type ${text}`)
380 return { $ref: `#/components/schemas/${id}` }
381 }
382 for (const block of blocks) {
383 const rows = tables(block.body)[0]
384 if (rows?.[0]?.join('|') === 'Field|Type|Required|Description') {
385 const schema: Schema = { type: 'object', properties: {} }
386 const nodes = new Map<string, Schema>([['', schema]])
387 for (const row of rows.slice(1)) {
388 if (row.length !== 4 || !['Yes', 'No'].includes(row[2] ?? ''))
389 fail('schema field row changed')
390 const field = row[0] ?? ''
391 const pieces = field.split('.')
392 const leaf = pieces.pop()
393 const parentPath = pieces.join('.')
394 let parent = nodes.get(parentPath)
395 if (!parent || !leaf) fail(`unresolved nested field ${field}`)
396 // A nullable object has its object branch in anyOf.
397 if (Array.isArray(parent.anyOf)) {
398 parent = (parent.anyOf as Array<Schema>).find(
399 (s) => s.type === 'object',
400 )
401 if (!parent) fail(`non-object parent ${field}`)
402 }
403 if (parent.type === 'array') parent = parent.items as Schema
404 if (parent.type !== 'object') fail(`non-object field parent ${field}`)
405 const node = typeOf(row[1] ?? '')
406 const description = row[3] ?? ''
407 node.description = description
408 for (const m of description.matchAll(
409 /\b(minimum|maximum|minItems|maxItems|minLength|maxLength): (-?\d+(?:\.\d+)?)/g,
410 ))
411 node[m[1] ?? ''] = Number(m[2])
412 const def = description.match(
413 /\bdefault: (true|false|-?\d+(?:\.\d+)?)/,
414 )?.[1]
415 if (def !== undefined)
416 node.default =
417 def === 'true' ? true : def === 'false' ? false : Number(def)
418 const properties = (parent.properties ??= {}) as Record<string, Schema>
419 properties[leaf.replace(/\[\]$/, '')] = node
420 if (row[2] === 'Yes') {
421 const required = (parent.required ??= []) as Array<string>
422 required.push(leaf.replace(/\[\]$/, ''))
423 }
424 nodes.set(field, node)
425 if (node.type === 'array') nodes.set(`${field}[]`, node)
426 if (leaf.endsWith('[]')) nodes.set(field.replace(/\[\]$/, ''), node)
427 }
428 out[block.id] = schema
429 } else {
430 const alias = [...block.body.matchAll(/<p\b[^>]*>([\s\S]*?)<\/p>/g)]
431 .map((p) => plain(p[1] ?? ''))
432 .find((p) => p.startsWith('Type: '))
433 if (!alias) fail(`schema ${block.name} has no table or type`)
434 out[block.id] = typeOf(alias.slice(6))
435 }
436 }
437 if (!Object.keys(out).length) fail('no native schema definitions')
438 return out
440export function metaOperation(
441 html: string,
442 schemas: Record<string, Schema>,
443): { path: string; operation: Schema } {
444 const source = article(html)
445 const text = plain(source)
446 const endpoint = text.match(/\bPOST (\/[^ ]+)/)?.[1]
447 if (!endpoint) fail('missing native POST endpoint')
448 const request = source
449 .split('id="request-body"')[1]
450 ?.split('id="response"')[0]
451 const response = source.split('id="response"')[1]
452 const content = (block: string | undefined): Record<string, unknown> => {
453 if (!block) fail('missing native content block')
454 const contentHeads = [...block.matchAll(/<h4\b[^>]*>[\s\S]*?<\/h4>/g)]
455 const out: Record<string, unknown> = {}
456 for (const [i, heading] of contentHeads.entries()) {
457 const media = plain(heading[0]).match(/^Content Type: ([\w/+.-]+)$/)?.[1]
458 if (!media) fail('unreadable native content type')
459 const body =
460 block
461 .slice(
462 heading.index + heading[0].length,
463 contentHeads[i + 1]?.index ?? block.length,
464 )
465 .split(/<h3\b/)[0] ?? ''
466 const id = body.match(/href="[^"#]*\/schemas#([^"]+)"/)?.[1]
467 let schema: Schema
468 if (id) {
469 if (!schemas[id]) fail('missing native schema reference')
470 schema = { $ref: `#/components/schemas/${id}` }
471 } else {
472 // ASR publishes an inline `object`, without a field/type table. Keep
473 // that exact declared shape unconstrained; do not invent multipart fields.
474 const inline = [...body.matchAll(/<p\b[^>]*>([\s\S]*?)<\/p>/g)]
475 .map((p) => plain(p[1] ?? ''))
476 .find((p) => p === 'object')
477 if (!inline) fail('missing native schema reference')
478 schema = { type: 'object', 'x-source-fields': null }
479 }
480 out[media] = { schema }
481 }
482 if (!Object.keys(out).length) fail('missing native content types')
483 return out
484 }
485 if (!plain(response ?? '').includes('HTTP 200'))
486 fail('missing native successful response')
487 return {
488 path: `/v1${endpoint}`,
489 operation: {
490 requestBody: { required: true, content: content(request) },
491 responses: {
492 '200': {
493 description: 'Native documented response',
494 content: content(response),
495 },
496 },
497 },
498 }