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

cloudflare-workers-ai.ts

548 lines17.2 KB

1/**
2 * Cloudflare Workers AI — model cards from the public models page.
3 * `data-model-id` is the caller id. A per-1M-token price is stored only
4 * when that card names both input and output. Other units stay null.
5 *
6 * Each text-generation page is built from one catalog file in Cloudflare's
7 * docs repository. That file states the model's properties (function
8 * calling, vision, reasoning efforts) and its own request and response
9 * schema; both are read from it. The schemas share a template, so a field
10 * in one is not proof the model honours it: capability flags come from the
11 * properties only, never from the schema walk. `enable_thinking` is not
12 * template: only reasoning models' schemas carry it, each with its own
13 * enum, so with no effort list it is read as the model's on/off switch.
14 */
15import { compileTokenCard } from '@modelschemas/rate-card'
16import type { RateCard } from '@modelschemas/rate-card'
17​
18import type { Activity } from '#/db/schema.ts'
19​
20import {
21 docsReport,
22 docsRun,
23 mapConcurrent,
24 tryDocs,
25 unavailable,
26} from '../model-facts.ts'
27import { REASONING_SOURCE_SILENT } from '../reasoning-config.ts'
28import { SHARED_EFFORT_LEVELS } from '../request-map.ts'
29import type {
30 ChatRequestMap,
31 EffortLevelMap,
32 ThinkingRequest,
33} from '../request-map.ts'
34import { fetchText, sha256Text } from '../types.ts'
35import { bearerConnect } from '../connect.ts'
36import type {
37 FactSource,
38 ListModelsResult,
39 ModelFact,
40 ModelInfo,
41 ModelReasoning,
42 OpenApiDocument,
43 ProviderConfig,
44 ProviderSecrets,
45 SpecFetchResult,
46 SpecSource,
47} from '../types.ts'
48​
49export const WORKERS_AI_MODELS_URL =
50 'https://developers.cloudflare.com/workers-ai/models/'
51​
52/** One `<page slug>.json` per model: the source of its docs page. */
53export const WORKERS_AI_CATALOG_URL =
54 'https://raw.githubusercontent.com/cloudflare/cloudflare-docs/production/src/content/workers-ai-models/'
55​
56const FETCH_TIMEOUT_MS = 20_000
57const CATALOG_CONCURRENCY = 8
58​
59const TASK_ACTIVITY: Record<string, Activity> = {
60 'Text Generation': 'chat',
61 'Text-to-Image': 'image',
62 'Text Embeddings': 'embeddings',
63 'Text-to-Speech': 'audio',
64 'Automatic Speech Recognition': 'audio',
66​
67function isRecord(value: unknown): value is Record<string, unknown> {
68 return typeof value === 'object' && value !== null && !Array.isArray(value)
70​
71function fetchPage(url: string): Promise<string> {
72 return fetchText(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) })
74​
75function attr(tag: string, name: string): string | null {
76 const match = tag.match(new RegExp(`\\b${name}="([^"]*)"`))
77 return match?.[1] ? match[1] : null
79​
80function dollarsPerMillion(text: string, label: string): number | null {
81 const match = text.match(
82 new RegExp(`${label} \\(per 1M tokens\\): \\$([0-9]+(?:\\.[0-9]+)?)`),
83 )
84 if (!match?.[1]) return null
85 const dollars = Number(match[1])
86 return Number.isFinite(dollars) && dollars > 0 ? dollars / 1_000_000 : null
88​
89/** The catalog file behind a card's `/workers-ai/models/<slug>/` page. */
90function catalogUrl(tag: string): string | null {
91 const slug = attr(tag, 'data-model-href')?.match(
92 /^\/workers-ai\/models\/([A-Za-z0-9][A-Za-z0-9._-]*)\/$/,
93 )?.[1]
94 return slug ? `${WORKERS_AI_CATALOG_URL}${slug}.json` : null
96​
97interface ListedModel {
98 model: ModelInfo
99 catalogUrl: string | null
101​
102export function parseWorkersAiModels(
103 html: string,
104 source: RateCard['source'],
105): Array<ListedModel> {
106 const models: Array<ListedModel> = []
107 const seen = new Set<string>()
108 for (const match of html.matchAll(
109 /<[^>]*?\bdata-model-id="([^"]+)"([\s\S]*?)>/g,
110 )) {
111 const rawId = match[1] ?? ''
112 const tag = match[0]
113 if (rawId.length === 0 || seen.has(rawId)) continue
114 seen.add(rawId)
115 const task = attr(tag, 'data-model-task')
116 const context = attr(tag, 'data-model-context')
117 const pricingText = attr(tag, 'data-model-pricing') ?? ''
118 const input = dollarsPerMillion(pricingText, 'Input')
119 const output = dollarsPerMillion(pricingText, 'Output')
120 const cache = dollarsPerMillion(pricingText, 'Cached input')
121 const rates =
122 input !== null && output !== null
123 ? {
124 input_tokens: input,
125 output_tokens: output,
126 ...(cache !== null ? { cache_read_tokens: cache } : {}),
127 }
128 : null
129 const contextWindow =
130 context !== null && /^[0-9]+$/.test(context) ? Number(context) : null
131 models.push({
132 model: {
133 rawId,
134 displayName: attr(tag, 'data-model-label'),
135 activity: task ? (TASK_ACTIVITY[task] ?? null) : null,
136 contextWindow,
137 pricing: rates ? compileTokenCard(rates, [], source) : null,
138 },
139 catalogUrl: catalogUrl(tag),
140 })
141 }
142 if (models.length === 0) {
143 throw new Error('cloudflare-workers-ai: models page listed no ids')
144 }
145 return models
147​
148async function fetchListing(): Promise<Array<ListedModel>> {
149 const html = await fetchPage(WORKERS_AI_MODELS_URL)
150 return parseWorkersAiModels(html, {
151 url: WORKERS_AI_MODELS_URL,
152 hash: await sha256Text(html),
153 extractedAt: new Date().toISOString(),
154 })
156​
157export interface CatalogModel {
158 /** `property_id` → value, as published. */
159 properties: Record<string, unknown>
160 input: Record<string, unknown> | null
161 output: Record<string, unknown> | null
163​
164/**
165 * One catalog file. Throws unless it is JSON for exactly `rawId` — an HTML
166 * error page or another model's file is never read as this model's facts.
167 */
168export function parseCatalogModel(
169 text: string,
170 rawId: string,
171 url: string,
172): CatalogModel {
173 const fail = (why: string) =>
174 new Error(`cloudflare-workers-ai: ${url} ${why}`)
175 let doc: unknown
176 try {
177 doc = JSON.parse(text)
178 } catch {
179 throw fail('is not JSON')
180 }
181 if (!isRecord(doc) || doc.name !== rawId) {
182 throw fail(`is not the catalog file for ${rawId}`)
183 }
184 if (!Array.isArray(doc.properties)) throw fail('has no properties list')
185 const properties: Record<string, unknown> = {}
186 for (const entry of doc.properties as Array<unknown>) {
187 if (
188 !isRecord(entry) ||
189 typeof entry.property_id !== 'string' ||
190 !('value' in entry)
191 ) {
192 throw fail('has a malformed property')
193 }
194 properties[entry.property_id] = entry.value
195 }
196 const schema = isRecord(doc.schema) ? doc.schema : {}
197 return {
198 properties,
199 input: isRecord(schema.input) ? schema.input : null,
200 output: isRecord(schema.output) ? schema.output : null,
201 }
203​
204/**
205 * Field names of the request bodies that take `messages`. The same file
206 * also describes prompt, batch, and Responses bodies; their fields are not
207 * chat fields.
208 */
209export function chatBodyFields(schema: unknown): Array<string> {
210 const fields = new Set<string>()
211 const visit = (node: unknown) => {
212 if (!isRecord(node)) return
213 if (isRecord(node.properties) && 'messages' in node.properties) {
214 for (const name of Object.keys(node.properties)) fields.add(name)
215 }
216 for (const variants of [node.oneOf, node.anyOf]) {
217 if (Array.isArray(variants)) variants.forEach(visit)
218 }
219 }
220 visit(schema)
221 return [...fields]
223​
224export type ThinkingSwitch = 'on-off' | 'on-only'
225​
226/**
227 * `chat_template_kwargs.enable_thinking` of the request bodies that take
228 * `messages`: `on-off` for a plain boolean, `on-only` when its enum is
229 * `[true]`. Null when no body has it, when the bodies disagree, or when it
230 * has another shape.
231 */
232export function thinkingSwitch(schema: unknown): ThinkingSwitch | null {
233 const found = new Set<ThinkingSwitch | null>()
234 const visit = (node: unknown) => {
235 if (!isRecord(node)) return
236 const kwargs =
237 isRecord(node.properties) && 'messages' in node.properties
238 ? node.properties.chat_template_kwargs
239 : undefined
240 const field =
241 isRecord(kwargs) && isRecord(kwargs.properties)
242 ? kwargs.properties.enable_thinking
243 : undefined
244 if (field !== undefined) {
245 const boolean = isRecord(field) && field.type === 'boolean'
246 found.add(
247 !boolean
248 ? null
249 : field.enum === undefined
250 ? 'on-off'
251 : JSON.stringify(field.enum) === '[true]'
252 ? 'on-only'
253 : null,
254 )
255 }
256 for (const variants of [node.oneOf, node.anyOf]) {
257 if (Array.isArray(variants)) variants.forEach(visit)
258 }
259 }
260 visit(schema)
261 const [only = null] = [...found]
262 return found.size === 1 ? only : null
264​
265/** What `listModels` keeps of a catalog file (six hours in KV). */
266export interface CatalogDoc {
267 properties: Record<string, unknown>
268 chatFields: Array<string>
269 /** Absent on an entry cached before this was read: no switch is claimed. */
270 thinkingSwitch?: ThinkingSwitch | null
271 hasRequestSchema: boolean
272 hash: string
274​
275function runPath(rawId: string): string {
276 return `/accounts/{account_id}/ai/run/${rawId}`
278​
279function thinkingRequest(efforts: Array<string>): ThinkingRequest | null {
280 // `on` means "effort high"; a model without that level has no such body.
281 if (!efforts.includes('high')) return null
282 const off = efforts.includes('none') ? 'none' : null
283 const levels = Object.fromEntries(
284 SHARED_EFFORT_LEVELS.map((level) => [
285 level,
286 level === 'off' ? off : efforts.includes(level) ? level : null,
287 ]),
288 ) as EffortLevelMap
289 return {
290 on: { reasoning_effort: 'high' },
291 off: off ? { reasoning_effort: off } : null,
292 levels,
293 }
295​
296function requestMap(
297 fields: Array<string>,
298 efforts: Array<string> | null,
299): ChatRequestMap | null {
300 const maxTokensField = fields.includes('max_completion_tokens')
301 ? 'max_completion_tokens'
302 : fields.includes('max_tokens')
303 ? 'max_tokens'
304 : null
305 const takesEffort = fields.includes('reasoning_effort')
306 if (maxTokensField === null && !takesEffort) return null
307 return {
308 thinking: takesEffort && efforts ? thinkingRequest(efforts) : null,
309 maxTokensField,
310 developerRole: null,
311 replayReasoningContent: null,
312 store: null,
313 strictTools: null,
314 sessionAffinity: null,
315 cacheControl: null,
316 toolStream: null,
317 reasoningEffort: takesEffort ? true : null,
318 }
320​
321/**
322 * Chat facts from one catalog file. A property whose shape changed throws:
323 * nothing is stored from a file this cannot read.
324 */
325export function catalogFacts(
326 doc: CatalogDoc,
327 rawId: string,
328 url: string,
329): Partial<ModelInfo> {
330 const fail = (id: string) =>
331 new Error(`cloudflare-workers-ai: ${url} property ${id} changed shape`)
332 const flag = (id: string): boolean => {
333 const value = doc.properties[id]
334 if (value === undefined || value === 'false') return false
335 if (value === 'true') return true
336 throw fail(id)
337 }
338 const source = (path: string): FactSource => ({
339 derivation: 'listing',
340 sourceUrl: url,
341 sourceHash: doc.hash,
342 path,
343 })
344​
345 const tools = flag('function_calling')
346 const reasons = flag('reasoning')
347 const vision = flag('vision')
348​
349 // `supported_efforts` is an effort mode. Without it the property only
350 // says whether reasoning can be turned off (`mandatory`).
351 let efforts: Array<string> | null = null
352 let mandatory = false
353 const effort = doc.properties.reasoning_effort
354 if (effort !== undefined) {
355 if (!isRecord(effort)) throw fail('reasoning_effort')
356 const listed = effort.supported_efforts
357 if (listed != null) {
358 if (
359 !Array.isArray(listed) ||
360 listed.length === 0 ||
361 !listed.every((item) => typeof item === 'string') ||
362 typeof effort.mandatory !== 'boolean'
363 ) {
364 throw fail('reasoning_effort')
365 }
366 efforts = listed
367 mandatory = effort.mandatory
368 }
369 }
370​
371 // No effort list: `enable_thinking` in the model's own request schema is
372 // the whole control. The catalog's `mandatory` is the statement, and wins
373 // over the schema. With none, a plain boolean field offers "off"; a field
374 // that only takes `true` states nothing by itself. A `reasoning` flag
375 // with no request field stores no object.
376 let toggle: ModelReasoning | null = null
377 if (efforts === null && reasons && doc.thinkingSwitch) {
378 const stated = isRecord(effort) ? effort.mandatory : undefined
379 if (stated !== undefined && typeof stated !== 'boolean') {
380 throw fail('reasoning_effort')
381 }
382 if (stated === true) toggle = { mode: 'toggle', mandatory: true }
383 else if (doc.thinkingSwitch === 'on-off') {
384 toggle = { mode: 'toggle', mandatory: false }
385 }
386 }
387​
388 const map = requestMap(doc.chatFields, efforts)
389 return {
390 modalities: {
391 input: vision ? ['text', 'image'] : ['text'],
392 output: ['text'],
393 },
394 capabilities: [
395 ...(tools ? ['tools'] : []),
396 ...(reasons ? ['reasoning'] : []),
397 ],
398 exactCapabilities: true,
399 ...(efforts
400 ? { reasoning: { mode: 'effort', mandatory, efforts } }
401 : toggle
402 ? { reasoning: toggle }
403 : {}),
404 ...(map ? { requestMap: map } : {}),
405 ...(doc.hasRequestSchema
406 ? { schemaEndpointId: runPath(rawId).slice(1) }
407 : {}),
408 factSources: {
409 modalities: source('properties.vision'),
410 capabilities: {
411 ...(tools ? { tools: source('properties.function_calling') } : {}),
412 ...(reasons ? { reasoning: source('properties.reasoning') } : {}),
413 },
414 ...(efforts
415 ? { reasoning: source('properties.reasoning_effort') }
416 : toggle
417 ? { reasoning: source('chat_template_kwargs.enable_thinking') }
418 : reasons
419 ? { reasoning: source(REASONING_SOURCE_SILENT) }
420 : {}),
421 },
422 }
424​
425/** Every stored fact `catalogFacts` supplies. */
426const CATALOG_FACTS: Array<ModelFact> = [
427 'modalities',
428 'capabilities',
429 'reasoning',
430 'requestMap',
431 'schemaEndpointId',
433​
434/** A chat card must link its page: the catalog file is named after it. */
435function requireCatalogUrl(listed: ListedModel): string {
436 if (listed.catalogUrl) return listed.catalogUrl
437 throw new Error(
438 `cloudflare-workers-ai: ${listed.model.rawId} links no model page`,
439 )
441​
442async function listModels(
443 _env: ProviderSecrets,
444 kv?: KVNamespace,
445): Promise<ListModelsResult> {
446 const listed = await fetchListing()
447 // One unreadable file is that model's alone: its row keeps the stored
448 // catalog facts and the next poll retries. The page's prices still land.
449 const docs = docsRun()
450 const models = await mapConcurrent(
451 listed,
452 CATALOG_CONCURRENCY,
453 async (card): Promise<ModelInfo> => {
454 const { model } = card
455 if (model.activity !== 'chat') return model
456 const url = requireCatalogUrl(card)
457 const facts = await tryDocs(docs, url, async (cached) => {
458 const doc = await cached(kv, url, async (): Promise<CatalogDoc> => {
459 const text = await fetchPage(url)
460 const parsed = parseCatalogModel(text, model.rawId, url)
461 return {
462 properties: parsed.properties,
463 chatFields: chatBodyFields(parsed.input),
464 thinkingSwitch: thinkingSwitch(parsed.input),
465 hasRequestSchema: parsed.input !== null,
466 hash: await sha256Text(text),
467 }
468 })
469 return catalogFacts(doc, model.rawId, url)
470 })
471 return { ...model, ...(facts ?? unavailable(...CATALOG_FACTS)) }
472 },
473 )
474 return { models, docsFailures: docsReport(docs) }
476​
477/** One document per text-generation model that publishes a request schema. */
478async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
479 const chat = (await fetchListing()).filter(
480 (card) => card.model.activity === 'chat',
481 )
482 const specs: Array<OpenApiDocument> = []
483 const sources: Array<SpecSource> = []
484 const fetched = await mapConcurrent(
485 chat,
486 CATALOG_CONCURRENCY,
487 async (card) => {
488 const { model } = card
489 const url = requireCatalogUrl(card)
490 const text = await fetchPage(url)
491 return {
492 model,
493 url,
494 hash: await sha256Text(text),
495 ...parseCatalogModel(text, model.rawId, url),
496 }
497 },
498 )
499 for (const { model, url, hash, input, output } of fetched) {
500 if (input === null) continue
501 specs.push({
502 openapi: '3.1.0',
503 info: { title: model.rawId, version: hash },
504 paths: {
505 [runPath(model.rawId)]: {
506 post: {
507 summary: `Run ${model.rawId}`,
508 requestBody: { content: { 'application/json': { schema: input } } },
509 responses: output
510 ? {
511 '200': {
512 content: { 'application/json': { schema: output } },
513 },
514 }
515 : {},
516 },
517 },
518 },
519 })
520 sources.push({ url, hash })
521 }
522 if (specs.length === 0) {
523 throw new Error(
524 'cloudflare-workers-ai: no text-generation model published a request schema',
525 )
526 }
527 return { specs, sources, outputStrategy: 'post-200' }
529​
530export const provider: ProviderConfig = {
531 id: 'cloudflare-workers-ai',
532 modelNamespaces: ['workers-ai'],
533 displayName: 'Cloudflare Workers AI',
534 specSourceUrl: WORKERS_AI_MODELS_URL,
535 modelsEndpoint: WORKERS_AI_MODELS_URL,
536 // The per-model schemas are Cloudflare's own, re-fetched every sync.
537 defaultDerivation: 'upstream-spec',
538 connect: bearerConnect(
539 'https://api.cloudflare.com/client/v4',
540 'Account-scoped: {account_id} is a path parameter on every route.',
541 ),
542 // A model listed today has no synced schema until the next daily sync.
543 bindSyncedRoutesOnly: true,
544 fetchSpec,
545 listModels,
546 classify: (path) =>
547 path.startsWith('/accounts/{account_id}/ai/run/') ? 'chat' : null,