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