Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(fal): run any fal endpoint and fetch fal's image/video model list (#21238)

Morax5735041755db
diff --git a/packages/model-bank/src/modelProviders/fal.ts b/packages/model-bank/src/modelProviders/fal.ts
index 1390938f852..442c6b95e20 100644
--- a/packages/model-bank/src/modelProviders/fal.ts
+++ b/packages/model-bank/src/modelProviders/fal.ts
@@ -7,12 +7,15 @@ const Fal: ModelProviderCard = {
chatModels: [],
description: 'A generative media platform built for developers.',
id: 'fal',
+ // Fetching lists every fal image/video endpoint (any owner) with parameters from its schema
+ modelList: { showModelFetcher: true },
+ modelsUrl: 'https://fal.ai/models',
name: 'Fal',
settings: {
disableBrowserRequest: true,
showAddNewModel: false,
showChecker: false,
- showModelFetcher: false,
+ showModelFetcher: true,
},
url: 'https://fal.ai',
};
diff --git a/packages/model-runtime/src/providers/fal/catalog.ts b/packages/model-runtime/src/providers/fal/catalog.ts
new file mode 100644
index 00000000000..753688edca4
--- /dev/null
+++ b/packages/model-runtime/src/providers/fal/catalog.ts
@@ -0,0 +1,232 @@
+import debug from 'debug';
+
+import type { FalJsonSchema } from './schema';
+import {
+ extractFalInputSchema,
+ falInputSchemaToImageParameters,
+ falInputSchemaToVideoParameters,
+} from './schema';
+
+const log = debug('lobe-image:fal:catalog');
+
+// https://fal.ai/docs/platform-apis/v1/models
+const FAL_MODELS_API = 'https://api.fal.ai/v1/models';
+
+/**
+ * Catalog categories the generation pages can drive, in listing order, with the model type each
+ * maps to.
+ */
+const FAL_GENERATION_CATEGORIES = [
+ ['text-to-image', 'image'],
+ ['image-to-image', 'image'],
+ ['text-to-video', 'video'],
+ ['image-to-video', 'video'],
+] as const;
+
+type FalGenerationCategory = (typeof FAL_GENERATION_CATEGORIES)[number];
+
+/** fal caps the page size at 10 when a catalog request expands OpenAPI schemas */
+export const FAL_CATALOG_PAGE_SIZE = 10;
+
+/** Upper bound of pages per category, so a model fetch stays a bounded number of requests */
+const MAX_PAGES_PER_CATEGORY = 40;
+
+/** Attempts per catalog request; fal rate limits (429) bursts of paginated requests */
+const MAX_ATTEMPTS = 4;
+const MAX_RETRY_DELAY_MS = 8000;
+
+const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/** Delay before retrying a 429: fal's `Retry-After` seconds when sent, else exponential backoff */
+const retryDelay = (response: Response, attempt: number) => {
+ const retryAfter = Number(response.headers.get('retry-after'));
+ const delay = Number.isFinite(retryAfter) && response.headers.has('retry-after')
+ ? retryAfter * 1000
+ : 1000 * 2 ** attempt;
+ return Math.min(Math.max(delay, 0), MAX_RETRY_DELAY_MS);
+};
+
+interface FalCatalogModel {
+ endpoint_id: string;
+ metadata?: {
+ category?: string;
+ date?: string;
+ description?: string;
+ display_name?: string;
+ kind?: string;
+ status?: string;
+ };
+ openapi?: unknown;
+}
+
+interface FalCatalogPage {
+ has_more?: boolean;
+ models?: FalCatalogModel[];
+ next_cursor?: string | null;
+}
+
+export interface FalModelListItem {
+ description?: string;
+ displayName: string;
+ id: string;
+ parameters: Record<string, unknown>;
+ releasedAt?: string;
+ type: 'image' | 'video';
+}
+
+const requestCatalog = async (
+ apiKey: string,
+ query: Record<string, string | undefined>,
+ signal?: AbortSignal,
+): Promise<FalCatalogPage> => {
+ const url = new URL(FAL_MODELS_API);
+ for (const [key, value] of Object.entries(query)) {
+ if (value !== undefined) url.searchParams.set(key, value);
+ }
+
+ let response = await fetch(url, { headers: { Authorization: `Key ${apiKey}` }, signal });
+ for (let attempt = 1; response.status === 429 && attempt < MAX_ATTEMPTS; attempt++) {
+ await wait(retryDelay(response, attempt - 1));
+ response = await fetch(url, { headers: { Authorization: `Key ${apiKey}` }, signal });
+ }
+
+ if (!response.ok) {
+ const error = new Error(`fal model catalog request failed: ${response.status}`);
+ Object.assign(error, { status: response.status });
+ throw error;
+ }
+
+ return response.json();
+};
+
+const toModelListItem = (
+ model: FalCatalogModel,
+ type: 'image' | 'video',
+): FalModelListItem | undefined => {
+ if (model.metadata?.kind === 'training') return;
+
+ const input = extractFalInputSchema(model.openapi, model.endpoint_id);
+ const parameters =
+ type === 'image'
+ ? falInputSchemaToImageParameters(input)
+ : falInputSchemaToVideoParameters(input);
+ if (!parameters) return;
+
+ const releasedAt = model.metadata?.date?.slice(0, 10);
+
+ return {
+ description: model.metadata?.description?.trim(),
+ displayName: model.metadata?.display_name || model.endpoint_id,
+ id: model.endpoint_id,
+ parameters,
+ ...(releasedAt && { releasedAt }),
+ type,
+ };
+};
+
+const listCategory = async (
+ apiKey: string,
+ [category, type]: FalGenerationCategory,
+ signal?: AbortSignal,
+) => {
+ const items: FalModelListItem[] = [];
+ let cursor: string | undefined;
+
+ for (let page = 0; page < MAX_PAGES_PER_CATEGORY; page++) {
+ let result: FalCatalogPage;
+ try {
+ result = await requestCatalog(
+ apiKey,
+ {
+ category,
+ cursor,
+ expand: 'openapi-3.0',
+ limit: String(FAL_CATALOG_PAGE_SIZE),
+ status: 'active',
+ },
+ signal,
+ );
+ } catch (error) {
+ // Keep the pages already listed; only a category whose first page fails is lost
+ if (page === 0) throw error;
+ log('fal catalog %s stopped at page %d: %O', category, page, error);
+ break;
+ }
+
+ for (const model of result.models ?? []) {
+ const item = toModelListItem(model, type);
+ if (item) items.push(item);
+ }
+
+ if (!result.has_more || !result.next_cursor) break;
+ cursor = result.next_cursor;
+ }
+
+ return items;
+};
+
+/**
+ * List the fal endpoints that can run on the image and video generation pages, each with the
+ * parameters derived from its input schema. Categories are listed one after another to stay
+ * under fal's rate limit. A failing category is skipped so it does not hide the rest; only a
+ * failure of every category (e.g. an invalid key) is thrown.
+ */
+export const listFalGenerationModels = async (apiKey: string, signal?: AbortSignal) => {
+ const results: PromiseSettledResult<FalModelListItem[]>[] = [];
+ for (const category of FAL_GENERATION_CATEGORIES) {
+ try {
+ results.push({ status: 'fulfilled', value: await listCategory(apiKey, category, signal) });
+ } catch (reason) {
+ results.push({ reason, status: 'rejected' });
+ }
+ }
+
+ const rejected = results.filter((result) => result.status === 'rejected');
+ if (rejected.length === results.length) throw (rejected[0] as PromiseRejectedResult).reason;
+
+ const models = new Map<string, FalModelListItem>();
+ for (const result of results) {
+ if (result.status === 'rejected') {
+ log('fal catalog category failed: %O', result.reason);
+ continue;
+ }
+ for (const item of result.value) if (!models.has(item.id)) models.set(item.id, item);
+ }
+
+ return [...models.values()];
+};
+
+/** fal redeploys endpoints in place, so a cached input schema is refetched after this long */
+export const FAL_INPUT_SCHEMA_TTL_MS = 60 * 60 * 1000;
+
+const inputSchemaCache = new Map<
+ string,
+ { expiresAt: number; schema: Promise<FalJsonSchema | undefined> }
+>();
+
+/**
+ * Input schema of one fal endpoint, cached per process for `FAL_INPUT_SCHEMA_TTL_MS`. Resolves
+ * undefined when the catalog cannot be reached, so callers fall back to sending the request as
+ * built.
+ */
+export const getFalInputSchema = (apiKey: string, endpointId: string) => {
+ const cached = inputSchemaCache.get(endpointId);
+ if (cached && cached.expiresAt > Date.now()) return cached.schema;
+
+ const schema = requestCatalog(apiKey, { endpoint_id: endpointId, expand: 'openapi-3.0' })
+ .then((page) => {
+ const model = page.models?.find((item) => item.endpoint_id === endpointId);
+ return extractFalInputSchema(model?.openapi, endpointId);
+ })
+ .catch((error) => {
+ log('Failed to load fal input schema for %s: %O', endpointId, error);
+ inputSchemaCache.delete(endpointId);
+ return undefined;
+ });
+
+ inputSchemaCache.set(endpointId, { expiresAt: Date.now() + FAL_INPUT_SCHEMA_TTL_MS, schema });
+ return schema;
+};
+
+/** @internal Test helper */
+export const clearFalInputSchemaCache = () => inputSchemaCache.clear();
diff --git a/packages/model-runtime/src/providers/fal/createVideo.test.ts b/packages/model-runtime/src/providers/fal/createVideo.test.ts
index c947dc5f886..84edcb62369 100644
--- a/packages/model-runtime/src/providers/fal/createVideo.test.ts
+++ b/packages/model-runtime/src/providers/fal/createVideo.test.ts
@@ -1,8 +1,10 @@
// @vitest-environment node
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { clearFalInputSchemaCache } from './catalog';
import { buildFalVideoRequest, parseFalVideoInferenceId } from './createVideo';
import { LobeFalAI } from './index';
+import { buildFalCatalogResponse } from './testUtils';
const { queue } = vi.hoisted(() => ({
queue: { result: vi.fn(), status: vi.fn(), submit: vi.fn() },
@@ -183,11 +185,89 @@ describe('LobeFalAI video', () => {
expect(queue.submit).toHaveBeenCalledWith('minimax/h3-max/text-to-video', expect.anything());
});
- it('rejects models without a video endpoint', async () => {
- await expect(
- runtime.createVideo({ model: 'fal-ai/qwen-image', params: { prompt: 'p' } }),
- ).rejects.toMatchObject({ errorType: 'ProviderBizError' });
- expect(queue.submit).not.toHaveBeenCalled();
+ describe('any other fal video endpoint', () => {
+ const KLING = 'fal-ai/kling-video/v2.1/standard/image-to-video';
+
+ beforeEach(() => {
+ clearFalInputSchemaCache();
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('submits to the endpoint as is and fits params to its schema', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify(
+ buildFalCatalogResponse(KLING, {
+ duration: { default: '5', enum: ['5', '10'], type: 'string' },
+ image_url: { type: 'string' },
+ prompt: { type: 'string' },
+ }),
+ ),
+ ),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ queue.submit.mockResolvedValue({ request_id: 'req-3' });
+
+ const result = await runtime.createVideo({
+ model: KLING,
+ params: {
+ aspectRatio: '16:9',
+ duration: 10,
+ imageUrl: 'https://img/first.png',
+ prompt: 'p',
+ },
+ });
+
+ expect(queue.submit).toHaveBeenCalledWith(KLING, {
+ // fal takes the duration as a string enum and has no aspect ratio on this endpoint
+ input: { duration: '10', image_url: 'https://img/first.png', prompt: 'p' },
+ });
+ expect(String(fetchMock.mock.calls[0][0])).toContain(
+ `endpoint_id=${encodeURIComponent(KLING)}`,
+ );
+ expect(result).toEqual({ inferenceId: `${KLING}/requests/req-3` });
+ });
+
+ it('keeps endpoints from other owners verbatim and matches suffixed durations', async () => {
+ const endpoint = 'bytedance/seedance-2.0/text-to-video';
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn().mockResolvedValue(
+ new Response(
+ JSON.stringify(
+ buildFalCatalogResponse(endpoint, {
+ duration: { enum: ['4s', '8s'], type: 'string' },
+ prompt: { type: 'string' },
+ }),
+ ),
+ ),
+ ),
+ );
+ queue.submit.mockResolvedValue({ request_id: 'req-4' });
+
+ await runtime.createVideo({ model: endpoint, params: { duration: 8, prompt: 'p' } });
+
+ expect(queue.submit).toHaveBeenCalledWith(endpoint, {
+ input: { duration: '8s', prompt: 'p' },
+ });
+ });
+
+ it('sends the request as built when the schema cannot be loaded', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('network down')));
+ queue.submit.mockResolvedValue({ request_id: 'req-5' });
+
+ await runtime.createVideo({
+ model: 'someone/custom-video',
+ params: { duration: 5, prompt: 'p' },
+ });
+
+ expect(queue.submit).toHaveBeenCalledWith('someone/custom-video', {
+ input: { duration: 5, prompt: 'p' },
+ });
+ });
});
it('maps a 401 submit error to InvalidProviderAPIKey', async () => {
@@ -241,6 +321,16 @@ describe('LobeFalAI video', () => {
});
});
+ it('reads the first entry of a videos array', async () => {
+ queue.status.mockResolvedValue({ status: 'COMPLETED' });
+ queue.result.mockResolvedValue({ data: { videos: [{ url: 'https://v/1.mp4' }] } });
+
+ await expect(runtime.handlePollVideoStatus(inferenceId)).resolves.toEqual({
+ status: 'success',
+ videoUrl: 'https://v/1.mp4',
+ });
+ });
+
it('fails when the result has no video', async () => {
queue.status.mockResolvedValue({ status: 'COMPLETED' });
queue.result.mockResolvedValue({ data: {} });
diff --git a/packages/model-runtime/src/providers/fal/createVideo.ts b/packages/model-runtime/src/providers/fal/createVideo.ts
index c055f63e6dc..6087309344b 100644
--- a/packages/model-runtime/src/providers/fal/createVideo.ts
+++ b/packages/model-runtime/src/providers/fal/createVideo.ts
@@ -4,6 +4,8 @@ import type { RuntimeVideoGenParams } from 'model-bank';
import { getVideoReferenceImages } from '../../core/usageConverters/utils/computeVideoCost';
import type { CreateVideoResult, PollVideoStatusResult } from '../../types/video';
+import type { FalJsonSchema } from './schema';
+import { coerceFalInput } from './schema';
const log = debug('lobe-video:fal');
@@ -44,7 +46,14 @@ const FAL_VIDEO_MODELS: Record<string, FalVideoModelSpec> = {
*/
const REQUEST_PATH_SEPARATOR = '/requests/';
-export const isFalVideoModel = (model: string) => Object.hasOwn(FAL_VIDEO_MODELS, model);
+/** Video model cards whose task endpoint the runtime picks from the request params */
+export const isFalTaskRoutedVideoModel = (model: string) => Object.hasOwn(FAL_VIDEO_MODELS, model);
+
+const FAL_VIDEO_TASKS = ['text-to-video', 'image-to-video', 'reference-to-video'] as const;
+
+/** fal endpoints a task-routed video card sends requests to; empty for any other model */
+export const getFalTaskRoutedVideoEndpoints = (model: string) =>
+ isFalTaskRoutedVideoModel(model) ? FAL_VIDEO_TASKS.map((task) => `${model}/${task}`) : [];
export const toFalVideoInferenceId = (appId: string, requestId: string) =>
`${appId}${REQUEST_PATH_SEPARATOR}${requestId}`;
@@ -67,7 +76,7 @@ export const parseFalVideoInferenceId = (inferenceId: string) => {
* - otherwise → `/text-to-video`
*/
export const buildFalVideoRequest = (model: string, params: RuntimeVideoGenParams) => {
- const spec = isFalVideoModel(model) ? FAL_VIDEO_MODELS[model] : undefined;
+ const spec = isFalTaskRoutedVideoModel(model) ? FAL_VIDEO_MODELS[model] : undefined;
if (!spec) throw new Error(`Unsupported fal video model: ${model}`);
const { aspectRatio, duration, endImageUrl, imageUrl, imageUrls, prompt, resolution, seed } =
@@ -78,7 +87,7 @@ export const buildFalVideoRequest = (model: string, params: RuntimeVideoGenParam
if (resolution) input.resolution = resolution;
if (typeof seed === 'number' && seed >= 0) input.seed = seed;
- let task: 'image-to-video' | 'reference-to-video' | 'text-to-video';
+ let task: (typeof FAL_VIDEO_TASKS)[number];
if (imageUrls?.length) {
task = 'reference-to-video';
// Shared with pricing so the billed reference tokens cover every image sent
@@ -100,6 +109,37 @@ export const buildFalVideoRequest = (model: string, params: RuntimeVideoGenParam
return { endpoint: `${model}/${task}`, input };
};
+/**
+ * Build the input of any other fal video endpoint, whose id already names its task (e.g.
+ * `fal-ai/kling-video/v2.1/master/image-to-video`). Fields use fal's common names; the caller
+ * fits them to the endpoint's schema with `coerceFalInput`.
+ */
+export const buildGenericFalVideoInput = (params: RuntimeVideoGenParams) => {
+ const {
+ aspectRatio,
+ duration,
+ endImageUrl,
+ generateAudio,
+ imageUrl,
+ imageUrls,
+ prompt,
+ resolution,
+ seed,
+ } = params;
+
+ const input: Record<string, unknown> = { prompt };
+ if (aspectRatio) input.aspect_ratio = aspectRatio;
+ if (duration) input.duration = duration;
+ if (resolution) input.resolution = resolution;
+ if (typeof seed === 'number' && seed >= 0) input.seed = seed;
+ if (imageUrl) input.image_url = imageUrl;
+ if (endImageUrl) input.end_image_url = endImageUrl;
+ if (imageUrls?.length) input.image_urls = imageUrls;
+ if (typeof generateAudio === 'boolean') input.generate_audio = generateAudio;
+
+ return input;
+};
+
const getFalErrorMessage = (error: unknown): string => {
const detail = (error as { body?: { detail?: unknown } } | undefined)?.body?.detail;
if (typeof detail === 'string') return detail;
@@ -117,12 +157,22 @@ export const createFalVideo = async (
client: FalClient,
model: string,
params: RuntimeVideoGenParams,
+ loadInputSchema?: (endpoint: string) => Promise<FalJsonSchema | undefined>,
): Promise<CreateVideoResult> => {
- const { endpoint, input } = buildFalVideoRequest(model, params);
+ let endpoint: string;
+ let input: Record<string, unknown>;
+
+ if (isFalTaskRoutedVideoModel(model)) {
+ ({ endpoint, input } = buildFalVideoRequest(model, params));
+ } else {
+ endpoint = model;
+ input = coerceFalInput(buildGenericFalVideoInput(params), await loadInputSchema?.(endpoint));
+ }
log('Submitting fal video request to %s with input: %O', endpoint, input);
const { request_id } = await client.queue.submit(endpoint, { input });
+ // Status and result URLs only use `<owner>/<app>`, so a full endpoint id also works as app id
return { inferenceId: toFalVideoInferenceId(model, request_id) };
};
@@ -144,7 +194,8 @@ export const pollFalVideoStatus = async (
return { error: getFalErrorMessage(error), status: 'failed' };
}
- const videoUrl = (data as { video?: { url?: string } } | undefined)?.video?.url;
+ const output = data as { video?: { url?: string }; videos?: { url?: string }[] } | undefined;
+ const videoUrl = output?.video?.url ?? output?.videos?.[0]?.url;
if (!videoUrl) return { error: 'fal returned no video', status: 'failed' };
return { status: 'success', videoUrl };
diff --git a/packages/model-runtime/src/providers/fal/endpoint.test.ts b/packages/model-runtime/src/providers/fal/endpoint.test.ts
new file mode 100644
index 00000000000..ae9837a6ca8
--- /dev/null
+++ b/packages/model-runtime/src/providers/fal/endpoint.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, it } from 'vitest';
+
+import { resolveFalEndpointId, resolveFalImageEndpoint } from './endpoint';
+
+describe('resolveFalEndpointId', () => {
+ it.each([
+ // Endpoints outside the `fal-ai/` namespace are used verbatim
+ ['bytedance/seedance-2.5', 'bytedance/seedance-2.5'],
+ ['black-forest-labs/flux-2-pro', 'black-forest-labs/flux-2-pro'],
+ ['openai/gpt-image-1/text-to-image', 'openai/gpt-image-1/text-to-image'],
+ ['someone/my-app/variant', 'someone/my-app/variant'],
+ // fal serves newer Seedream releases under the top-level bytedance owner
+ ['bytedance/seedream/v5/flash/edit', 'bytedance/seedream/v5/flash/edit'],
+ ['fal-ai/flux/dev', 'fal-ai/flux/dev'],
+ // Bare and legacy short ids keep resolving to fal-ai
+ ['nano-banana', 'fal-ai/nano-banana'],
+ ['flux/dev', 'fal-ai/flux/dev'],
+ ['bytedance/seedream/v4', 'fal-ai/bytedance/seedream/v4'],
+ [' /fal-ai/flux/dev/ ', 'fal-ai/flux/dev'],
+ ])('resolves %s to %s', (model, endpoint) => {
+ expect(resolveFalEndpointId(model)).toBe(endpoint);
+ });
+});
+
+describe('resolveFalImageEndpoint', () => {
+ it('adds the task path to one-card families', () => {
+ expect(resolveFalImageEndpoint('fal-ai/bytedance/seedream/v4.5', false)).toBe(
+ 'fal-ai/bytedance/seedream/v4.5/text-to-image',
+ );
+ expect(resolveFalImageEndpoint('fal-ai/bytedance/seedream/v4.5', true)).toBe(
+ 'fal-ai/bytedance/seedream/v4.5/edit',
+ );
+ });
+
+ it('does not add a second task path to an endpoint that already names one', () => {
+ expect(resolveFalImageEndpoint('fal-ai/bytedance/seedream/v4.5/edit', true)).toBe(
+ 'fal-ai/bytedance/seedream/v4.5/edit',
+ );
+ expect(resolveFalImageEndpoint('fal-ai/hunyuan-image/v3/text-to-image', false)).toBe(
+ 'fal-ai/hunyuan-image/v3/text-to-image',
+ );
+ });
+});
diff --git a/packages/model-runtime/src/providers/fal/endpoint.ts b/packages/model-runtime/src/providers/fal/endpoint.ts
new file mode 100644
index 00000000000..8111affda8b
--- /dev/null
+++ b/packages/model-runtime/src/providers/fal/endpoint.ts
@@ -0,0 +1,57 @@
+/**
+ * Short ids saved before model cards carried fal's `fal-ai/` namespace (e.g. `flux/dev`). Any
+ * other id with a `/` is a full fal endpoint id (`bytedance/seedance-2.5`,
+ * `black-forest-labs/flux-2`, `<user>/<app>`) and is used verbatim.
+ */
+const LEGACY_SHORT_ID_PREFIXES = ['flux/', 'flux-kontext/', 'flux-pro/', 'hunyuan-image/', 'imagen4/'];
+
+/**
+ * Legacy short ids under an owner fal also uses at the top level: `bytedance/seedream/v4` meant
+ * `fal-ai/bytedance/seedream/v4`, while newer releases live at `bytedance/seedream/v5/...`, so
+ * only these exact ids are rewritten.
+ */
+const LEGACY_SHORT_IDS = new Set(['bytedance/seedream/v4', 'bytedance/seedream/v4.5']);
+
+/**
+ * Model families exposed as one card but served by separate fal endpoints: requests with
+ * reference images go to `/edit`, others to `/text-to-image`. Only the family root matches, so
+ * an id that already names its task (e.g. `.../v4/edit`) is sent as is.
+ */
+const EDIT_OR_TEXT_TO_IMAGE_FAMILIES = [
+ /^fal-ai\/bytedance\/seedream\/v[\d.]+$/,
+ /^fal-ai\/hunyuan-image\/v[\d.]+$/,
+ /^alibaba\/qwen-image-3$/,
+];
+
+/** Image cards whose `/edit` endpoint serves requests with reference images */
+const EDIT_WITH_IMAGES_MODELS = new Set(['fal-ai/nano-banana']);
+
+/**
+ * Turn a model id into the fal endpoint id it runs on. fal endpoint ids are always
+ * `<owner>/<app>[/<path>]`, so only a bare id (no `/`) or a legacy short id gets `fal-ai/`.
+ */
+export const resolveFalEndpointId = (model: string) => {
+ const id = model.trim().replaceAll(/^\/+|\/+$/g, '');
+
+ if (!id.includes('/')) return `fal-ai/${id}`;
+ if (LEGACY_SHORT_IDS.has(id)) return `fal-ai/${id}`;
+ if (LEGACY_SHORT_ID_PREFIXES.some((prefix) => id.startsWith(prefix))) return `fal-ai/${id}`;
+
+ return id;
+};
+
+/** fal endpoint for an image request, adding the task path for one-card model families */
+export const resolveFalImageEndpoint = (model: string, hasImageUrls: boolean) => {
+ const endpoint = resolveFalEndpointId(model);
+
+ if (EDIT_OR_TEXT_TO_IMAGE_FAMILIES.some((family) => family.test(endpoint))) {
+ return `${endpoint}/${hasImageUrls ? 'edit' : 'text-to-image'}`;
+ }
+ if (EDIT_WITH_IMAGES_MODELS.has(endpoint) && hasImageUrls) return `${endpoint}/edit`;
+
+ return endpoint;
+};
+
+/** Families billed by output resolution tier, whose `resolution` preset becomes an image size */
+export const isFalResolutionTierEndpoint = (endpoint: string) =>
+ endpoint.startsWith('alibaba/qwen-image-3/');
diff --git a/packages/model-runtime/src/providers/fal/index.test.ts b/packages/model-runtime/src/providers/fal/index.test.ts
index e7ef8c5c428..5596939cc2e 100644
--- a/packages/model-runtime/src/providers/fal/index.test.ts
+++ b/packages/model-runtime/src/providers/fal/index.test.ts
@@ -3,6 +3,7 @@ import { fal } from '@fal-ai/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { CreateImagePayload } from '../../types';
+import { clearFalInputSchemaCache } from './catalog';
import { LobeFalAI, resolveFalImageSize } from './index';
// Mock the fal client
@@ -28,11 +29,19 @@ let instance: LobeFalAI;
beforeEach(() => {
vi.clearAllMocks();
+ clearFalInputSchemaCache();
+ // Endpoints outside the built-in cards look up their input schema; keep that lookup off
+ // fal's real catalog API, where rate limiting retries outlast the test timeout.
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => new Response('{}', { status: 500 })),
+ );
instance = new LobeFalAI({ apiKey: 'test-api-key' });
});
afterEach(() => {
vi.clearAllMocks();
+ vi.unstubAllGlobals();
});
describe('LobeFalAI', () => {
diff --git a/packages/model-runtime/src/providers/fal/index.ts b/packages/model-runtime/src/providers/fal/index.ts
index 676ec59677c..c31d3ffcb46 100644
--- a/packages/model-runtime/src/providers/fal/index.ts
+++ b/packages/model-runtime/src/providers/fal/index.ts
@@ -1,4 +1,5 @@
import { createFalClient, fal, type FalClient } from '@fal-ai/client';
+import type { ChatModelCard } from '@lobechat/types';
import debug from 'debug';
import { pick } from 'es-toolkit/compat';
import type { RuntimeImageGenParamsValue } from 'model-bank';
@@ -16,28 +17,29 @@ import type {
import { AgentRuntimeError } from '../../utils/createError';
import type { ModelIdMappingOptions } from '../../utils/modelIdMapping';
import { resolveMappedModelId } from '../../utils/modelIdMapping';
-import { createFalVideo, isFalVideoModel, pollFalVideoStatus } from './createVideo';
+import { getFalInputSchema, listFalGenerationModels } from './catalog';
+import {
+ createFalVideo,
+ getFalTaskRoutedVideoEndpoints,
+ pollFalVideoStatus,
+} from './createVideo';
+import {
+ isFalResolutionTierEndpoint,
+ resolveFalEndpointId,
+ resolveFalImageEndpoint,
+} from './endpoint';
+import { coerceFalInput } from './schema';
// Create debug logger
const log = debug('lobe-image:fal');
-type FluxDevOutput = Awaited<ReturnType<typeof fal.subscribe<'fal-ai/flux/dev'>>>['data'];
-
-/**
- * fal hosts models under several namespaces (e.g. `alibaba/qwen-image-3`); only bare
- * model ids without a known namespace get the default `fal-ai/` prefix.
- */
-const FAL_NAMESPACES = ['fal-ai/', 'alibaba/', 'minimax/'];
+interface FalImageOutput {
+ image?: { height?: number; url: string; width?: number };
+ images?: { height?: number; url: string; width?: number }[];
+}
-/**
- * Model families exposed as one card but served by separate fal endpoints: requests
- * with reference images go to `/edit`, others to `/text-to-image`.
- */
-const EDIT_OR_TEXT_TO_IMAGE_ENDPOINT_PREFIXES = [
- 'fal-ai/bytedance/seedream/v',
- 'fal-ai/hunyuan-image/v',
- 'alibaba/qwen-image-3',
-];
+/** fal endpoints that run faster with `acceleration: 'high'` at no quality cost */
+const ACCELERATED_BY_DEFAULT_ENDPOINTS = new Set(['fal-ai/flux/krea']);
/**
* Long edge of a square image for each `resolution` preset. fal bills some models
@@ -76,6 +78,24 @@ export const resolveFalImageSize = (
return { height: roundDown(ratioHeight * scale), width: roundDown(ratioWidth * scale) };
};
+/**
+ * fal endpoints served by the built-in cards: each card's id plus the task endpoints its one-card
+ * family routes to (e.g. `fal-ai/bytedance/seedream/v4/edit`). The catalog copies of these are
+ * duplicates without the curated parameters and pricing.
+ */
+const loadBuiltinFalEndpoints = async () => {
+ const { default: builtinModels } = await import('model-bank/fal');
+
+ return new Set(
+ builtinModels.flatMap(({ id }) => [
+ id,
+ resolveFalImageEndpoint(id, false),
+ resolveFalImageEndpoint(id, true),
+ ...getFalTaskRoutedVideoEndpoints(id),
+ ]),
+ );
+};
+
// https://docs.fal.ai/model-apis/errors/
const toFalRuntimeError = (error: unknown) => {
if (error instanceof Error && 'status' in error && error.status === 401) {
@@ -109,6 +129,7 @@ export class LobeFalAI implements LobeRuntimeAI {
* submitting a request and polling it.
*/
private readonly client: FalClient;
+ private readonly apiKey: string;
// OpenAI SDK v6 widened `apiKey` to `string | ApiKeySetter`; lobehub only uses the string form.
constructor({
@@ -120,6 +141,7 @@ export class LobeFalAI implements LobeRuntimeAI {
fal.config({
credentials: apiKey,
});
+ this.apiKey = apiKey;
this.client = createFalClient({ credentials: apiKey });
this.modelIdMappingOptions = { modelIdMapping };
log('FalAI initialized with apiKey: %s', apiKey ? '*****' : 'Not set');
@@ -130,15 +152,14 @@ export class LobeFalAI implements LobeRuntimeAI {
}
async createVideo(payload: CreateVideoPayload): Promise<CreateVideoResult> {
- const requestModel = resolveMappedModelId(payload.model, this.modelIdMappingOptions);
- if (!isFalVideoModel(requestModel)) {
- throw AgentRuntimeError.createError(AgentRuntimeErrorType.ProviderBizError, {
- message: `Video generation is not supported for fal model: ${requestModel}`,
- });
- }
+ const requestModel = resolveFalEndpointId(
+ resolveMappedModelId(payload.model, this.modelIdMappingOptions),
+ );
try {
- return await createFalVideo(this.client, requestModel, payload.params);
+ return await createFalVideo(this.client, requestModel, payload.params, (endpoint) =>
+ getFalInputSchema(this.apiKey, endpoint),
+ );
} catch (error) {
throw toFalRuntimeError(error);
}
@@ -159,6 +180,7 @@ export class LobeFalAI implements LobeRuntimeAI {
['imageUrl', 'image_url'],
['imageUrls', 'image_urls'],
['size', 'image_size'],
+ ['aspectRatio', 'aspect_ratio'],
]);
const defaultInput: Record<string, unknown> = {
@@ -175,13 +197,20 @@ export class LobeFalAI implements LobeRuntimeAI {
.map(([key, value]) => [paramsMap.get(key) ?? key, value]),
);
- if (typeof userInput.resolution === 'string' && RESOLUTION_BASE_EDGE[userInput.resolution]) {
+ const hasImageUrls = (params.imageUrls?.length ?? 0) > 0;
+ const endpoint = resolveFalImageEndpoint(requestModel, hasImageUrls);
+
+ if (
+ isFalResolutionTierEndpoint(endpoint) &&
+ typeof userInput.resolution === 'string' &&
+ RESOLUTION_BASE_EDGE[userInput.resolution]
+ ) {
const imageSize = resolveFalImageSize(
- userInput.aspectRatio as string | undefined,
+ userInput.aspect_ratio as string | undefined,
userInput.resolution,
);
if (imageSize) userInput.image_size = imageSize;
- delete userInput.aspectRatio;
+ delete userInput.aspect_ratio;
delete userInput.resolution;
}
@@ -198,32 +227,26 @@ export class LobeFalAI implements LobeRuntimeAI {
}
}
- const modelsAcceleratedByDefault = new Set<string>(['flux/krea']);
- if (modelsAcceleratedByDefault.has(requestModel)) {
+ if (ACCELERATED_BY_DEFAULT_ENDPOINTS.has(endpoint)) {
defaultInput['acceleration'] = 'high';
}
- let endpoint = FAL_NAMESPACES.some((namespace) => requestModel.startsWith(namespace))
- ? requestModel
- : `fal-ai/${requestModel}`;
- const hasImageUrls = (params.imageUrls?.length ?? 0) > 0;
- if (EDIT_OR_TEXT_TO_IMAGE_ENDPOINT_PREFIXES.some((m) => endpoint.startsWith(m))) {
- endpoint += hasImageUrls ? '/edit' : '/text-to-image';
- } else if (endpoint === 'fal-ai/nano-banana' && hasImageUrls) {
- endpoint += '/edit';
- }
-
- const finalInput = {
- ...defaultInput,
- ...userInput,
- };
+ const builtinEndpoints = await loadBuiltinFalEndpoints();
+ const input = { ...defaultInput, ...userInput };
+ // Fetched endpoints only accept the fields their schema declares; built-in cards send the
+ // curated input as is
+ const finalInput = builtinEndpoints.has(endpoint)
+ ? input
+ : coerceFalInput(input, await getFalInputSchema(this.apiKey, endpoint));
log('Calling fal.subscribe with endpoint: %s and input: %O', endpoint, finalInput);
try {
const { data } = await fal.subscribe(endpoint, {
input: finalInput,
});
- const image = (data as FluxDevOutput).images[0];
+ const output = data as FalImageOutput;
+ const image = output.images?.[0] ?? output.image;
+ if (!image?.url) throw new Error(`fal returned no image for ${endpoint}`);
return {
imageUrl: image.url,
@@ -233,4 +256,27 @@ export class LobeFalAI implements LobeRuntimeAI {
throw toFalRuntimeError(error);
}
}
+
+ /**
+ * List fal's image and video endpoints with parameters derived from their input schemas, so any
+ * endpoint (any owner, not only `fal-ai/`) can be enabled on the generation pages. Endpoints of
+ * built-in cards are skipped: they are already listed with curated parameters and pricing.
+ */
+ async models(): Promise<ChatModelCard[]> {
+ const builtinEndpoints = await loadBuiltinFalEndpoints();
+
+ try {
+ const models = await listFalGenerationModels(this.apiKey);
+
+ return models
+ .filter((model) => !builtinEndpoints.has(model.id))
+ .map(({ parameters, ...model }) => ({
+ ...model,
+ enabled: false,
+ parameters: parameters as ChatModelCard['parameters'],
+ }));
+ } catch (error) {
+ throw toFalRuntimeError(error);
+ }
+ }
}
diff --git a/packages/model-runtime/src/providers/fal/models.test.ts b/packages/model-runtime/src/providers/fal/models.test.ts
new file mode 100644
index 00000000000..ee21a9a3624
--- /dev/null
+++ b/packages/model-runtime/src/providers/fal/models.test.ts
@@ -0,0 +1,338 @@
+// @vitest-environment node
+import { fal } from '@fal-ai/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { clearFalInputSchemaCache, FAL_INPUT_SCHEMA_TTL_MS, getFalInputSchema } from './catalog';
+import { LobeFalAI } from './index';
+import { buildFalCatalogResponse, buildFalOpenAPI } from './testUtils';
+
+vi.mock('@fal-ai/client', () => ({
+ createFalClient: vi.fn(() => ({})),
+ fal: { config: vi.fn(), subscribe: vi.fn() },
+}));
+
+const mockFal = vi.mocked(fal);
+
+let instance: LobeFalAI;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ clearFalInputSchemaCache();
+ // No test reaches fal's real catalog API; tests that need a schema stub their own
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => new Response('{}', { status: 500 })),
+ );
+ instance = new LobeFalAI({ apiKey: 'test-api-key' });
+ mockFal.subscribe.mockResolvedValue({
+ data: { images: [{ url: 'https://example.com/out.png' }] },
+ requestId: 'r',
+ } as any);
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+/** Serve one endpoint's input schema from the catalog, or fail when no properties are given */
+const stubInputSchema = (endpointId: string, properties?: Record<string, any>) => {
+ const fetchMock = vi.fn(async () =>
+ properties
+ ? new Response(JSON.stringify(buildFalCatalogResponse(endpointId, properties)))
+ : new Response('{}', { status: 500 }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ return fetchMock;
+};
+
+describe('LobeFalAI createImage with any fal endpoint', () => {
+ it('sends endpoints from other owners verbatim', async () => {
+ stubInputSchema('black-forest-labs/flux-2-pro');
+
+ await instance.createImage({
+ model: 'black-forest-labs/flux-2-pro',
+ params: { prompt: 'a fox' },
+ });
+
+ expect(mockFal.subscribe).toHaveBeenCalledWith('black-forest-labs/flux-2-pro', {
+ input: { enable_safety_checker: false, num_images: 1, prompt: 'a fox' },
+ });
+ });
+
+ it('sends the aspect ratio under the field fal reads', async () => {
+ await instance.createImage({
+ model: 'fal-ai/flux-pro/kontext',
+ params: { aspectRatio: '16:9', prompt: 'a fox' },
+ });
+
+ expect(mockFal.subscribe).toHaveBeenCalledWith('fal-ai/flux-pro/kontext', {
+ input: expect.objectContaining({ aspect_ratio: '16:9' }),
+ });
+ });
+
+ it('passes a native resolution through instead of converting it to a size', async () => {
+ await instance.createImage({
+ model: 'fal-ai/nano-banana-pro',
+ params: { aspectRatio: '1:1', prompt: 'a fox', resolution: '2K' },
+ });
+
+ expect(mockFal.subscribe).toHaveBeenCalledWith('fal-ai/nano-banana-pro', {
+ input: expect.objectContaining({ aspect_ratio: '1:1', resolution: '2K' }),
+ });
+ });
+
+ it('accelerates FLUX Krea by its full endpoint id', async () => {
+ await instance.createImage({ model: 'fal-ai/flux/krea', params: { prompt: 'a fox' } });
+
+ expect(mockFal.subscribe).toHaveBeenCalledWith('fal-ai/flux/krea', {
+ input: expect.objectContaining({ acceleration: 'high' }),
+ });
+ });
+
+ it('sends a fetched endpoint only the fields its schema declares', async () => {
+ const fetchMock = stubInputSchema('someone/prompt-only', { prompt: { type: 'string' } });
+
+ await instance.createImage({ model: 'someone/prompt-only', params: { prompt: 'a fox' } });
+
+ expect(mockFal.subscribe).toHaveBeenCalledWith('someone/prompt-only', {
+ input: { prompt: 'a fox' },
+ });
+ expect((fetchMock.mock.calls[0] as unknown as [URL])[0].searchParams.get('endpoint_id')).toBe(
+ 'someone/prompt-only',
+ );
+ });
+
+ it('sends built-in cards their curated input without loading a schema', async () => {
+ const fetchMock = stubInputSchema('fal-ai/flux/schnell', { prompt: { type: 'string' } });
+
+ await instance.createImage({ model: 'fal-ai/flux/schnell', params: { prompt: 'a fox' } });
+
+ expect(mockFal.subscribe).toHaveBeenCalledWith('fal-ai/flux/schnell', {
+ input: { enable_safety_checker: false, num_images: 1, prompt: 'a fox' },
+ });
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('reads a single `image` output', async () => {
+ stubInputSchema('fal-ai/some-upscaler');
+
+ mockFal.subscribe.mockResolvedValue({
+ data: { image: { height: 512, url: 'https://example.com/one.png', width: 512 } },
+ requestId: 'r',
+ } as any);
+
+ await expect(
+ instance.createImage({ model: 'fal-ai/some-upscaler', params: { prompt: 'p' } }),
+ ).resolves.toEqual({ height: 512, imageUrl: 'https://example.com/one.png', width: 512 });
+ });
+});
+
+describe('LobeFalAI models', () => {
+ const catalogModel = (
+ endpointId: string,
+ category: string,
+ properties: Record<string, any>,
+ metadata: Record<string, unknown> = {},
+ ) => ({
+ endpoint_id: endpointId,
+ metadata: { category, display_name: `${endpointId} name`, ...metadata },
+ openapi: buildFalOpenAPI(endpointId, properties),
+ });
+
+ // fal rejects pages above 10 models when OpenAPI schemas are expanded
+ const rejectsLargePages = (url: URL) =>
+ url.searchParams.get('expand') === 'openapi-3.0' && Number(url.searchParams.get('limit')) > 10
+ ? new Response('{"error":{"type":"validation_error"}}', { status: 400 })
+ : undefined;
+
+ const stubCatalog = (pages: Record<string, any[]>) => {
+ const fetchMock = vi.fn(async (url: URL) => {
+ const rejected = rejectsLargePages(url);
+ if (rejected) return rejected;
+ const category = url.searchParams.get('category') ?? '';
+ return new Response(
+ JSON.stringify({ has_more: false, models: pages[category] ?? [], next_cursor: null }),
+ );
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ return fetchMock;
+ };
+
+ it('lists image and video endpoints of any owner with derived parameters', async () => {
+ const fetchMock = stubCatalog({
+ 'image-to-video': [
+ catalogModel('bytedance/seedance-2.5/image-to-video', 'image-to-video', {
+ image_url: { type: 'string' },
+ prompt: { type: 'string' },
+ }),
+ catalogModel('fal-ai/kling-video/v2.1/standard/image-to-video', 'image-to-video', {
+ duration: { default: '5', enum: ['5', '10'], type: 'string' },
+ image_url: { type: 'string' },
+ prompt: { type: 'string' },
+ }),
+ ],
+ 'text-to-image': [
+ catalogModel(
+ 'black-forest-labs/flux-2-pro',
+ 'text-to-image',
+ {
+ aspect_ratio: { default: '1:1', enum: ['1:1', '16:9'], type: 'string' },
+ prompt: { type: 'string' },
+ },
+ { date: '2026-05-01T10:00:00Z', description: ' Flux 2 ' },
+ ),
+ // Built-in cards keep their curated parameters, so the catalog copy is skipped
+ catalogModel('fal-ai/flux/schnell', 'text-to-image', { prompt: { type: 'string' } }),
+ // Task endpoints a built-in one-card family routes to are duplicates of that card
+ catalogModel('fal-ai/bytedance/seedream/v4/edit', 'text-to-image', {
+ prompt: { type: 'string' },
+ }),
+ // Upscalers and other prompt-less endpoints cannot be driven by the generation page
+ catalogModel('fal-ai/upscaler', 'text-to-image', { image_url: { type: 'string' } }),
+ catalogModel(
+ 'fal-ai/flux-lora-trainer',
+ 'text-to-image',
+ { prompt: { type: 'string' } },
+ { kind: 'training' },
+ ),
+ ],
+ });
+
+ const models = await instance.models();
+
+ expect(models).toEqual([
+ {
+ description: 'Flux 2',
+ displayName: 'black-forest-labs/flux-2-pro name',
+ enabled: false,
+ id: 'black-forest-labs/flux-2-pro',
+ parameters: {
+ aspectRatio: { default: '1:1', enum: ['1:1', '16:9'] },
+ prompt: { default: '' },
+ },
+ releasedAt: '2026-05-01',
+ type: 'image',
+ },
+ {
+ description: undefined,
+ displayName: 'fal-ai/kling-video/v2.1/standard/image-to-video name',
+ enabled: false,
+ id: 'fal-ai/kling-video/v2.1/standard/image-to-video',
+ parameters: {
+ duration: { default: 5, enum: [5, 10] },
+ imageUrl: { default: null },
+ prompt: { default: '' },
+ },
+ type: 'video',
+ },
+ ]);
+
+ const url = fetchMock.mock.calls[0][0] as URL;
+ expect(url.searchParams.get('expand')).toBe('openapi-3.0');
+ expect(url.searchParams.get('status')).toBe('active');
+ expect(fetchMock.mock.calls[0][1]).toMatchObject({
+ headers: { Authorization: 'Key test-api-key' },
+ });
+ });
+
+ it('follows the catalog cursor', async () => {
+ const fetchMock = vi.fn(async (url: URL) => {
+ const rejected = rejectsLargePages(url);
+ if (rejected) return rejected;
+ const category = url.searchParams.get('category');
+ if (category !== 'text-to-image') {
+ return new Response(JSON.stringify({ has_more: false, models: [] }));
+ }
+ const cursor = url.searchParams.get('cursor');
+ const model = catalogModel(cursor ? 'b/second' : 'a/first', 'text-to-image', {
+ prompt: { type: 'string' },
+ });
+ return new Response(
+ JSON.stringify({
+ has_more: !cursor,
+ models: [model],
+ next_cursor: cursor ? null : 'page-2',
+ }),
+ );
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ const models = await instance.models();
+
+ expect(models.map((model) => model.id)).toEqual(['a/first', 'b/second']);
+ });
+
+ it('retries rate-limited pages and keeps listed pages when a later page fails', async () => {
+ const calls: string[] = [];
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async (url: URL) => {
+ const rejected = rejectsLargePages(url);
+ if (rejected) return rejected;
+ const category = url.searchParams.get('category');
+ const cursor = url.searchParams.get('cursor');
+ calls.push(`${category}:${cursor ?? 'first'}`);
+ if (category === 'text-to-image') {
+ if (!cursor) {
+ return new Response(
+ JSON.stringify({
+ has_more: true,
+ models: [catalogModel('a/first', 'text-to-image', { prompt: { type: 'string' } })],
+ next_cursor: 'page-2',
+ }),
+ );
+ }
+ // The second page keeps failing: the first page must survive
+ return new Response('{}', { status: 500 });
+ }
+ if (
+ category === 'text-to-video' &&
+ calls.filter((c) => c.startsWith('text-to-video')).length === 1
+ ) {
+ return new Response('{}', { headers: { 'retry-after': '0' }, status: 429 });
+ }
+ return new Response(
+ JSON.stringify({
+ has_more: false,
+ models:
+ category === 'text-to-video'
+ ? [catalogModel('b/video', 'text-to-video', { prompt: { type: 'string' } })]
+ : [],
+ }),
+ );
+ }),
+ );
+
+ const models = await instance.models();
+
+ expect(models.map((model) => model.id)).toEqual(['a/first', 'b/video']);
+ expect(calls.filter((call) => call.startsWith('text-to-video'))).toHaveLength(2);
+ });
+
+ it('throws InvalidProviderAPIKey when every catalog request is unauthorized', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => new Response('{}', { status: 401 })),
+ );
+
+ await expect(instance.models()).rejects.toMatchObject({
+ errorType: 'InvalidProviderAPIKey',
+ });
+ });
+});
+
+describe('getFalInputSchema', () => {
+ it('refetches a cached schema once it expires', async () => {
+ const now = vi.spyOn(Date, 'now').mockReturnValue(1_000);
+ const fetchMock = stubInputSchema('a/app', { prompt: { type: 'string' } });
+
+ await getFalInputSchema('key', 'a/app');
+ await getFalInputSchema('key', 'a/app');
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+
+ now.mockReturnValue(1_000 + FAL_INPUT_SCHEMA_TTL_MS + 1);
+ await getFalInputSchema('key', 'a/app');
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/packages/model-runtime/src/providers/fal/schema.test.ts b/packages/model-runtime/src/providers/fal/schema.test.ts
new file mode 100644
index 00000000000..42504671ffd
--- /dev/null
+++ b/packages/model-runtime/src/providers/fal/schema.test.ts
@@ -0,0 +1,188 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import {
+ coerceFalInput,
+ extractFalInputSchema,
+ falInputSchemaToImageParameters,
+ falInputSchemaToVideoParameters,
+} from './schema';
+import { buildFalOpenAPI } from './testUtils';
+
+const IMAGE_SIZE = {
+ anyOf: [
+ { $ref: '#/components/schemas/ImageSize' },
+ {
+ enum: ['square_hd', 'square', 'landscape_4_3', 'landscape_16_9', 'auto_2K'],
+ type: 'string',
+ },
+ ],
+ default: { height: 2048, width: 2048 },
+};
+
+describe('extractFalInputSchema', () => {
+ it('resolves the submit operation body and inlines property refs', () => {
+ const openapi = buildFalOpenAPI('fal-ai/flux/dev', {
+ image_size: IMAGE_SIZE,
+ prompt: { type: 'string' },
+ });
+ (openapi.components.schemas as Record<string, unknown>).ImageSize = {
+ properties: { height: { type: 'integer' }, width: { type: 'integer' } },
+ type: 'object',
+ };
+
+ const input = extractFalInputSchema(openapi, 'fal-ai/flux/dev');
+
+ expect(input?.required).toEqual(['prompt']);
+ expect(input?.properties?.image_size.anyOf?.[0]).toMatchObject({
+ properties: { width: { type: 'integer' } },
+ type: 'object',
+ });
+ });
+
+ it('returns undefined for a schema expansion error', () => {
+ expect(
+ extractFalInputSchema({ error: { code: 'x', message: 'y' } }, 'fal-ai/flux/dev'),
+ ).toBeUndefined();
+ });
+});
+
+describe('falInputSchemaToImageParameters', () => {
+ it('maps fal fields to the parameters the runtime sends', () => {
+ expect(
+ falInputSchemaToImageParameters({
+ properties: {
+ guidance_scale: { default: 3.5, maximum: 20, minimum: 1, type: 'number' },
+ image_size: IMAGE_SIZE,
+ image_urls: { items: { type: 'string' }, maxItems: 10, type: 'array' },
+ num_inference_steps: { default: 28, maximum: 50, minimum: 1, type: 'integer' },
+ output_format: { enum: ['jpeg', 'png'], type: 'string' },
+ prompt: { type: 'string' },
+ seed: { anyOf: [{ type: 'integer' }, { type: 'null' }] },
+ },
+ }),
+ ).toEqual({
+ cfg: { default: 3.5, max: 20, min: 1, step: 0.1 },
+ imageUrls: { default: [], maxCount: 10 },
+ prompt: { default: '' },
+ // An object default is not selectable, so an `auto` preset wins over the first value
+ size: {
+ default: 'auto_2K',
+ enum: ['square_hd', 'square', 'landscape_4_3', 'landscape_16_9', 'auto_2K'],
+ },
+ seed: { default: null },
+ steps: { default: 28, max: 50, min: 1, step: 1 },
+ });
+ });
+
+ it('exposes aspect ratio and resolution enums', () => {
+ expect(
+ falInputSchemaToImageParameters({
+ properties: {
+ aspect_ratio: { default: '16:9', enum: ['1:1', '16:9'], type: 'string' },
+ image_url: { type: 'string' },
+ prompt: { type: 'string' },
+ resolution: { enum: ['1K', '2K', '4K'], type: 'string' },
+ },
+ }),
+ ).toEqual({
+ aspectRatio: { default: '16:9', enum: ['1:1', '16:9'] },
+ imageUrl: { default: null },
+ prompt: { default: '' },
+ resolution: { default: '1K', enum: ['1K', '2K', '4K'] },
+ });
+ });
+
+ it('skips endpoints without a prompt', () => {
+ expect(
+ falInputSchemaToImageParameters({ properties: { image_url: { type: 'string' } } }),
+ ).toBeUndefined();
+ });
+
+ it('skips endpoints that require an input the runtime does not send', () => {
+ expect(
+ falInputSchemaToImageParameters({
+ properties: { control_image_url: { type: 'string' }, prompt: { type: 'string' } },
+ required: ['prompt', 'control_image_url'],
+ }),
+ ).toBeUndefined();
+ });
+
+ it('keeps endpoints whose required inputs are all exposed', () => {
+ expect(
+ falInputSchemaToImageParameters({
+ properties: { image_urls: { type: 'array' }, prompt: { type: 'string' } },
+ required: ['prompt', 'image_urls'],
+ }),
+ ).toEqual({ imageUrls: { default: [] }, prompt: { default: '' } });
+ });
+});
+
+describe('falInputSchemaToVideoParameters', () => {
+ it('turns string duration enums into numbers', () => {
+ expect(
+ falInputSchemaToVideoParameters({
+ properties: {
+ aspect_ratio: { default: '16:9', enum: ['16:9', '9:16'], type: 'string' },
+ duration: { default: '8s', enum: ['4s', '6s', '8s'], type: 'string' },
+ end_image_url: { type: 'string' },
+ generate_audio: { default: true, type: 'boolean' },
+ image_url: { type: 'string' },
+ prompt: { type: 'string' },
+ resolution: { default: '720p', enum: ['720p', '1080p'], type: 'string' },
+ seed: { anyOf: [{ type: 'integer' }, { type: 'null' }] },
+ },
+ }),
+ ).toEqual({
+ aspectRatio: { default: '16:9', enum: ['16:9', '9:16'] },
+ duration: { default: 8, enum: [4, 6, 8] },
+ endImageUrl: { default: null, requiresImageUrl: true },
+ generateAudio: { default: true },
+ imageUrl: { default: null },
+ prompt: { default: '' },
+ resolution: { default: '720p', enum: ['720p', '1080p'] },
+ seed: { default: null },
+ });
+ });
+
+ it('keeps numeric duration ranges', () => {
+ expect(
+ falInputSchemaToVideoParameters({
+ properties: {
+ duration: { default: 5, maximum: 15, minimum: 3, type: 'integer' },
+ prompt: { type: 'string' },
+ },
+ })?.duration,
+ ).toEqual({ default: 5, max: 15, min: 3, step: 1 });
+ });
+
+ it('skips endpoints that require an input the runtime does not send', () => {
+ expect(
+ falInputSchemaToVideoParameters({
+ properties: { audio_url: { type: 'string' }, prompt: { type: 'string' } },
+ required: ['prompt', 'audio_url'],
+ }),
+ ).toBeUndefined();
+ });
+});
+
+describe('coerceFalInput', () => {
+ it('drops fields the endpoint does not declare and stringifies enum numbers', () => {
+ expect(
+ coerceFalInput(
+ { aspect_ratio: '16:9', duration: 6, prompt: 'p', seed: 3 },
+ {
+ properties: {
+ duration: { enum: ['4s', '6s'], type: 'string' },
+ prompt: { type: 'string' },
+ seed: { anyOf: [{ type: 'integer' }, { type: 'null' }] },
+ },
+ },
+ ),
+ ).toEqual({ duration: '6s', prompt: 'p', seed: 3 });
+ });
+
+ it('returns the input untouched without a schema', () => {
+ expect(coerceFalInput({ duration: 5 }, undefined)).toEqual({ duration: 5 });
+ });
+});
diff --git a/packages/model-runtime/src/providers/fal/schema.ts b/packages/model-runtime/src/providers/fal/schema.ts
new file mode 100644
index 00000000000..7da47cfa4a5
--- /dev/null
+++ b/packages/model-runtime/src/providers/fal/schema.ts
@@ -0,0 +1,375 @@
+import type { ModelParamsSchema, VideoModelParamsSchema } from 'model-bank';
+
+/**
+ * Subset of an OpenAPI 3.0 schema object as fal publishes it for model inputs.
+ */
+export interface FalJsonSchema {
+ $ref?: string;
+ allOf?: FalJsonSchema[];
+ anyOf?: FalJsonSchema[];
+ default?: unknown;
+ description?: string;
+ enum?: unknown[];
+ items?: FalJsonSchema;
+ maximum?: number;
+ maxItems?: number;
+ minimum?: number;
+ oneOf?: FalJsonSchema[];
+ properties?: Record<string, FalJsonSchema>;
+ required?: string[];
+ type?: string;
+}
+
+interface FalOpenAPIDocument {
+ components?: { schemas?: Record<string, FalJsonSchema> };
+ paths?: Record<
+ string,
+ {
+ post?: {
+ requestBody?: { content?: Record<string, { schema?: FalJsonSchema }> };
+ };
+ }
+ >;
+}
+
+const REF_PREFIX = '#/components/schemas/';
+
+const resolveRef = (doc: FalOpenAPIDocument, schema: FalJsonSchema | undefined, depth = 0) => {
+ let current = schema;
+ while (current?.$ref && depth < 10) {
+ const name = current.$ref.startsWith(REF_PREFIX) ? current.$ref.slice(REF_PREFIX.length) : '';
+ const target = doc.components?.schemas?.[name];
+ // Keep sibling keywords (e.g. `default`, `description`) next to the `$ref`
+ const { $ref: _ref, ...siblings } = current;
+ current = target ? { ...target, ...siblings } : undefined;
+ depth += 1;
+ }
+
+ return current;
+};
+
+/**
+ * Inline every `$ref` in a property schema, including the alternatives of `anyOf` / `oneOf` /
+ * `allOf`, so callers can read enums and bounds without the OpenAPI document.
+ */
+const inlineSchema = (
+ doc: FalOpenAPIDocument,
+ schema: FalJsonSchema | undefined,
+ depth = 0,
+): FalJsonSchema | undefined => {
+ const resolved = resolveRef(doc, schema);
+ if (!resolved || depth > 4) return resolved;
+
+ const inlineList = (list?: FalJsonSchema[]) =>
+ list?.map((item) => inlineSchema(doc, item, depth + 1)).filter((item) => !!item);
+
+ return {
+ ...resolved,
+ ...(resolved.anyOf && { anyOf: inlineList(resolved.anyOf) }),
+ ...(resolved.oneOf && { oneOf: inlineList(resolved.oneOf) }),
+ ...(resolved.allOf && { allOf: inlineList(resolved.allOf) }),
+ ...(resolved.items && { items: inlineSchema(doc, resolved.items, depth + 1) }),
+ };
+};
+
+/**
+ * Extract the request body schema of a fal endpoint from its queue OpenAPI document. The submit
+ * operation is `POST /<endpoint id>`; other POST paths (e.g. `/requests/{id}/cancel`) carry no body.
+ */
+export const extractFalInputSchema = (
+ openapi: unknown,
+ endpointId: string,
+): FalJsonSchema | undefined => {
+ const doc = openapi as FalOpenAPIDocument | undefined;
+ if (!doc?.paths) return;
+
+ const operations = Object.entries(doc.paths)
+ .filter(([, item]) => item?.post?.requestBody)
+ .sort(([path]) => (path === `/${endpointId}` ? -1 : 0));
+
+ const bodySchema = operations[0]?.[1].post?.requestBody?.content?.['application/json']?.schema;
+ const input = resolveRef(doc, bodySchema);
+ if (!input?.properties) return;
+
+ return {
+ ...input,
+ properties: Object.fromEntries(
+ Object.entries(input.properties).map(([key, value]) => [key, inlineSchema(doc, value) ?? {}]),
+ ),
+ };
+};
+
+const alternativesOf = (schema: FalJsonSchema): FalJsonSchema[] => [
+ schema,
+ ...(schema.anyOf ?? []).flatMap(alternativesOf),
+ ...(schema.oneOf ?? []).flatMap(alternativesOf),
+ ...(schema.allOf ?? []).flatMap(alternativesOf),
+];
+
+/** All enum values a property accepts, across its `anyOf` / `oneOf` alternatives */
+const enumOf = (schema: FalJsonSchema): unknown[] | undefined => {
+ const values = alternativesOf(schema).flatMap((item) => item.enum ?? []);
+ return values.length > 0 ? [...new Set(values)] : undefined;
+};
+
+const stringEnumOf = (schema: FalJsonSchema) => {
+ const values = enumOf(schema)?.filter((value): value is string => typeof value === 'string');
+ return values && values.length > 0 ? values : undefined;
+};
+
+const typesOf = (schema: FalJsonSchema) =>
+ new Set(alternativesOf(schema).flatMap((item) => (item.type ? [item.type] : [])));
+
+const pickEnumDefault = (values: string[], fallback: unknown, preferred: string[] = []) => {
+ if (typeof fallback === 'string' && values.includes(fallback)) return fallback;
+ return preferred.find((value) => values.includes(value)) ?? values[0];
+};
+
+const numberBounds = (schema: FalJsonSchema) => {
+ const alternative = alternativesOf(schema).find(
+ (item) => item.minimum !== undefined || item.maximum !== undefined,
+ );
+ return { max: alternative?.maximum, min: alternative?.minimum };
+};
+
+/**
+ * Parse a fal duration enum value: fal publishes durations as `"5"`, `"10"` or `"8s"`.
+ */
+const parseDuration = (value: unknown) => {
+ const parsed = typeof value === 'number' ? value : Number.parseFloat(String(value));
+ return Number.isFinite(parsed) ? parsed : undefined;
+};
+
+/** fal input field each image parameter is sent as by `createImage` */
+const IMAGE_PARAMETER_FIELDS: Record<string, string> = {
+ aspectRatio: 'aspect_ratio',
+ cfg: 'guidance_scale',
+ imageUrl: 'image_url',
+ imageUrls: 'image_urls',
+ prompt: 'prompt',
+ resolution: 'resolution',
+ seed: 'seed',
+ size: 'image_size',
+ steps: 'num_inference_steps',
+ strength: 'strength',
+};
+
+/** fal input field each video parameter is sent as by `buildGenericFalVideoInput` */
+const VIDEO_PARAMETER_FIELDS: Record<string, string> = {
+ aspectRatio: 'aspect_ratio',
+ duration: 'duration',
+ endImageUrl: 'end_image_url',
+ generateAudio: 'generate_audio',
+ imageUrl: 'image_url',
+ imageUrls: 'image_urls',
+ prompt: 'prompt',
+ resolution: 'resolution',
+ seed: 'seed',
+};
+
+/**
+ * Whether every input the endpoint requires is one the exposed parameters send. An endpoint that
+ * requires anything else (e.g. `control_image_url`) would fail fal's validation on every request.
+ */
+const sendsRequiredInputs = (
+ required: string[] | undefined,
+ parameters: Record<string, unknown>,
+ fields: Record<string, string>,
+) => {
+ const sent = new Set(Object.keys(parameters).map((key) => fields[key]));
+ return (required ?? []).every((field) => sent.has(field));
+};
+
+/**
+ * Map a fal image endpoint's input schema to the image generation parameters lobehub renders.
+ * Only fields the runtime knows how to send are exposed (see `createImage`'s parameter map);
+ * returns undefined for endpoints without a text prompt or with a required input the runtime does
+ * not send, which the generation page cannot drive.
+ */
+export const falInputSchemaToImageParameters = (
+ input: FalJsonSchema | undefined,
+): ModelParamsSchema | undefined => {
+ const properties = input?.properties;
+ if (!properties?.prompt) return;
+
+ const parameters: ModelParamsSchema = { prompt: { default: '' } };
+
+ if (properties.image_urls) {
+ const maxCount = alternativesOf(properties.image_urls).find((item) => item.maxItems)?.maxItems;
+ parameters.imageUrls = { default: [], ...(maxCount && { maxCount }) };
+ } else if (properties.image_url) {
+ parameters.imageUrl = { default: null };
+ }
+
+ const imageSizes = properties.image_size && stringEnumOf(properties.image_size);
+ if (imageSizes) {
+ parameters.size = {
+ default: pickEnumDefault(imageSizes, properties.image_size.default, [
+ 'auto_2K',
+ 'auto',
+ 'square_hd',
+ ]),
+ enum: imageSizes,
+ };
+ }
+
+ const aspectRatios = properties.aspect_ratio && stringEnumOf(properties.aspect_ratio);
+ if (aspectRatios) {
+ parameters.aspectRatio = {
+ default: pickEnumDefault(aspectRatios, properties.aspect_ratio.default, ['1:1']),
+ enum: aspectRatios,
+ };
+ }
+
+ const resolutions = properties.resolution && stringEnumOf(properties.resolution);
+ if (resolutions) {
+ parameters.resolution = {
+ default: pickEnumDefault(resolutions, properties.resolution.default),
+ enum: resolutions,
+ };
+ }
+
+ if (properties.num_inference_steps) {
+ const { max = 50, min = 1 } = numberBounds(properties.num_inference_steps);
+ const fallback = properties.num_inference_steps.default;
+ parameters.steps = {
+ default: typeof fallback === 'number' ? fallback : Math.min(max, Math.max(min, 28)),
+ max,
+ min,
+ step: 1,
+ };
+ }
+
+ if (properties.guidance_scale) {
+ const { max = 20, min = 0 } = numberBounds(properties.guidance_scale);
+ const fallback = properties.guidance_scale.default;
+ parameters.cfg = {
+ default: typeof fallback === 'number' ? fallback : min,
+ max,
+ min,
+ step: 0.1,
+ };
+ }
+
+ if (properties.strength) {
+ const { max = 1, min = 0 } = numberBounds(properties.strength);
+ const fallback = properties.strength.default;
+ parameters.strength = {
+ default: typeof fallback === 'number' ? fallback : max,
+ max,
+ min,
+ step: 0.05,
+ };
+ }
+
+ if (properties.seed) parameters.seed = { default: null };
+
+ if (!sendsRequiredInputs(input?.required, parameters, IMAGE_PARAMETER_FIELDS)) return;
+
+ return parameters;
+};
+
+/**
+ * Map a fal video endpoint's input schema to the video generation parameters lobehub renders.
+ * Field names follow `buildGenericFalVideoInput`, so every exposed parameter reaches fal. Returns
+ * undefined for endpoints without a prompt or with a required input the runtime does not send.
+ */
+export const falInputSchemaToVideoParameters = (
+ input: FalJsonSchema | undefined,
+): VideoModelParamsSchema | undefined => {
+ const properties = input?.properties;
+ if (!properties?.prompt) return;
+
+ const parameters: VideoModelParamsSchema = { prompt: { default: '' } };
+
+ if (properties.image_url) parameters.imageUrl = { default: null };
+ if (properties.end_image_url) {
+ parameters.endImageUrl = {
+ default: null,
+ ...(properties.image_url && { requiresImageUrl: true }),
+ };
+ }
+ if (properties.image_urls) {
+ const maxCount = alternativesOf(properties.image_urls).find((item) => item.maxItems)?.maxItems;
+ parameters.imageUrls = { default: [], ...(maxCount && { maxCount }) };
+ }
+
+ const aspectRatios = properties.aspect_ratio && stringEnumOf(properties.aspect_ratio);
+ if (aspectRatios) {
+ parameters.aspectRatio = {
+ default: pickEnumDefault(aspectRatios, properties.aspect_ratio.default, ['16:9']),
+ enum: aspectRatios,
+ };
+ }
+
+ const resolutions = properties.resolution && stringEnumOf(properties.resolution);
+ if (resolutions) {
+ parameters.resolution = {
+ default: pickEnumDefault(resolutions, properties.resolution.default),
+ enum: resolutions,
+ };
+ }
+
+ if (properties.duration) {
+ const durations = enumOf(properties.duration)
+ ?.map(parseDuration)
+ .filter((value): value is number => value !== undefined);
+ const fallback = parseDuration(properties.duration.default);
+
+ if (durations && durations.length > 0) {
+ parameters.duration = {
+ default: fallback !== undefined && durations.includes(fallback) ? fallback : durations[0],
+ enum: durations,
+ };
+ } else if (typesOf(properties.duration).has('integer') || typesOf(properties.duration).has('number')) {
+ const { max, min } = numberBounds(properties.duration);
+ parameters.duration = {
+ default: fallback ?? min ?? 5,
+ ...(max !== undefined && { max }),
+ ...(min !== undefined && { min }),
+ step: 1,
+ };
+ }
+ }
+
+ if (properties.generate_audio) {
+ const fallback = properties.generate_audio.default;
+ parameters.generateAudio = { default: typeof fallback === 'boolean' ? fallback : true };
+ }
+
+ if (properties.seed) parameters.seed = { default: null };
+
+ if (!sendsRequiredInputs(input?.required, parameters, VIDEO_PARAMETER_FIELDS)) return;
+
+ return parameters;
+};
+
+/**
+ * Fit request values to the types the endpoint declares: fal takes many numeric options as string
+ * enums (`duration: "5"` or `"8s"`), and rejects fields its schema does not define.
+ */
+export const coerceFalInput = (input: Record<string, unknown>, schema: FalJsonSchema | undefined) => {
+ const properties = schema?.properties;
+ if (!properties) return input;
+
+ return Object.fromEntries(
+ Object.entries(input).flatMap(([key, value]) => {
+ const property = properties[key];
+ if (!property) return [];
+ if (typeof value !== 'number') return [[key, value]];
+
+ const stringValues = stringEnumOf(property);
+ if (stringValues) {
+ const match = stringValues.find((item) => parseDuration(item) === value);
+ return [[key, match ?? String(value)]];
+ }
+
+ const types = typesOf(property);
+ if (types.has('string') && !types.has('number') && !types.has('integer')) {
+ return [[key, String(value)]];
+ }
+
+ return [[key, value]];
+ }),
+ );
+};
diff --git a/packages/model-runtime/src/providers/fal/testUtils.ts b/packages/model-runtime/src/providers/fal/testUtils.ts
new file mode 100644
index 00000000000..d5de49e72eb
--- /dev/null
+++ b/packages/model-runtime/src/providers/fal/testUtils.ts
@@ -0,0 +1,42 @@
+import type { FalJsonSchema } from './schema';
+
+/**
+ * Queue OpenAPI document shaped like the ones fal publishes: the submit operation is
+ * `POST /<endpoint id>` with its input schema under `components.schemas`.
+ */
+export const buildFalOpenAPI = (endpointId: string, properties: Record<string, FalJsonSchema>) => ({
+ components: {
+ schemas: {
+ Input: { properties, required: ['prompt'], type: 'object' },
+ QueueStatus: { properties: { status: { type: 'string' } }, type: 'object' },
+ },
+ },
+ openapi: '3.0.4',
+ paths: {
+ [`/${endpointId}`]: {
+ post: {
+ requestBody: {
+ content: { 'application/json': { schema: { $ref: '#/components/schemas/Input' } } },
+ },
+ },
+ },
+ [`/${endpointId}/requests/{request_id}/cancel`]: { put: {} },
+ },
+});
+
+/** `GET /v1/models` response for one endpoint with an expanded OpenAPI schema */
+export const buildFalCatalogResponse = (
+ endpointId: string,
+ properties: Record<string, FalJsonSchema>,
+ metadata: Record<string, unknown> = {},
+) => ({
+ has_more: false,
+ models: [
+ {
+ endpoint_id: endpointId,
+ metadata: { display_name: endpointId, ...metadata },
+ openapi: buildFalOpenAPI(endpointId, properties),
+ },
+ ],
+ next_cursor: null,
+});