Open History to see the last commit
1/**
2 * FAL — one OpenAPI spec per model from the FAL models API
3 * (`expand=openapi-3.0`; NB the param is plain `expand`, not `expand[]` —
4 * the bracketed form is silently ignored). Requires FAL_KEY; skipped with a
5 * recorded warning when absent. Output schemas use the `sibling-get`
6 * strategy (the POST returns a queue ack).
7 *
8 * Activity comes from the model's `<source>-to-<target>` category, not the
9 * path, so fetchSpec annotates every operation with FAL_ACTIVITY_MARKER and
10 * classify reads it back.
11 *
12 * Listed models with a classifiable activity but no OpenAPI POST are probed
13 * for a WMA AsyncAPI contract (llms.txt `AsyncAPI Contract` link, then
14 * `/api/apps/{app}/asyncapi.json`). Misses do not fail the sync. Classic
15 * realtime apps that reuse HTTP OpenAPI over WebSocket are not AsyncAPI.
16 */
17import type { Activity } from '#/db/schema.ts'
18import { activities } from '#/db/schema.ts'
19import { extractAsyncApiSchemas } from '#/server/ingest/asyncapi.ts'
20import { compileFalTokenCard } from '#/server/ingest/fal-token-rate.ts'
21import { contentHash } from '#/server/kv.ts'
22import { falChatFacts } from './fal-chat-facts.ts'
23import {
24 docsReport,
25 docsRun,
26 mapConcurrent,
27 markdownSection,
28 tryDocs,
29 unavailable,
30} from './model-facts.ts'
31import { isoToEpochSeconds } from './release-dates.ts'
32import { sha256Text, skippedResult } from './types.ts'
33import type {
34 BundledEndpoint,
35 FactSource,
36 ListModelsResult,
37 ModelFactSources,
38 ModelInfo,
39 OpenApiDocument,
40 OpenApiOperation,
41 ProviderConfig,
42 ProviderSecrets,
43 SpecFetchResult,
44 SpecSource,
45} from './types.ts'
46
47const FAL_MODELS_URL = 'https://api.fal.ai/v1/models'
48
49export const FAL_ACTIVITY_MARKER = 'x-modelschemas-fal-activity'
50
51interface FalApiModel {
52 endpoint_id: string
53 openapi?: OpenApiDocument
54 metadata: {
55 display_name?: string
56 category: string
57 description?: string
58 status?: 'active' | 'inactive' | 'deprecated'
59 /** Listing/release date, ISO 8601. */
60 date?: string
61 [key: string]: unknown
62 }
63}
64
65interface FalApiResponse {
66 models: Array<FalApiModel>
67 has_more: boolean
68 next_cursor: string | null
69}
70
71/**
72 * Full-category overrides, applied before the target-modality mapping.
73 * Transcription belongs in `audio` regardless of its `text` target;
74 * `training` is fine-tuning (platform — dropped), `workflow`/`unknown` are
75 * not generation endpoints.
76 */
77const FAL_CATEGORY_OVERRIDES: Record<string, Activity | null> = {
78 'speech-to-text': 'audio',
79 'audio-to-text': 'audio',
80 training: null,
81 workflow: null,
82 unknown: null,
83}
84
85/**
86 * Target modality (from `<source>-to-<target>` category names) → activity.
87 * Speech and music land in `audio`; image/video/audio-to-text (captioning,
88 * visual QA) land in `chat` like other text generation. Target modalities
89 * outside the shared taxonomy (`3d`, `json`, `vision`, …) have no activity
90 * in our six-value enum and classify to null (PR #622 kept them as their own
91 * sub-groups; our catalog drops them until the taxonomy grows).
92 */
93const FAL_MODALITY_ACTIVITIES: Record<string, Activity> = {
94 image: 'image',
95 video: 'video',
96 audio: 'audio',
97 speech: 'audio',
98 music: 'audio',
99 text: 'chat',
100 llm: 'chat',
101}
102
103export function falCategoryActivity(category: string): Activity | null {
104 const override = FAL_CATEGORY_OVERRIDES[category]
105 if (override !== undefined) return override
106 const modality = category.replace(/^.+-to-/, '')
107 return FAL_MODALITY_ACTIVITIES[modality] ?? null
108}
109
110function classify(_path: string, op: OpenApiOperation): Activity | null {
111 const marker = op[FAL_ACTIVITY_MARKER]
112 if (
113 typeof marker === 'string' &&
114 (activities as ReadonlyArray<string>).includes(marker)
115 ) {
116 return marker as Activity
117 }
118 return null
119}
120
121/**
122 * Statuses worth retrying: rate limiting and transient upstream/gateway
123 * failures. Anything else (401, 403, 404, …) is a real config problem and
124 * fails fast.
125 */
126const RETRYABLE_STATUSES = new Set([408, 429, 500, 502, 503, 504])
127
128const MAX_BACKOFF_MS = 15_000
129
130/** A page that has not answered by now is retried like a dropped connection. */
131const FETCH_TIMEOUT_MS = 60_000
132
133/** Most `endpoint_id` filters the models API takes in one request. */
134const ENDPOINT_FILTER_MAX = 50
135
136/** Non-retryable upstream failure — thrown through the retry loop as-is. */
137class FalFetchError extends Error {}
138
139/**
140 * The paginated crawl is ~30 requests per pass and runs from both cron
141 * tiers, so transient 429s/5xxs and dropped connections are routine — each
142 * page gets exponential backoff (honoring `Retry-After` when sent) rather
143 * than one throw sinking the whole sync and flagging the provider degraded.
144 */
145export async function fetchPageWithRetry(
146 url: string,
147 apiKey: string,
148 attempts = 5,
149): Promise<FalApiResponse> {
150 let lastFailure = 'unknown failure'
151 for (let attempt = 1; attempt <= attempts; attempt++) {
152 let retryAfterMs: number | null = null
153 try {
154 const response = await fetch(url, {
155 headers: { Authorization: `Key ${apiKey}` },
156 signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
157 })
158 if (response.ok) return (await response.json()) as FalApiResponse
159 lastFailure = `${String(response.status)} ${response.statusText}`
160 if (!RETRYABLE_STATUSES.has(response.status)) {
161 throw new FalFetchError(`fal models fetch failed: ${lastFailure}`)
162 }
163 const retryAfter = Number(response.headers.get('retry-after'))
164 if (Number.isFinite(retryAfter) && retryAfter > 0) {
165 retryAfterMs = retryAfter * 1000
166 }
167 } catch (error) {
168 if (error instanceof FalFetchError) throw error
169 // Network-level failure (or a truncated body mid-json()) — retryable.
170 lastFailure = error instanceof Error ? error.message : String(error)
171 }
172 if (attempt < attempts) {
173 const backoff = Math.min(1000 * Math.pow(2, attempt), MAX_BACKOFF_MS)
174 const waitMs = Math.min(retryAfterMs ?? backoff, MAX_BACKOFF_MS)
175 await new Promise((resolve) => setTimeout(resolve, waitMs))
176 }
177 }
178 throw new Error(
179 `fal models fetch failed after ${String(attempts)} attempts: ${lastFailure}`,
180 )
181}
182
183async function fetchFalModels(
184 apiKey: string,
185 expandOpenApi: boolean,
186 endpointIds: Array<string> = [],
187): Promise<Array<FalApiModel>> {
188 const allModels: Array<FalApiModel> = []
189 let cursor: string | null = null
190 do {
191 const params = new URLSearchParams({ status: 'active' })
192 if (expandOpenApi) params.set('expand', 'openapi-3.0')
193 for (const id of endpointIds) params.append('endpoint_id', id)
194 if (cursor) params.set('cursor', cursor)
195 const data = await fetchPageWithRetry(
196 `${FAL_MODELS_URL}?${params.toString()}`,
197 apiKey,
198 )
199 allModels.push(...data.models)
200 cursor = data.has_more ? data.next_cursor : null
201 } while (cursor)
202 return allModels
203}
204
205function annotateOperations(spec: OpenApiDocument, activity: Activity): void {
206 for (const operations of Object.values(spec.paths ?? {})) {
207 for (const op of Object.values(operations)) {
208 op[FAL_ACTIVITY_MARKER] = activity
209 }
210 }
211}
212
213function hasPostOperation(spec: OpenApiDocument): boolean {
214 for (const operations of Object.values(spec.paths ?? {})) {
215 if (operations.post) return true
216 }
217 return false
218}
219
220/** `minimax/h3-max/director` → `fal-ai/minimax-h3-max-director`. */
221export function falAppSlug(rawId: string): string {
222 return `fal-ai/${rawId.replaceAll('/', '-')}`
223}
224
225export function falAsyncApiUrl(rawId: string): string {
226 return `https://fal.ai/api/apps/${falAppSlug(rawId)}/asyncapi.json`
227}
228
229export function falLlmsTxtUrl(rawId: string): string {
230 return `https://fal.ai/models/${rawId}/llms.txt`
231}
232
233const ASYNCAPI_CONTRACT_LINK = /\[AsyncAPI Contract\]\((https?:\/\/[^)\s]+)\)/i
234
235export function parseAsyncApiContractUrl(llmsTxt: string): string | null {
236 const match = ASYNCAPI_CONTRACT_LINK.exec(llmsTxt)
237 return match?.[1] ?? null
238}
239
240async function fetchTextOrNull(url: string): Promise<string | null> {
241 try {
242 const response = await fetch(url)
243 if (!response.ok) return null
244 return await response.text()
245 } catch {
246 return null
247 }
248}
249
250async function discoverAsyncApiDocument(
251 rawId: string,
252): Promise<{ url: string; text: string } | null> {
253 const llms = await fetchTextOrNull(falLlmsTxtUrl(rawId))
254 const fromLlms = llms ? parseAsyncApiContractUrl(llms) : null
255 const candidates = [...new Set([fromLlms, falAsyncApiUrl(rawId)])].filter(
256 (url): url is string => typeof url === 'string' && url.length > 0,
257 )
258 for (const url of candidates) {
259 const text = await fetchTextOrNull(url)
260 if (text === null) continue
261 try {
262 const parsed: unknown = JSON.parse(text)
263 if (
264 typeof parsed === 'object' &&
265 parsed !== null &&
266 'asyncapi' in parsed &&
267 typeof parsed.asyncapi === 'string'
268 ) {
269 return { url, text }
270 }
271 } catch {
272 continue
273 }
274 }
275 return null
276}
277
278function asyncApiDescription(document: unknown, rawId: string): string | null {
279 if (typeof document !== 'object' || document === null) {
280 return `AsyncAPI ${rawId}`
281 }
282 const info =
283 'info' in document &&
284 typeof document.info === 'object' &&
285 document.info !== null
286 ? document.info
287 : null
288 if (info && 'title' in info && typeof info.title === 'string') {
289 return info.title
290 }
291 if (info && 'description' in info && typeof info.description === 'string') {
292 return info.description
293 }
294 return `AsyncAPI ${rawId}`
295}
296
297async function fetchSpec(env: ProviderSecrets): Promise<SpecFetchResult> {
298 const apiKey = env.FAL_KEY
299 if (!apiKey) {
300 return {
301 specs: [],
302 sources: [],
303 outputStrategy: 'sibling-get',
304 ...skippedResult('fal', 'FAL_KEY'),
305 }
306 }
307 const models = await fetchFalModels(apiKey, true)
308 const specs: Array<OpenApiDocument> = []
309 const sources: Array<SpecSource> = []
310 const openApiPosted = new Set<string>()
311 for (const model of models) {
312 if (!model.openapi) continue
313 const activity = falCategoryActivity(model.metadata.category)
314 if (activity === null) continue
315 const spec = model.openapi
316 if (hasPostOperation(spec)) openApiPosted.add(model.endpoint_id)
317 // FAL specs arrive embedded in the models API response (no standalone
318 // file URL), so provenance hashes the embedded document as delivered —
319 // before our annotations below.
320 sources.push({
321 url: `${FAL_MODELS_URL}?expand=openapi-3.0#${model.endpoint_id}`,
322 hash: await contentHash(spec),
323 })
324 // Stash endpointId on info for the merge step (per-endpoint schema
325 // dedup-renaming), mirroring the PR's x-fal-metadata trick.
326 spec.info ??= {}
327 spec.info['x-fal-endpoint-id'] = model.endpoint_id
328 annotateOperations(spec, activity)
329 specs.push(spec)
330 }
331
332 const bundledEndpoints: Array<BundledEndpoint> = []
333 const asyncApiRawIds: Array<string> = []
334 const warnings: Array<string> = []
335 for (const model of models) {
336 if (openApiPosted.has(model.endpoint_id)) continue
337 const activity = falCategoryActivity(model.metadata.category)
338 if (activity === null) continue
339 try {
340 const discovered = await discoverAsyncApiDocument(model.endpoint_id)
341 if (!discovered) continue
342 const document: unknown = JSON.parse(discovered.text)
343 const extracted = extractAsyncApiSchemas(document)
344 warnings.push(...extracted.warnings)
345 if (!extracted.input && !extracted.output) continue
346 bundledEndpoints.push({
347 path: `/${model.endpoint_id}`,
348 activity,
349 description: asyncApiDescription(document, model.endpoint_id),
350 source: {
351 url: discovered.url,
352 hash: await sha256Text(discovered.text),
353 },
354 derivation: 'upstream-spec',
355 input: extracted.input,
356 output: extracted.output,
357 asyncapi: true,
358 })
359 asyncApiRawIds.push(model.endpoint_id)
360 } catch (error) {
361 const message = error instanceof Error ? error.message : String(error)
362 warnings.push(
363 `fal ${model.endpoint_id}: asyncapi ingest failed: ${message}`,
364 )
365 }
366 }
367
368 return {
369 specs,
370 sources,
371 outputStrategy: 'sibling-get',
372 bundledEndpoints,
373 asyncApiRawIds,
374 ...(warnings.length > 0 ? { warnings } : {}),
375 }
376}
377
378interface ChatTokenPrice {
379 card: NonNullable<ModelInfo['pricing']>
380 source: FactSource
381}
382
383/**
384 * Token cards for chat endpoints, from each endpoint's own llms.txt.
385 * The hourly extract still owns the other ~1500 endpoints and any Pricing
386 * section this parser will not stand behind. A missing Pricing heading is
387 * a failed fetch (not cached); a heading with no token price is a real
388 * page and stores nothing.
389 */
390async function loadChatTokenPrices(
391 rawIds: Array<string>,
392 docs: ReturnType<typeof docsRun>,
393 kv: KVNamespace | undefined,
394): Promise<Map<string, ChatTokenPrice | 'unavailable'>> {
395 const out = new Map<string, ChatTokenPrice | 'unavailable'>()
396 if (rawIds.length === 0) return out
397 const loaded = await mapConcurrent(rawIds, 4, async (rawId) => {
398 const url = falLlmsTxtUrl(rawId)
399 const result = await tryDocs(docs, url, async (cached) => {
400 const text = await cached(kv, url, async () => {
401 const response = await fetch(url, {
402 signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
403 })
404 if (!response.ok) {
405 throw new Error(
406 `fal ${rawId} llms.txt: ${String(response.status)} ${response.statusText}`,
407 )
408 }
409 return await response.text()
410 })
411 const section = markdownSection(text, 'Pricing').trim()
412 if (section.length === 0) {
413 throw new Error(`fal ${rawId} llms.txt: no Pricing section`)
414 }
415 const hash = await sha256Text(section)
416 const card = compileFalTokenCard(section, {
417 url,
418 hash,
419 extractedAt: new Date().toISOString(),
420 })
421 const source: FactSource = {
422 derivation: 'docs-extracted',
423 sourceUrl: url,
424 sourceHash: hash,
425 path: 'Pricing',
426 }
427 return card === null ? { card: null, source } : { card, source }
428 })
429 return { rawId, result }
430 })
431 for (const item of loaded) {
432 if (item.result === null) out.set(item.rawId, 'unavailable')
433 else if (item.result.card !== null) {
434 out.set(item.rawId, {
435 card: item.result.card,
436 source: item.result.source,
437 })
438 }
439 }
440 return out
441}
442
443async function listModels(
444 env: ProviderSecrets,
445 kv?: KVNamespace,
446): Promise<ListModelsResult> {
447 const apiKey = env.FAL_KEY
448 if (!apiKey) {
449 return { models: [], ...skippedResult('fal', 'FAL_KEY') }
450 }
451 const falModels = await fetchFalModels(apiKey, false)
452 // The poll lists without specs (1,500 documents). Chat facts come from
453 // the request schema, so fetch the few chat endpoints' specs by id. A
454 // failed fetch is the chat rows' alone: they keep their stored chat
455 // facts, and the other 1,500 rows still poll.
456 const chat = falModels.filter(
457 (m) => falCategoryActivity(m.metadata.category) === 'chat',
458 )
459 const chatIds = chat.map((m) => m.endpoint_id)
460 const docs = docsRun()
461 const chatFacts = await tryDocs(
462 docs,
463 `${FAL_MODELS_URL}?expand=openapi-3.0 (chat endpoints)`,
464 async () => {
465 const chatSpecs = new Map<string, OpenApiDocument | undefined>()
466 for (let i = 0; i < chatIds.length; i += ENDPOINT_FILTER_MAX) {
467 const page = await fetchFalModels(
468 apiKey,
469 true,
470 chatIds.slice(i, i + ENDPOINT_FILTER_MAX),
471 )
472 for (const m of page) chatSpecs.set(m.endpoint_id, m.openapi)
473 }
474 const unanswered = chatIds.filter((id) => !chatSpecs.has(id))
475 if (unanswered.length > 0) {
476 throw new Error(
477 `fal chat specs: models API left out ${unanswered.join(', ')}`,
478 )
479 }
480 return new Map(
481 chat.map((m) => [
482 m.endpoint_id,
483 falChatFacts(
484 {
485 endpoint_id: m.endpoint_id,
486 description: m.metadata.description,
487 openapi: chatSpecs.get(m.endpoint_id),
488 },
489 FAL_MODELS_URL,
490 ),
491 ]),
492 )
493 },
494 )
495 const chatUnavailable = unavailable(
496 'contextWindow',
497 'maxOutput',
498 'modalities',
499 'capabilities',
500 'reasoning',
501 'requestMap',
502 )
503 const tokenPrices = await loadChatTokenPrices(chatIds, docs, kv)
504 const models: Array<ModelInfo> = falModels.map((m) => {
505 const facts = chatFacts?.get(m.endpoint_id)
506 const price = tokenPrices.get(m.endpoint_id)
507 const card = price && price !== 'unavailable' ? price : null
508 const absent = {
509 ...(facts || !chatIds.includes(m.endpoint_id)
510 ? {}
511 : (chatUnavailable.absent ?? {})),
512 ...(price === 'unavailable' ? { pricing: 'unavailable' as const } : {}),
513 }
514 const factSources: ModelFactSources = {
515 ...(facts?.factSources ?? {}),
516 ...(card ? { pricing: card.source } : {}),
517 }
518 const { factSources: _listedSources, ...rest } = facts ?? {}
519 return {
520 rawId: m.endpoint_id,
521 displayName: m.metadata.display_name ?? null,
522 activity: falCategoryActivity(m.metadata.category),
523 deprecated: m.metadata.status === 'deprecated',
524 releasedAt: isoToEpochSeconds(m.metadata.date),
525 providerMetadata: { category: m.metadata.category },
526 // A chat row with a request schema also carries the flag list every
527 // other provider's chat rows do.
528 ...rest,
529 ...(card ? { pricing: card.card } : {}),
530 ...(Object.keys(factSources).length > 0 ? { factSources } : {}),
531 ...(Object.keys(absent).length > 0 ? { absent } : {}),
532 }
533 })
534 return { models, docsFailures: docsReport(docs) }
535}
536
537export const falProvider: ProviderConfig = {
538 id: 'fal',
539 displayName: 'FAL',
540 authEnvVar: 'FAL_KEY',
541 defaultDerivation: 'upstream-spec',
542 specGrain: 'model',
543 connect: {
544 servers: [{ url: 'https://queue.fal.run' }],
545 securitySchemes: {
546 apiKey: {
547 type: 'apiKey',
548 in: 'header',
549 name: 'Authorization',
550 description:
551 'Send `Key <FAL_KEY>` (literal prefix "Key ", then the token).',
552 },
553 },
554 security: [{ apiKey: [] }],
555 siblingGet: true,
556 },
557 fetchSpec,
558 listModels,
559 classify,
560}