Open History to see the last commit
1/** The current Meta Model API: live provider-owned tables and schema references. */
2import { cachedDocs } from '../model-facts.ts'
3import { tagDocsFacts } from '../fact-sources.ts'
4import { bearerConnect } from '../connect.ts'
5import { fetchText, sha256Text } from '../types.ts'
6import type { ProviderConfig, ModelInfo } from '../types.ts'
7import {
8 article,
9 plain,
10 tables,
11 list,
12 parseMetaModels,
13 parseMetaPricing,
14 parseMetaSchemas,
15 metaOperation,
16 META_MODELS,
17 META_PRICING,
18 META_PROTOCOLS,
19 META_REASONING,
20 META_REFERENCE,
21} from '../meta-docs.ts'
22
23const REFERENCES = [
24 { resource: 'chat-completions', operation: 'create-chat-completion' },
25 { resource: 'responses', operation: 'create-response' },
26 { resource: 'messages', operation: 'create-message' },
27 { resource: 'images', operation: 'create-image' },
28 { resource: 'images', operation: 'edit-image' },
29 { resource: 'voice', operation: 'transcribe' },
30]
31async function load(url: string, kv?: KVNamespace) {
32 return cachedDocs(kv, `meta:docs:${url}`, async () => {
33 const html = await fetchText(url)
34 return { html, hash: await sha256Text(html) }
35 })
36}
37export const provider: ProviderConfig = {
38 id: 'meta',
39 displayName: 'Meta',
40 specSourceUrl: META_REFERENCE,
41 modelsEndpoint: META_MODELS,
42 defaultDerivation: 'docs-derived',
43 bindSyncedRoutesOnly: true,
44 connect: bearerConnect('https://api.meta.ai'),
45 async listModels(_env, kv) {
46 const [catalog, prices, reasoning] = await Promise.all([
47 load(META_MODELS, kv),
48 load(META_PRICING, kv),
49 load(META_REASONING, kv),
50 ])
51 const models = parseMetaModels(catalog.html)
52 const source = {
53 url: META_PRICING,
54 hash: prices.hash,
55 extractedAt: new Date().toISOString(),
56 }
57 const cards = parseMetaPricing(prices.html, models, source)
58 const levels = tables(article(reasoning.html)).find(
59 (rows) => rows[0]?.join('|') === 'Value|Behavior',
60 )
61 if (!levels) throw new Error('meta: missing reasoning effort table')
62 const text = plain(article(reasoning.html))
63 // '"none" disables reasoning entirely, which Muse Wonder and Muse Spark
64 // do not support.' names the families whose reasoning cannot be off.
65 const applies =
66 /"none" disables reasoning entirely, which (.+?) (?:do|does) not support\./.exec(
67 text,
68 )?.[1]
69 if (!applies) throw new Error('meta: unreadable reasoning applicability')
70 const families = list(applies)
71 if (
72 levels
73 .slice(1)
74 .some(
75 (row) =>
76 row.length !== 2 || !/^"[a-z]+"$/.test(row[0] ?? '') || !row[1],
77 )
78 ) {
79 throw new Error('meta: unreadable reasoning effort row')
80 }
81 const known = new Set(models.map((model) => model.rawId))
82 const named = [
83 ...known,
84 ...models.map(
85 (model) =>
86 (model.providerMetadata as { family?: string }).family ?? '\u0000',
87 ),
88 ]
89 const unreadable = (): never => {
90 throw new Error('meta: unreadable reasoning effort restriction')
91 }
92 const ids = (clause?: string) => {
93 if (clause === undefined) return undefined
94 const out = list(clause)
95 if (out.some((id) => !known.has(id))) unreadable()
96 return out
97 }
98 const allows = (behavior: string, rawId: string) => {
99 if (behavior.includes('Not supported')) return false
100 const only = ids(
101 /(?:^|\. )Supported by (.+?)(?:;|\.(?: |$))/.exec(behavior)?.[1],
102 )
103 const except = ids(
104 /\bnot available with (.+?)(?:;|\.(?: |$))/.exec(behavior)?.[1],
105 )
106 if (
107 !only &&
108 !except &&
109 (/\b(?:only|not available|supported)\b/i.test(behavior) ||
110 named.some((name) => behavior.includes(name)))
111 )
112 unreadable()
113 return (!only || only.includes(rawId)) && !except?.includes(rawId)
114 }
115 return {
116 models: models.map((model): ModelInfo => {
117 const reasons = families.includes(
118 (
119 (model.providerMetadata as { family?: string }).family ?? ''
120 ).toLowerCase(),
121 )
122 const efforts = reasons
123 ? levels
124 .slice(1)
125 .filter((row) => allows(row[1] ?? '', model.rawId))
126 .map((row) => (row[0] ?? '').replace(/^"|"$/g, ''))
127 : []
128 if (reasons && !efforts.length)
129 throw new Error('meta: no supported reasoning efforts')
130 const facts = {
131 ...model,
132 pricing: cards.get(model.rawId) ?? null,
133 reasoning: reasons
134 ? { mode: 'effort' as const, mandatory: true, efforts }
135 : null,
136 }
137 return {
138 ...facts,
139 absent: facts.pricing ? {} : { pricing: 'cleared' },
140 factSources: {
141 ...tagDocsFacts(
142 {
143 modalities: model.modalities,
144 contextWindow: model.contextWindow,
145 capabilities: model.capabilities,
146 },
147 META_MODELS,
148 catalog.hash,
149 ),
150 ...(facts.pricing
151 ? tagDocsFacts(
152 { pricing: facts.pricing },
153 META_PRICING,
154 prices.hash,
155 )
156 : {}),
157 ...(facts.reasoning
158 ? tagDocsFacts(
159 { reasoning: facts.reasoning },
160 META_REASONING,
161 reasoning.hash,
162 )
163 : {}),
164 },
165 }
166 }),
167 }
168 },
169 async fetchSpec(_env) {
170 const [protocols, catalog] = await Promise.all([
171 load(META_PROTOCOLS),
172 load(META_MODELS),
173 ])
174 const routes =
175 tables(article(protocols.html))[0]
176 ?.slice(1)
177 .map((row) => row[1]?.match(/^POST (\/v1\/[^ ]+)$/)?.[1]) ?? []
178 if (!routes.length || routes.some((path) => !path))
179 throw new Error('meta: unreadable native protocol endpoint table')
180 const docs = await Promise.all(
181 REFERENCES.map(async (ref) => {
182 const schemaUrl = `${META_REFERENCE}${ref.resource}/schemas`
183 const operationUrl = `${META_REFERENCE}${ref.resource}/${ref.operation}`
184 const [schema, operation] = await Promise.all([
185 load(schemaUrl),
186 load(operationUrl),
187 ])
188 const schemas = parseMetaSchemas(schema.html)
189 const parsed = metaOperation(operation.html, schemas)
190 if (
191 !routes.includes(parsed.path) &&
192 !plain(article(catalog.html)).includes(parsed.path)
193 )
194 throw new Error('meta: operation absent from native protocol table')
195 return {
196 spec: {
197 openapi: '3.1.0',
198 info: { title: 'Meta native Model API', version: 'source-derived' },
199 paths: { [parsed.path]: { post: parsed.operation } },
200 components: { schemas },
201 },
202 // Each assembled document has one index-aligned provenance record.
203 // Its revision covers schema types and native operation/protocol links.
204 source: {
205 url: schemaUrl,
206 hash: await sha256Text(
207 `${schema.html}\n${operation.html}\n${protocols.html}`,
208 ),
209 },
210 }
211 }),
212 )
213 if (
214 routes.some(
215 (path) =>
216 !docs.some(
217 (doc) =>
218 path !== undefined &&
219 Object.prototype.hasOwnProperty.call(doc.spec.paths, path),
220 ),
221 )
222 ) {
223 throw new Error(
224 'meta: native protocol endpoint has no parsed schema resource',
225 )
226 }
227 return {
228 specs: docs.map((d) => d.spec),
229 sources: docs.map((d) => d.source),
230 outputStrategy: 'post-200',
231 }
232 },
233 classify: (path) =>
234 ['/v1/chat/completions', '/v1/responses', '/v1/messages'].includes(path)
235 ? 'chat'
236 : ['/v1/images/generations', '/v1/images/edits'].includes(path)
237 ? 'image'
238 : path === '/v1/asr/transcribe'
239 ? 'audio'
240 : null,
241 generationEndpointId: ({ activity }) =>
242 activity === 'chat'
243 ? 'v1/chat/completions'
244 : activity === 'image'
245 ? 'v1/images/generations'
246 : activity === 'audio'
247 ? 'v1/asr/transcribe'
248 : null,
249}