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