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 )
72export function parseMetaModels(html: string): Array<ModelInfo> {
73 const out: Array<ModelInfo> = []
74 const seen = new Set<string>()
75 for (const section of sections(html, 2))
76 for (const rows of tables(section.body)) {
77 const head = rows[0] ?? []
78 if (head[0] !== 'Model ID') continue
79 const inputCol = head.findIndex(
80 (h) => h === 'Input modalities' || h === 'Input',
81 )
82 const outputCol = head.findIndex(
83 (h) => h === 'Output modalities' || h === 'Output',
84 )
85 if (inputCol < 0 || outputCol < 0) fail('model modality headers changed')
86 for (const row of rows.slice(1)) {
87 const rawId = row[0] ?? ''
88 if (
89 row.length !== head.length ||
90 !rawId ||
91 !/^[a-z0-9][a-z0-9.-]*$/.test(rawId) ||
92 seen.has(rawId)
93 )
94 fail('invalid or duplicate model row')
95 seen.add(rawId)
96 const input = row[inputCol]
97 const output = row[outputCol]
98 if (!input || !output) fail('missing model modalities')
99 const contextCol = head.indexOf('Context window')
100 const context =
101 contextCol < 0
102 ? null
103 : Number(
104 (row[contextCol] ?? '')
105 .replace(/ tokens$/, '')
106 .replace(/,/g, ''),
107 )
108 if (
109 context !== null &&
110 (!Number.isSafeInteger(context) || context <= 0)
111 )
112 fail('unreadable model context')
113 const activity = head.includes('Tier')
114 ? 'chat'
115 : output === 'Image'
116 ? 'image'
117 : section.name === 'Muse Voice Transcribe'
118 ? 'audio'
119 : null
120 out.push({
121 rawId,
122 displayName: head.includes('Family') ? (row[1] ?? null) : null,
123 activity,
124 modalities: { input: csv(input), output: csv(output) },
125 contextWindow: context,
126 maxOutput: null,
127 capabilities: [
128 ...section.body.matchAll(
129 /href="(\/docs\/(?:tool-calling|structured-output|reasoning))"/g,
130 ),
131 ]
132 .map((m) =>
133 m[1] === '/docs/tool-calling'
134 ? 'tools'
135 : m[1] === '/docs/structured-output'
136 ? 'structured_outputs'
137 : 'reasoning',
138 )
139 .filter((flag, i, all) => all.indexOf(flag) === i),
140 pricing: null,
141 reasoning: null,
142 providerMetadata: {
143 family: section.name,
144 ...(head.includes('Tier')
145 ? { tier: row[head.indexOf('Tier')] }
146 : {}),
147 },
148 })
149 }
150 }
151 if (!out.length) fail('model table listed no models')
152 return out
153}
154export function parseMetaPricing(
155 html: string,
156 models: Array<ModelInfo>,
157 source: RateCard['source'],
158): Map<string, RateCard> {
159 const cards = new Map<string, RateCard>()
160 for (const section of sections(html, 3)) {
161 const sourceIds = [
162 ...section.body.matchAll(/<code\b[^>]*>([^<]+)<\/code>/g),
163 ]
164 .map((m) => plain(m[1] ?? ''))
165 .filter((id) => models.some((model) => model.rawId === id))
166 const rows = tables(section.body)[0]
167 if (rows?.[0]?.join('|') === 'Usage|Price per 1M tokens') {
168 if (!sourceIds.length) fail('token pricing has no native model IDs')
169 const rates: Record<string, number> = {}
170 const meters: Record<string, string> = {
171 'Cached input': 'cache_read_tokens',
172 Input: 'input_tokens',
173 Output: 'output_tokens',
174 }
175 for (const row of rows.slice(1)) {
176 const key = meters[row[0] ?? '']
177 const price = /^\$(\d+(?:\.\d+)?)$/.exec(row[1] ?? '')
178 if (!key || !price || row.length !== 2) fail('unreadable token price')
179 rates[key] = Number(price[1]) / 1e6
180 }
181 if (!('input_tokens' in rates) || !('output_tokens' in rates))
182 fail('incomplete token pricing')
183 for (const id of sourceIds) {
184 if (cards.has(id)) fail('duplicate model price')
185 const card = compileTokenCard(rates, [], source)
186 if (!card) fail('uncompilable token price')
187 cards.set(id, card)
188 }
189 } else {
190 const matches = models.filter((model) => {
191 const metadata = model.providerMetadata as { family?: string }
192 return section.name.includes(metadata.family ?? '\u0000')
193 })
194 if (!matches.length) continue
195 const rates: Record<string, number> = {}
196 const text = plain(section.body)
197 if (rows?.[0]?.join('|') === 'Usage|Price')
198 for (const row of rows.slice(1)) {
199 const value = row[1] ?? ''
200 if (row[0] === 'Audio processed') {
201 const p = /^\$(\d+(?:\.\d+)?) per hour$/.exec(value)
202 if (!p) fail('unreadable audio price')
203 rates.audio_seconds = Number(p[1]) / 3600
204 } else if (
205 row[0] === 'Image segmentation' ||
206 row[0] === 'Video segmentation'
207 ) {
208 const p = /^\$(\d+(?:\.\d+)?) per ([\d,]+) (images|frames)$/.exec(
209 value,
210 )
211 if (!p) fail('unreadable segmentation price')
212 rates[p[3] === 'images' ? 'segmented_images' : 'video_frames'] =
213 Number(p[1]) / Number(p[2]?.replace(/,/g, ''))
214 } else fail('unknown priced usage')
215 }
216 else if (section.name.includes('Image generation')) {
217 const p = /flat \$(\d+(?:\.\d+)?) per generated image/.exec(text)
218 if (!p) fail('unreadable image price')
219 rates.generated_images = Number(p[1])
220 } else continue
221 const card = compileTokenCard(rates, [], source)
222 if (!card) fail('uncompilable unit pricing')
223 for (const model of matches) cards.set(model.rawId, card)
224 }
225 }
226 if (!cards.size) fail('pricing parsed no rates')
227 return cards
228}
229
230// A mechanical translation of Meta's own schema tables. Unknown types throw.
231type Schema = Record<string, unknown>
232const nameKey = (s: string) => s.replace(/[^a-z0-9]/gi, '').toLowerCase()
233export function parseMetaSchemas(html: string): Record<string, Schema> {
234 const blocks = sections(html, 3)
235 const names = new Map(blocks.map((b) => [nameKey(b.name), b.id]))
236 const out: Record<string, Schema> = {}
237 const typeOf = (text: string): Schema => {
238 if (text === '') return { 'x-source-type': null }
239 const union = text.split(/\s*\|\s*/)
240 if (union.length > 1) return { anyOf: union.map(typeOf) }
241 if (text.startsWith('array of '))
242 return { type: 'array', items: typeOf(text.slice(9)) }
243 if (text.startsWith('enum (')) {
244 const values = [...text.matchAll(/'([^']*)'/g)].map((m) => m[1])
245 if (!values.length) fail('unreadable enum')
246 return { type: 'string', enum: values }
247 }
248 const primitive =
249 /^(string|integer|number|boolean|object|null)(?: \((uri|unixtime|binary|int64|int32)\))?$/.exec(
250 text,
251 )
252 if (primitive)
253 return {
254 type: primitive[1],
255 ...(primitive[2] && primitive[2] !== 'unixtime'
256 ? { format: primitive[2] }
257 : {}),
258 }
259 const id = names.get(nameKey(text))
260 if (!id) fail(`unknown schema type ${text}`)
261 return { $ref: `#/components/schemas/${id}` }
262 }
263 for (const block of blocks) {
264 const rows = tables(block.body)[0]
265 if (rows?.[0]?.join('|') === 'Field|Type|Required|Description') {
266 const schema: Schema = { type: 'object', properties: {} }
267 const nodes = new Map<string, Schema>([['', schema]])
268 for (const row of rows.slice(1)) {
269 if (row.length !== 4 || !['Yes', 'No'].includes(row[2] ?? ''))
270 fail('schema field row changed')
271 const field = row[0] ?? ''
272 const pieces = field.split('.')
273 const leaf = pieces.pop()
274 const parentPath = pieces.join('.')
275 let parent = nodes.get(parentPath)
276 if (!parent || !leaf) fail(`unresolved nested field ${field}`)
277 // A nullable object has its object branch in anyOf.
278 if (Array.isArray(parent.anyOf)) {
279 parent = (parent.anyOf as Array<Schema>).find(
280 (s) => s.type === 'object',
281 )
282 if (!parent) fail(`non-object parent ${field}`)
283 }
284 if (parent.type === 'array') parent = parent.items as Schema
285 if (parent.type !== 'object') fail(`non-object field parent ${field}`)
286 const node = typeOf(row[1] ?? '')
287 const description = row[3] ?? ''
288 node.description = description
289 for (const m of description.matchAll(
290 /\b(minimum|maximum|minItems|maxItems|minLength|maxLength): (-?\d+(?:\.\d+)?)/g,
291 ))
292 node[m[1] ?? ''] = Number(m[2])
293 const def = description.match(
294 /\bdefault: (true|false|-?\d+(?:\.\d+)?)/,
295 )?.[1]
296 if (def !== undefined)
297 node.default =
298 def === 'true' ? true : def === 'false' ? false : Number(def)
299 const properties = (parent.properties ??= {}) as Record<string, Schema>
300 properties[leaf.replace(/\[\]$/, '')] = node
301 if (row[2] === 'Yes') {
302 const required = (parent.required ??= []) as Array<string>
303 required.push(leaf.replace(/\[\]$/, ''))
304 }
305 nodes.set(field, node)
306 if (node.type === 'array') nodes.set(`${field}[]`, node)
307 if (leaf.endsWith('[]')) nodes.set(field.replace(/\[\]$/, ''), node)
308 }
309 out[block.id] = schema
310 } else {
311 const alias = [...block.body.matchAll(/<p\b[^>]*>([\s\S]*?)<\/p>/g)]
312 .map((p) => plain(p[1] ?? ''))
313 .find((p) => p.startsWith('Type: '))
314 if (!alias) fail(`schema ${block.name} has no table or type`)
315 out[block.id] = typeOf(alias.slice(6))
316 }
317 }
318 if (!Object.keys(out).length) fail('no native schema definitions')
319 return out
320}
321export function metaOperation(
322 html: string,
323 schemas: Record<string, Schema>,
324): { path: string; operation: Schema } {
325 const source = article(html)
326 const text = plain(source)
327 const endpoint = text.match(/\bPOST (\/[^ ]+)/)?.[1]
328 if (!endpoint) fail('missing native POST endpoint')
329 const request = source
330 .split('id="request-body"')[1]
331 ?.split('id="response"')[0]
332 const response = source.split('id="response"')[1]
333 const content = (block: string | undefined): Record<string, unknown> => {
334 if (!block) fail('missing native content block')
335 const contentHeads = [...block.matchAll(/<h4\b[^>]*>[\s\S]*?<\/h4>/g)]
336 const out: Record<string, unknown> = {}
337 for (const [i, heading] of contentHeads.entries()) {
338 const media = plain(heading[0]).match(/^Content Type: ([\w/+.-]+)$/)?.[1]
339 if (!media) fail('unreadable native content type')
340 const body =
341 block
342 .slice(
343 heading.index + heading[0].length,
344 contentHeads[i + 1]?.index ?? block.length,
345 )
346 .split(/<h3\b/)[0] ?? ''
347 const id = body.match(/href="[^"#]*\/schemas#([^"]+)"/)?.[1]
348 let schema: Schema
349 if (id) {
350 if (!schemas[id]) fail('missing native schema reference')
351 schema = { $ref: `#/components/schemas/${id}` }
352 } else {
353 // ASR publishes an inline `object`, without a field/type table. Keep
354 // that exact declared shape unconstrained; do not invent multipart fields.
355 const inline = [...body.matchAll(/<p\b[^>]*>([\s\S]*?)<\/p>/g)]
356 .map((p) => plain(p[1] ?? ''))
357 .find((p) => p === 'object')
358 if (!inline) fail('missing native schema reference')
359 schema = { type: 'object', 'x-source-fields': null }
360 }
361 out[media] = { schema }
362 }
363 if (!Object.keys(out).length) fail('missing native content types')
364 return out
365 }
366 if (!plain(response ?? '').includes('HTTP 200'))
367 fail('missing native successful response')
368 return {
369 path: `/v1${endpoint}`,
370 operation: {
371 requestBody: { required: true, content: content(request) },
372 responses: {
373 '200': {
374 description: 'Native documented response',
375 content: content(response),
376 },
377 },
378 },
379 }
380}