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 { fetchWithRetry, 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 /**
55 * Null on rows the active search omits. Category then lives on the
56 * embedded OpenAPI document (`info['x-fal-metadata'].category`), which
57 * arrives only when the request sets `expand=openapi-3.0`.
58 */
59 metadata: {
60 display_name?: string
61 category?: string
62 description?: string
63 status?: 'active' | 'inactive' | 'deprecated'
64 /** Listing/release date, ISO 8601. */
65 date?: string
66 [key: string]: unknown
67 } | null
68 retires_at?: string | null
69}
70
71/**
72 * Ids the active models search never pages, while `endpoint_id` lookup
73 * still serves queue OpenAPI. `fal-ai/whisper` is the default transcription
74 * model in TanStack AI. One id per request: a missing id 404s the batch.
75 */
76const FAL_UNLISTED_ENDPOINT_IDS = ['fal-ai/whisper']
77
78/**
79 * Body of a filtered models request whose `endpoint_id` FAL no longer
80 * serves. One such id 404s the whole batch (`Endpoint(s) not found`).
81 * Any other 404 is a different failure and must still throw.
82 */
83const FAL_ENDPOINT_NOT_FOUND = 'Endpoint(s) not found'
84
85function openApiCategory(model: FalApiModel): string | null {
86 const meta = model.openapi?.info?.['x-fal-metadata']
87 if (typeof meta !== 'object' || meta === null || !('category' in meta)) {
88 return null
89 }
90 const category = meta.category
91 return typeof category === 'string' && category.length > 0 ? category : null
92}
93
94/** Listing category, else the category stamped on the embedded OpenAPI. */
95function modelCategory(model: FalApiModel): string | null {
96 const listed = model.metadata?.category
97 if (typeof listed === 'string' && listed.length > 0) return listed
98 return openApiCategory(model)
99}
100
101/**
102 * A listing says `deprecated` in metadata. An unlisted row has no metadata;
103 * a `retires_at` already in the past is the only deprecation signal left.
104 */
105function modelDeprecated(model: FalApiModel): boolean {
106 if (model.metadata?.status === 'deprecated') return true
107 if (model.metadata != null) return false
108 if (typeof model.retires_at !== 'string') return false
109 const at = Date.parse(model.retires_at)
110 return Number.isFinite(at) && at <= Date.now()
111}
112
113interface FalApiResponse {
114 models: Array<FalApiModel>
115 has_more: boolean
116 next_cursor: string | null
117}
118
119/**
120 * Full-category overrides, applied before the target-modality mapping.
121 * Transcription belongs in `audio` regardless of its `text` target;
122 * `training` is fine-tuning (platform — dropped), `workflow`/`unknown` are
123 * not generation endpoints.
124 */
125const FAL_CATEGORY_OVERRIDES: Record<string, Activity | null> = {
126 'speech-to-text': 'audio',
127 'audio-to-text': 'audio',
128 training: null,
129 workflow: null,
130 unknown: null,
131}
132
133/**
134 * Target modality (from `<source>-to-<target>` category names) → activity.
135 * Speech and music land in `audio`; image/video/audio-to-text (captioning,
136 * visual QA) land in `chat` like other text generation. Target modalities
137 * outside the shared taxonomy (`3d`, `json`, `vision`, …) have no activity
138 * in our six-value enum and classify to null (PR #622 kept them as their own
139 * sub-groups; our catalog drops them until the taxonomy grows).
140 */
141const FAL_MODALITY_ACTIVITIES: Record<string, Activity> = {
142 image: 'image',
143 video: 'video',
144 audio: 'audio',
145 speech: 'audio',
146 music: 'audio',
147 text: 'chat',
148 llm: 'chat',
149}
150
151export function falCategoryActivity(category: string): Activity | null {
152 const override = FAL_CATEGORY_OVERRIDES[category]
153 if (override !== undefined) return override
154 const modality = category.replace(/^.+-to-/, '')
155 return FAL_MODALITY_ACTIVITIES[modality] ?? null
156}
157
158function classify(_path: string, op: OpenApiOperation): Activity | null {
159 const marker = op[FAL_ACTIVITY_MARKER]
160 if (
161 typeof marker === 'string' &&
162 (activities as ReadonlyArray<string>).includes(marker)
163 ) {
164 return marker as Activity
165 }
166 return null
167}
168
169/** A page that has not answered by now is retried like a dropped connection. */
170const FETCH_TIMEOUT_MS = 60_000
171
172/** Most `endpoint_id` filters the models API takes in one request. */
173const ENDPOINT_FILTER_MAX = 50
174
175/** Non-retryable upstream failure — thrown through the retry loop as-is. */
176class FalFetchError extends Error {
177 constructor(
178 message: string,
179 readonly status: number,
180 readonly body: string,
181 ) {
182 super(message)
183 }
184}
185
186/** True when FAL says this filtered request names an endpoint it no longer serves. */
187function falEndpointGone(error: unknown): error is FalFetchError {
188 if (!(error instanceof FalFetchError) || error.status !== 404) return false
189 try {
190 const parsed: unknown = JSON.parse(error.body)
191 if (typeof parsed !== 'object' || parsed === null || !('error' in parsed)) {
192 return false
193 }
194 const inner = parsed.error
195 if (typeof inner !== 'object' || inner === null) return false
196 return (
197 'type' in inner &&
198 inner.type === 'not_found' &&
199 'message' in inner &&
200 inner.message === FAL_ENDPOINT_NOT_FOUND
201 )
202 } catch {
203 return false
204 }
205}
206
207/** The single-id request that proved `id` is gone, for the poll log. */
208function goneEndpointLocation(id: string, expandOpenApi: boolean): string {
209 const params = new URLSearchParams({ status: 'active' })
210 if (expandOpenApi) params.set('expand', 'openapi-3.0')
211 params.append('endpoint_id', id)
212 return `${FAL_MODELS_URL}?${params.toString()}`
213}
214
215function reportGoneEndpoint(id: string, expandOpenApi: boolean): void {
216 const location = goneEndpointLocation(id, expandOpenApi)
217 console.error(
218 `fal ${id}: no longer served at ${location} (404 ${FAL_ENDPOINT_NOT_FOUND}); omitting the row so the poll deprecates it`,
219 )
220}
221
222/**
223 * The paginated crawl is ~30 requests per pass and runs from both cron
224 * tiers, so transient 429s/5xxs and dropped connections are routine — each
225 * page is retried by {@link fetchWithRetry} rather than one throw sinking
226 * the whole sync and flagging the provider degraded.
227 */
228export function fetchPageWithRetry(
229 url: string,
230 apiKey: string,
231 attempts = 5,
232): Promise<FalApiResponse> {
233 return fetchWithRetry(
234 url,
235 () => ({
236 headers: { Authorization: `Key ${apiKey}` },
237 signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
238 }),
239 async (response) => (await response.json()) as FalApiResponse,
240 {
241 attempts,
242 reject: async (response) =>
243 new FalFetchError(
244 `fal models fetch failed: ${String(response.status)} ${response.statusText}`,
245 response.status,
246 await response.text(),
247 ),
248 },
249 )
250}
251
252async function fetchFalModels(
253 apiKey: string,
254 expandOpenApi: boolean,
255 endpointIds: Array<string> = [],
256): Promise<Array<FalApiModel>> {
257 const allModels: Array<FalApiModel> = []
258 let cursor: string | null = null
259 do {
260 const params = new URLSearchParams({ status: 'active' })
261 if (expandOpenApi) params.set('expand', 'openapi-3.0')
262 for (const id of endpointIds) params.append('endpoint_id', id)
263 if (cursor) params.set('cursor', cursor)
264 const data = await fetchPageWithRetry(
265 `${FAL_MODELS_URL}?${params.toString()}`,
266 apiKey,
267 )
268 allModels.push(...data.models)
269 cursor = data.has_more ? data.next_cursor : null
270 } while (cursor)
271 return allModels
272}
273
274/**
275 * Fetch by `endpoint_id`. A removed id 404s every filter it sits in, so
276 * split until that id is alone, log it, and return the rows FAL still
277 * serves. A 404 that is not {@link FAL_ENDPOINT_NOT_FOUND} still throws.
278 */
279async function fetchFalModelsAllowingGone(
280 apiKey: string,
281 expandOpenApi: boolean,
282 endpointIds: Array<string>,
283): Promise<{ models: Array<FalApiModel>; gone: Array<string> }> {
284 try {
285 return {
286 models: await fetchFalModels(apiKey, expandOpenApi, endpointIds),
287 gone: [],
288 }
289 } catch (error) {
290 if (!falEndpointGone(error) || endpointIds.length === 0) throw error
291 if (endpointIds.length === 1) {
292 const only = endpointIds[0]
293 if (only === undefined) throw error
294 reportGoneEndpoint(only, expandOpenApi)
295 return { models: [], gone: [only] }
296 }
297 const mid = Math.ceil(endpointIds.length / 2)
298 const left = await fetchFalModelsAllowingGone(
299 apiKey,
300 expandOpenApi,
301 endpointIds.slice(0, mid),
302 )
303 const right = await fetchFalModelsAllowingGone(
304 apiKey,
305 expandOpenApi,
306 endpointIds.slice(mid),
307 )
308 return {
309 models: [...left.models, ...right.models],
310 gone: [...left.gone, ...right.gone],
311 }
312 }
313}
314
315/**
316 * Append {@link FAL_UNLISTED_ENDPOINT_IDS} that the active crawl did not
317 * return. Only an id FAL reports as {@link FAL_ENDPOINT_NOT_FOUND} is
318 * skipped, so the row is marked removed. Any other failure throws:
319 * skipping it would also drop the row, and the poller would emit a false
320 * `model.removed`.
321 */
322async function appendUnlistedFalModels(
323 apiKey: string,
324 models: Array<FalApiModel>,
325 expandOpenApi: boolean,
326): Promise<Array<FalApiModel>> {
327 const seen = new Set(models.map((model) => model.endpoint_id))
328 const extra: Array<FalApiModel> = []
329 for (const id of FAL_UNLISTED_ENDPOINT_IDS) {
330 if (seen.has(id)) continue
331 const { models: page } = await fetchFalModelsAllowingGone(
332 apiKey,
333 expandOpenApi,
334 [id],
335 )
336 const match = page.find((model) => model.endpoint_id === id)
337 if (!match || seen.has(match.endpoint_id)) continue
338 seen.add(match.endpoint_id)
339 extra.push(match)
340 }
341 return extra.length === 0 ? models : [...models, ...extra]
342}
343
344function annotateOperations(spec: OpenApiDocument, activity: Activity): void {
345 for (const operations of Object.values(spec.paths ?? {})) {
346 for (const op of Object.values(operations)) {
347 op[FAL_ACTIVITY_MARKER] = activity
348 }
349 }
350}
351
352function hasPostOperation(spec: OpenApiDocument): boolean {
353 for (const operations of Object.values(spec.paths ?? {})) {
354 if (operations.post) return true
355 }
356 return false
357}
358
359/** `minimax/h3-max/director` → `fal-ai/minimax-h3-max-director`. */
360export function falAppSlug(rawId: string): string {
361 return `fal-ai/${rawId.replaceAll('/', '-')}`
362}
363
364export function falAsyncApiUrl(rawId: string): string {
365 return `https://fal.ai/api/apps/${falAppSlug(rawId)}/asyncapi.json`
366}
367
368export function falLlmsTxtUrl(rawId: string): string {
369 return `https://fal.ai/models/${rawId}/llms.txt`
370}
371
372const ASYNCAPI_CONTRACT_LINK = /\[AsyncAPI Contract\]\((https?:\/\/[^)\s]+)\)/i
373
374export function parseAsyncApiContractUrl(llmsTxt: string): string | null {
375 const match = ASYNCAPI_CONTRACT_LINK.exec(llmsTxt)
376 return match?.[1] ?? null
377}
378
379async function fetchTextOrNull(url: string): Promise<string | null> {
380 try {
381 const response = await fetch(url)
382 if (!response.ok) return null
383 return await response.text()
384 } catch {
385 return null
386 }
387}
388
389async function discoverAsyncApiDocument(
390 rawId: string,
391): Promise<{ url: string; text: string } | null> {
392 const llms = await fetchTextOrNull(falLlmsTxtUrl(rawId))
393 const fromLlms = llms ? parseAsyncApiContractUrl(llms) : null
394 const candidates = [...new Set([fromLlms, falAsyncApiUrl(rawId)])].filter(
395 (url): url is string => typeof url === 'string' && url.length > 0,
396 )
397 for (const url of candidates) {
398 const text = await fetchTextOrNull(url)
399 if (text === null) continue
400 try {
401 const parsed: unknown = JSON.parse(text)
402 if (
403 typeof parsed === 'object' &&
404 parsed !== null &&
405 'asyncapi' in parsed &&
406 typeof parsed.asyncapi === 'string'
407 ) {
408 return { url, text }
409 }
410 } catch {
411 continue
412 }
413 }
414 return null
415}
416
417function asyncApiDescription(document: unknown, rawId: string): string | null {
418 if (typeof document !== 'object' || document === null) {
419 return `AsyncAPI ${rawId}`
420 }
421 const info =
422 'info' in document &&
423 typeof document.info === 'object' &&
424 document.info !== null
425 ? document.info
426 : null
427 if (info && 'title' in info && typeof info.title === 'string') {
428 return info.title
429 }
430 if (info && 'description' in info && typeof info.description === 'string') {
431 return info.description
432 }
433 return `AsyncAPI ${rawId}`
434}
435
436async function fetchSpec(env: ProviderSecrets): Promise<SpecFetchResult> {
437 const apiKey = env.FAL_KEY
438 if (!apiKey) {
439 return {
440 specs: [],
441 sources: [],
442 outputStrategy: 'sibling-get',
443 ...skippedResult('fal', 'FAL_KEY'),
444 }
445 }
446 const models = await appendUnlistedFalModels(
447 apiKey,
448 await fetchFalModels(apiKey, true),
449 true,
450 )
451 const specs: Array<OpenApiDocument> = []
452 const sources: Array<SpecSource> = []
453 const openApiPosted = new Set<string>()
454 for (const model of models) {
455 if (!model.openapi) continue
456 const category = modelCategory(model)
457 const activity = category === null ? null : falCategoryActivity(category)
458 if (activity === null) continue
459 const spec = model.openapi
460 if (hasPostOperation(spec)) openApiPosted.add(model.endpoint_id)
461 // FAL specs arrive embedded in the models API response (no standalone
462 // file URL), so provenance hashes the embedded document as delivered —
463 // before our annotations below.
464 sources.push({
465 url: `${FAL_MODELS_URL}?expand=openapi-3.0#${model.endpoint_id}`,
466 hash: await contentHash(spec),
467 })
468 // Stash endpointId on info for the merge step (per-endpoint schema
469 // dedup-renaming), mirroring the PR's x-fal-metadata trick.
470 spec.info ??= {}
471 spec.info['x-fal-endpoint-id'] = model.endpoint_id
472 annotateOperations(spec, activity)
473 specs.push(spec)
474 }
475
476 const bundledEndpoints: Array<BundledEndpoint> = []
477 const asyncApiRawIds: Array<string> = []
478 const warnings: Array<string> = []
479 for (const model of models) {
480 if (openApiPosted.has(model.endpoint_id)) continue
481 const category = modelCategory(model)
482 const activity = category === null ? null : falCategoryActivity(category)
483 if (activity === null) continue
484 try {
485 const discovered = await discoverAsyncApiDocument(model.endpoint_id)
486 if (!discovered) continue
487 const document: unknown = JSON.parse(discovered.text)
488 const extracted = extractAsyncApiSchemas(document)
489 warnings.push(...extracted.warnings)
490 if (!extracted.input && !extracted.output) continue
491 bundledEndpoints.push({
492 path: `/${model.endpoint_id}`,
493 activity,
494 description: asyncApiDescription(document, model.endpoint_id),
495 source: {
496 url: discovered.url,
497 hash: await sha256Text(discovered.text),
498 },
499 derivation: 'upstream-spec',
500 input: extracted.input,
501 output: extracted.output,
502 asyncapi: true,
503 })
504 asyncApiRawIds.push(model.endpoint_id)
505 } catch (error) {
506 const message = error instanceof Error ? error.message : String(error)
507 warnings.push(
508 `fal ${model.endpoint_id}: asyncapi ingest failed: ${message}`,
509 )
510 }
511 }
512
513 return {
514 specs,
515 sources,
516 outputStrategy: 'sibling-get',
517 bundledEndpoints,
518 asyncApiRawIds,
519 ...(warnings.length > 0 ? { warnings } : {}),
520 }
521}
522
523interface ChatTokenPrice {
524 card: NonNullable<ModelInfo['pricing']>
525 source: FactSource
526}
527
528/**
529 * Token cards for chat endpoints, from each endpoint's own llms.txt.
530 * The hourly extract still owns the other ~1500 endpoints and any Pricing
531 * section this parser will not stand behind. A missing Pricing heading is
532 * a failed fetch (not cached); a heading with no token price is a real
533 * page and stores nothing.
534 */
535async function loadChatTokenPrices(
536 rawIds: Array<string>,
537 docs: ReturnType<typeof docsRun>,
538 kv: KVNamespace | undefined,
539): Promise<Map<string, ChatTokenPrice | 'unavailable'>> {
540 const out = new Map<string, ChatTokenPrice | 'unavailable'>()
541 if (rawIds.length === 0) return out
542 const loaded = await mapConcurrent(rawIds, 4, async (rawId) => {
543 const url = falLlmsTxtUrl(rawId)
544 const result = await tryDocs(docs, url, async (cached) => {
545 const text = await cached(kv, url, async () => {
546 const response = await fetch(url, {
547 signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
548 })
549 if (!response.ok) {
550 throw new Error(
551 `fal ${rawId} llms.txt: ${String(response.status)} ${response.statusText}`,
552 )
553 }
554 return await response.text()
555 })
556 const section = markdownSection(text, 'Pricing').trim()
557 if (section.length === 0) {
558 throw new Error(`fal ${rawId} llms.txt: no Pricing section`)
559 }
560 const hash = await sha256Text(section)
561 const card = compileFalTokenCard(section, {
562 url,
563 hash,
564 extractedAt: new Date().toISOString(),
565 })
566 const source: FactSource = {
567 derivation: 'docs-extracted',
568 sourceUrl: url,
569 sourceHash: hash,
570 path: 'Pricing',
571 }
572 return card === null ? { card: null, source } : { card, source }
573 })
574 return { rawId, result }
575 })
576 for (const item of loaded) {
577 if (item.result === null) out.set(item.rawId, 'unavailable')
578 else if (item.result.card !== null) {
579 out.set(item.rawId, {
580 card: item.result.card,
581 source: item.result.source,
582 })
583 }
584 }
585 return out
586}
587
588async function listModels(
589 env: ProviderSecrets,
590 kv?: KVNamespace,
591): Promise<ListModelsResult> {
592 const apiKey = env.FAL_KEY
593 if (!apiKey) {
594 return { models: [], ...skippedResult('fal', 'FAL_KEY') }
595 }
596 const listedModels = await fetchFalModels(apiKey, false)
597 // The poll lists without specs (1,500 documents). Chat facts come from
598 // the request schema, so fetch the few chat endpoints' specs by id. A
599 // failed fetch is the chat rows' alone: they keep their stored chat
600 // facts, and the other 1,500 rows still poll.
601 const chat = listedModels.filter((m) => {
602 const category = modelCategory(m)
603 return category !== null && falCategoryActivity(category) === 'chat'
604 })
605 const chatIds = chat.map((m) => m.endpoint_id)
606 const docs = docsRun()
607 // Ids the active search still returns but `endpoint_id` lookup 404s.
608 // Left out of the rows below, so the poll deprecates them.
609 const gone = new Set<string>()
610 const chatFacts = await tryDocs(
611 docs,
612 `${FAL_MODELS_URL}?expand=openapi-3.0 (chat endpoints)`,
613 async () => {
614 const chatSpecs = new Map<string, OpenApiDocument | undefined>()
615 for (let i = 0; i < chatIds.length; i += ENDPOINT_FILTER_MAX) {
616 const batch = chatIds.slice(i, i + ENDPOINT_FILTER_MAX)
617 const { models: page, gone: batchGone } =
618 await fetchFalModelsAllowingGone(apiKey, true, batch)
619 for (const id of batchGone) gone.add(id)
620 for (const m of page) chatSpecs.set(m.endpoint_id, m.openapi)
621 }
622 const unanswered = chatIds.filter(
623 (id) => !chatSpecs.has(id) && !gone.has(id),
624 )
625 if (unanswered.length > 0) {
626 throw new Error(
627 `fal chat specs: models API left out ${unanswered.join(', ')}`,
628 )
629 }
630 return new Map(
631 chat
632 .filter((m) => !gone.has(m.endpoint_id))
633 .map((m) => [
634 m.endpoint_id,
635 falChatFacts(
636 {
637 endpoint_id: m.endpoint_id,
638 description: m.metadata?.description,
639 openapi: chatSpecs.get(m.endpoint_id),
640 },
641 FAL_MODELS_URL,
642 ),
643 ]),
644 )
645 },
646 )
647 const chatUnavailable = unavailable(
648 'contextWindow',
649 'maxOutput',
650 'modalities',
651 'capabilities',
652 'reasoning',
653 'requestMap',
654 )
655 const tokenPrices = await loadChatTokenPrices(
656 chatIds.filter((id) => !gone.has(id)),
657 docs,
658 kv,
659 )
660 // After the chat spec request, so that request stays the second models
661 // call. The lookup expands OpenAPI: unlisted rows carry no metadata, and
662 // the category is on the document. A chat id the filter proved gone is
663 // dropped here: the active search still listed it.
664 const falModels = (
665 await appendUnlistedFalModels(apiKey, listedModels, true)
666 ).filter((model) => !gone.has(model.endpoint_id))
667 const models: Array<ModelInfo> = falModels.map((m) => {
668 const facts = chatFacts?.get(m.endpoint_id)
669 const price = tokenPrices.get(m.endpoint_id)
670 const card = price && price !== 'unavailable' ? price : null
671 const absent = {
672 ...(facts || !chatIds.includes(m.endpoint_id)
673 ? {}
674 : (chatUnavailable.absent ?? {})),
675 ...(price === 'unavailable' ? { pricing: 'unavailable' as const } : {}),
676 }
677 const factSources: ModelFactSources = {
678 ...facts?.factSources,
679 ...(card ? { pricing: card.source } : {}),
680 }
681 const { factSources: _listedSources, ...rest } = facts ?? {}
682 const category = modelCategory(m)
683 return {
684 rawId: m.endpoint_id,
685 displayName: m.metadata?.display_name ?? null,
686 activity: category === null ? null : falCategoryActivity(category),
687 deprecated: modelDeprecated(m),
688 releasedAt: isoToEpochSeconds(m.metadata?.date),
689 ...(category ? { providerMetadata: { category } } : {}),
690 // A chat row with a request schema also carries the flag list every
691 // other provider's chat rows do.
692 ...rest,
693 ...(card ? { pricing: card.card } : {}),
694 ...(Object.keys(factSources).length > 0 ? { factSources } : {}),
695 ...(Object.keys(absent).length > 0 ? { absent } : {}),
696 }
697 })
698 return { models, docsFailures: docsReport(docs) }
699}
700
701export const falProvider: ProviderConfig = {
702 id: 'fal',
703 displayName: 'FAL',
704 authEnvVar: 'FAL_KEY',
705 defaultDerivation: 'upstream-spec',
706 specGrain: 'model',
707 connect: {
708 servers: [{ url: 'https://queue.fal.run' }],
709 securitySchemes: {
710 apiKey: {
711 type: 'apiKey',
712 in: 'header',
713 name: 'Authorization',
714 description:
715 'Send `Key <FAL_KEY>` (literal prefix "Key ", then the token).',
716 },
717 },
718 security: [{ apiKey: [] }],
719 siblingGet: true,
720 },
721 fetchSpec,
722 listModels,
723 classify,
724}