# fal > ## Agent Instructions > fal has two developer products. Model APIs run hosted models through an API key. fal Serverless deploys your own Python apps and models on fal GPUs. > To call a hosted model, start with the [Quick Start](https://fal.ai/docs/documentation/quickstart.md) and the [Model APIs overview](https://fal.ai/docs/documentation/model-apis/overview.md). > To deploy your own model with fal Serverless, start with these pages: > - [Introduction to Serverless](https://fal.ai/docs/documentation/serverless/index.md): What fal Serverless is and the three ways to deploy on it. > - [Installation & Setup](https://fal.ai/docs/documentation/development/getting-started/installation.md): Install the fal CLI with `pip install fal` and authenticate. > - [Quick Start](https://fal.ai/docs/documentation/development/getting-started/quick-start.md): Build a Hello World app, test it with `fal run`, and ship it with `fal deploy`. > - [App Lifecycle](https://fal.ai/docs/documentation/development/app-lifecycle.md): How a `fal.App` goes from code to running runners. > - [Define Your Endpoints](https://fal.ai/docs/documentation/development/endpoints-overview.md): Structure the API endpoints that your app exposes. > - [Deploy to Production](https://fal.ai/docs/documentation/deployment/deploy-to-production.md): Persistent URLs, authentication modes, and automatic scaling. > - [Machine Types](https://fal.ai/docs/documentation/deployment/machine-types.md): Available GPU and CPU machine types and how to choose one. > - [Pricing](https://fal.ai/docs/documentation/serverless/pricing.md): Per-second billing and the runner states that are billed. > - [Scaling Parameter Reference](https://fal.ai/docs/documentation/deployment/scale-your-application.md): Parameters that control runners, concurrency, and scale to zero. > - [Optimizing Cold Starts](https://fal.ai/docs/documentation/serverless/optimizations/optimize-cold-starts.md): Causes of cold starts and ways to make them shorter. > - [Examples](https://fal.ai/docs/examples/index.md): Complete Serverless apps for image, video, audio, 3D, realtime, and multi-GPU workloads. > - [Migrating to fal](https://fal.ai/docs/documentation/development/migrating-to-fal.md): Guides to move an existing Docker server or an app from another platform to fal. > fal Serverless deploys need access that the fal team approves for each account. Request access at https://fal.ai/dashboard/serverless-get-started. # fal api Source: https://fal.ai/docs/api-reference/cli/api Call any fal model from the command line with fal api. Pass input as key=value pairs, use := for numbers and booleans, and stream output from /stream endpoints. Call any model on fal directly from the command line. Useful for quick testing without writing code. ## Usage ```bash theme={null} fal api [key=value ...] ``` **Arguments:** | Argument | Description | | - | - | | `model_id` | The model endpoint to call (e.g., `fal-ai/flux/schnell`) | | `params` | Key-value pairs for the request body (e.g., `prompt="a sunset"`) | ## Examples **Generate an image:** ```bash theme={null} fal api fal-ai/flux/schnell prompt="a cat wearing sunglasses" ``` The CLI shows real-time status updates (queued, in progress) and logs while the request is processing, then prints the result. **Nested parameters:** Use bracket notation for nested values: ```bash theme={null} fal api fal-ai/flux/schnell prompt="a sunset" image_size[width]:=1280 image_size[height]:=720 ``` Use `:=` for non-string values (numbers, booleans): ```bash theme={null} fal api fal-ai/flux/schnell prompt="a sunset" num_images:=4 seed:=42 ``` **Streaming endpoints:** If the model ID ends with `/stream`, the CLI streams output as it's generated: ```bash theme={null} fal api fal-ai/any-llm/stream prompt="What is the meaning of life?" model=google/gemini-flash-1.5 ``` ## How It Works * For regular endpoints: submits via the queue, polls for status with live log display, then prints the result * For `/stream` endpoints: connects via streaming and prints output as it arrives * Uses your configured `FAL_KEY` for authentication # fal apps delete Source: https://fal.ai/docs/api-reference/cli/apps/delete Delete a fal application from the command line with fal apps delete. Pass the app name, and use --env to delete the app from an environment such as staging. ```bash theme={null} Usage: fal apps delete [-h] [--debug] [--pdb] [--cprofile] [--env ENV] app_name Delete application. Positional Arguments: app_name Application name. Options: -h, --help show this help message and exit --env ENV Target environment (defaults to main). Examples: fal apps delete my-app fal apps delete my-app --env staging ``` # fal apps delete-rev Source: https://fal.ai/docs/api-reference/cli/apps/delete-rev Reference for fal apps delete-rev, the fal CLI command that deletes one revision of a fal application. Pass the revision ID as the app_rev argument. ```bash theme={null} Usage: fal apps delete-rev [-h] [--debug] [--pdb] [--cprofile] app_rev Delete application revision. Positional Arguments: app_rev Application revision. Options: -h, --help show this help message and exit ``` # fal apps gpus Source: https://fal.ai/docs/api-reference/cli/apps/gpus Show GPU usage for the runners of one fal application with fal apps gpus, as a table or JSON. Use fal runners gpus for a summary across the whole account. ```bash theme={null} Usage: fal apps gpus [-h] [--team TEAM] [--output {pretty,json}] [--json] app_name Show GPU usage for an application. Positional Arguments: app_name Application name. Options: -h, --help show this help message and exit --team TEAM The team to use. Output: --output {pretty,json} Modify the command output --json Output in JSON format (same as --output json) ``` Use this to see how the GPUs behind one application are being used. For a summary across every runner in the account rather than a single app, see [`fal runners gpus`](/docs/api-reference/cli/runners#gpus). # fal apps list Source: https://fal.ai/docs/api-reference/cli/apps/list List your fal applications with fal apps list. Filter by name or region, sort by runner count, choose an environment, and print the results as a table or JSON. ```bash theme={null} Usage: fal apps list [-h] [--debug] [--pdb] [--cprofile] [--sort-by-runners] [--filter FILTER] [--env ENV] [--regions REGIONS [REGIONS ...]] [--output {pretty,json}] [--json] List applications. Options: -h, --help show this help message and exit --sort-by-runners Sort by number of runners ascending. --filter FILTER Filter applications by alias contents. --env ENV Target environment (defaults to main). --regions REGIONS [REGIONS ...] Valid regions (pass several items to filter on multiple). Output: --output {pretty,json} Modify the command output --json Output in JSON format (same as --output json) Examples: fal apps list fal apps list --env staging fal apps list --filter myapp --sort-by-runners fal apps list --json ``` # fal apps list-rev Source: https://fal.ai/docs/api-reference/cli/apps/list-rev List the revisions of your fal applications with fal apps list-rev. Pass an app name to show the revisions of one app, and use --env to choose the environment. ```bash theme={null} Usage: fal apps list-rev [-h] [--debug] [--pdb] [--cprofile] [--env ENV] [app_name] List application revisions. Positional Arguments: app_name Application name (optional). Options: -h, --help show this help message and exit --env ENV Target environment (defaults to main). ``` # fal apps rollout Source: https://fal.ai/docs/api-reference/cli/apps/rollout Restart all runners of a fal app without a redeploy with fal apps rollout. Compare a graceful rollout that drains requests with a forced one. ```bash theme={null} Usage: fal apps rollout [-h] [--debug] [--pdb] [--cprofile] [--team TEAM] [--force] [--env ENV] app_name Rollout application by restarting all active runners. Positional Arguments: app_name Application name. Options: -h, --help show this help message and exit --team TEAM The team to use. --force Force rollout by killing runners immediately instead of gracefully stopping them. --env ENV Target environment (defaults to main). Debug: --debug Show verbose errors. --pdb Start pdb on error. --cprofile Show cProfile report. ``` ## When to Use Use `fal apps rollout` when you need to replace all runners for an application without redeploying: * **Environment variable changes**: Force runners to pick up updated secrets or environment variables * **Bad state recovery**: Replace runners that may be in an unhealthy state * **Memory cleanup**: Force garbage collection and memory cleanup across all runners * **Configuration updates**: Apply changes that require a fresh runner * **Machine type changes**: Move existing runners onto a machine type you changed with `fal apps scale` -- see [Changing Machine Types](/docs/documentation/deployment/machine-types#rolling-out-existing-runners) ## Graceful vs Force Rollout ### Graceful Rollout (Default) ```bash theme={null} fal apps rollout myapp ``` Brings up replacement runners before draining the existing ones, so requests are not interrupted. This is the recommended approach for most situations. **How it works:** 1. Identifies all active runners for the application 2. Marks each one for replacement -- they keep serving requests in the meantime 3. Starts replacement runners on the application's current configuration 4. As each new runner finishes starting up and joins the application, one marked runner stops accepting new requests and drains the ones it is still processing Replacements are started in parallel rather than one at a time, so while the rollout is in progress the application can run close to double its usual runner count -- and is billed for both sets. If your account's GPU limits are already fully consumed, replacements wait until capacity frees up and the marked runners keep serving in the meantime. ### Force Rollout ```bash theme={null} fal apps rollout myapp --force ``` Immediately kills all active runners without waiting for current requests to complete. Use this when runners are unresponsive or when you need an immediate restart. **How it works:** 1. Identifies all active runners for the application 2. Immediately terminates all runners 3. New runners are automatically started by the auto-scaling system > [!WARNING] > > Force rollout will terminate in-flight requests, potentially causing errors for active users. Use the graceful rollout (without `--force`) unless absolutely necessary. ## Examples ### Rollout after updating a secret ```bash theme={null} # Update a secret fal secrets set MY_API_KEY new_value # Gracefully rollout to pick up the new secret fal apps rollout myapp ``` ### Rollout in a specific environment ```bash theme={null} # Update a secret in staging fal secrets set MY_API_KEY staging_value --env staging # Rollout the staging environment fal apps rollout myapp --env staging ``` ### Force rollout to recover from frozen runners ```bash theme={null} # Check runners status fal apps runners myapp # Force immediate restart if runners are unresponsive fal apps rollout myapp --force ``` ## Difference from Redeployment `fal apps rollout` is different from `fal deploy`: * **`fal apps rollout`**: Replaces existing runners without creating a new revision, so they come up on the app's current configuration. Useful for applying environment or machine-type changes and recovering from bad states. * **`fal deploy`**: Creates a new revision of your application with updated code and configuration. Use this when you've made code changes. ## See Also * [fal deploy](/docs/serverless/cli/deploy) - Deploy a new revision of your application * [fal apps scale](/docs/serverless/cli/apps/scale) - Adjust scaling parameters * [fal apps runners](/docs/serverless/cli/apps/runners) - View active runners for an application # fal apps runners Source: https://fal.ai/docs/api-reference/cli/apps/runners List the runners of one fal application with fal apps runners. Filter by state, show runners that stopped in the last 24 hours, and read the table columns. ```bash theme={null} Usage: fal apps runners [-h] [--team TEAM] [--env ENV] [--since SINCE] [--state {all,idle,running,pending,setup,crash_backoff,terminated} [...]] [--output {pretty,json}] [--json] app_name List application runners. Positional Arguments: app_name Application name. Options: -h, --help show this help message and exit --team TEAM The team to use. --env ENV Target environment (defaults to main). --since SINCE Show terminated runners since the given time. Accepts 'now', relative like '30m', '1h', '1d', or an ISO timestamp. Max 24 hours. --state {all,idle,running,pending,setup,crash_backoff,terminated} [{all,idle,running,pending,setup,crash_backoff,terminated} ...] Filter by runner state(s). Choose one or more, or 'all' (default). Output: --output {pretty,json} Modify the command output --json Output in JSON format (same as --output json) Examples: fal apps runners my-app fal apps runners my-app --env staging ``` The runner table displays the following columns: * **Alias** -- Application name * **Machine Type** -- Hardware type (e.g. `GPU-A100`, `GPU-H100`) * **Runner ID** -- Unique runner identifier * **In Flight Requests** -- Number of active requests * **Expires In** -- Time until runner expires * **Uptime** -- How long the runner has been running * **Revision** -- Application revision * **State** -- Current runner state # fal apps scale Source: https://fal.ai/docs/api-reference/cli/apps/scale Change the scaling settings of a deployed fal app with fal apps scale. Set keep-alive, concurrency, multiplexing, timeouts, machine types, and regions. ```bash theme={null} Usage: fal apps scale [-h] [--debug] [--pdb] [--cprofile] [--team TEAM] [--keep-alive KEEP_ALIVE] [--max-multiplexing MAX_MULTIPLEXING] [--max-concurrency MAX_CONCURRENCY] [--min-concurrency MIN_CONCURRENCY] [--concurrency-buffer CONCURRENCY_BUFFER] [--concurrency-buffer-perc CONCURRENCY_BUFFER_PERC] [--scaling-delay SCALING_DELAY] [--request-timeout REQUEST_TIMEOUT] [--startup-timeout STARTUP_TIMEOUT] [--machine-types MACHINE_TYPES [MACHINE_TYPES ...]] [--regions REGIONS [REGIONS ...]] [--env ENV] app_name Scale application. Positional Arguments: app_name Application name. Options: -h, --help show this help message and exit --team TEAM The team to use. --keep-alive KEEP_ALIVE Keep alive (seconds). --max-multiplexing MAX_MULTIPLEXING Maximum multiplexing --max-concurrency MAX_CONCURRENCY Maximum concurrency. --min-concurrency MIN_CONCURRENCY Minimum concurrency --concurrency-buffer CONCURRENCY_BUFFER Concurrency buffer (minimum extra capacity). --concurrency-buffer-perc CONCURRENCY_BUFFER_PERC Concurrency buffer expressed as a percentage. --scaling-delay SCALING_DELAY Scaling delay (seconds). --request-timeout REQUEST_TIMEOUT Request timeout (seconds). If a request takes longer, it is aborted and the runner gracefully stopped as it could be in a bad state. --startup-timeout STARTUP_TIMEOUT Startup timeout (seconds). --machine-types MACHINE_TYPES [MACHINE_TYPES ...] Machine types (pass several items to set multiple). --regions REGIONS [REGIONS ...] Valid regions (pass several items to set multiple). --env ENV Target environment (defaults to main). ``` > [!NOTE] > > **Note:** > > Redeploying the application, by default, will not reset these settings, except for the code-specific settings. See [Code-Specific Settings (Reset on Deploy)](/docs/serverless/deployment-operations/scale-your-application#code-specific-settings-reset-on-deploy) for details. # fal apps set-rev Source: https://fal.ai/docs/api-reference/cli/apps/set-rev Point a fal application at a specific revision with fal apps set-rev to roll back. Set the auth mode, deployment strategy, and target environment. ```bash theme={null} Usage: fal apps set-rev [-h] [--debug] [--pdb] [--cprofile] [--team TEAM] [--auth {public,private,shared}] [--strategy {recreate,rolling}] [--env ENV] app_name app_rev Set application to a particular revision. Positional Arguments: app_name Application name. app_rev Application revision. Options: -h, --help show this help message and exit --team TEAM The team to use. --auth {public,private,shared} Application authentication mode. --strategy {recreate,rolling} Deployment strategy. --env ENV Target environment (defaults to main). Can also be set via FAL_ENV environment variable. Debug: --debug Show verbose errors. --pdb Start pdb on error. --cprofile Show cProfile report. ``` # fal auth Source: https://fal.ai/docs/api-reference/cli/auth Log in to fal from the CLI with GitHub, Google, or an enterprise SSO domain. Log out with fal auth logout, and show the current user with fal auth whoami. ```bash theme={null} fal auth [-h] [--debug] [--pdb] [--cprofile] command ... Authenticate with fal. Options: -h, --help show this help message and exit Commands: command login Log in a user. logout Log out the currently logged-in user. whoami Show the currently authenticated user. ``` ## Login ```bash theme={null} Usage: fal auth login [-h] [--debug] [--pdb] [--cprofile] [--connection CONNECTION] [--no-browser] Log in a user. Options: -h, --help show this help message and exit --connection CONNECTION Auth connection (e.g. github, google, or an SSO domain). Skips the interactive prompt. --no-browser Don't attempt to open a browser. Just print the URL to visit. ``` When `--connection` is omitted, the CLI prompts you to choose between GitHub, Google, or your enterprise SSO domain. The previously used choice is remembered and offered as the default on subsequent logins. ## Logout ```bash theme={null} Usage: fal auth logout [-h] [--debug] [--pdb] [--cprofile] [--no-browser] Log out the currently logged-in user. Options: -h, --help show this help message and exit --no-browser Don't attempt to open a browser. Just print the URL to visit. ``` ## Whoami ```bash theme={null} Usage: fal auth whoami [-h] [--debug] [--pdb] [--cprofile] Show the currently authenticated user. Options: -h, --help show this help message and exit Debug: --debug Show verbose errors. --pdb Start pdb on error. --cprofile Show cProfile report. ``` # fal create Source: https://fal.ai/docs/api-reference/cli/create Reference for fal create, the fal CLI command that creates a new fal application project from a project type. See the command usage and its arguments. ```bash theme={null} Usage: fal create [-h] [--debug] [--pdb] [--cprofile] project_type Create fal applications. Positional Arguments: project_type Type of project to create. Options: -h, --help show this help message and exit ``` # fal deploy Source: https://fal.ai/docs/api-reference/cli/deploy Deploy a fal app with fal deploy. Set the app name, auth mode, rolling or recreate strategy, and target environment, and add revision messages and annotations. > [!TIP] > > Before deploying, validate your app with [`fal run`](/docs/api-reference/cli/run). It boots your app on a temporary worker — running `setup()` and your endpoints just like production — so import and model-loading errors surface locally instead of as a production crashloop. On a first deploy or after a failed deploy, the CLI reminds you to do this. See [Development vs Production](/docs/documentation/deployment/deploy-to-production#development-vs-production). > [!NOTE] > > After a successful deployment, test the persistent app from the [Apps dashboard](https://fal.ai/dashboard/apps) under **Testing > Playground**. The links printed by `fal deploy` depend on your installed CLI release. Follow the [dashboard Playground flow](/docs/documentation/model-apis/playground#your-own-apps) as the stable entry point. ```bash theme={null} Usage: fal deploy [-h] [--output {pretty,json}] [--json] [--team TEAM] [--app-name APP_NAME] [--auth AUTH] [--strategy {recreate,rolling}] [--attach | --detach] [--no-scale] [--reset-scale] [--check] [--yes] [--message MESSAGE] [--annotation KEY=VALUE] [--no-cache] [--env ENV] [app_ref] Deploy a fal application. If no app reference is provided, the command will look for a pyproject.toml file with a [tool.fal.apps] section and deploy the application specified with the provided app name. Positional Arguments: app_ref Application reference. Either a file path or a file path and a function name separated by '::'. If no reference is provided, the command will look for a pyproject.toml file with a [tool.fal.apps] section and deploy the application specified with the provided app name. File path example: path/to/myfile.py::MyApp App name example: my-app (configure team in pyproject.toml) Options: -h, --help show this help message and exit --team TEAM The team to use. --app-name APP_NAME Application name to deploy with. --auth AUTH Application authentication mode (private, public, shared). --strategy {recreate,rolling} Deployment strategy. --attach Attach to the deployment process. Only applies when --strategy is rolling (the default). --detach Do not attach to the deployment process. Only applies when --strategy is rolling (the default). --no-scale Use the previous deployment of the application for scale settings. This is the default behavior. --reset-scale Use the application code for scale settings. --check Show a pre-deployment summary before deploying. Prompts for confirmation unless --yes is also set. --yes Skip interactive deploy confirmation prompts. When combined with --check, the summary is still shown. --message MESSAGE Freeform message to attach to this revision (e.g, 'add feature') --annotation KEY=VALUE Custom key=value pair to attach to this revision (e.g, GIT_SHA=1234567890). Can be repeated. Value must be a string. --no-cache Do not use the cache for the environment build. --env ENV Target environment (defaults to main). Can also be set via FAL_ENV environment variable. Output: --output {pretty,json} Modify the command output --json Output in JSON format (same as --output json) Examples: fal deploy fal deploy path/to/myfile.py fal deploy path/to/myfile.py::MyApp fal deploy path/to/myfile.py::MyApp --app-name myapp --auth public fal deploy path/to/myfile.py::MyApp --check fal deploy path/to/myfile.py::MyApp --check --yes fal deploy path/to/myfile.py::MyApp --env staging fal deploy my-app fal deploy my-app --message "a1b2c3d fix cold-start" fal deploy my-app --annotation DEPLOYER_ID=foo-123 --annotation GIT_SHA=1234567890 ``` # fal doctor Source: https://fal.ai/docs/api-reference/cli/doctor Use fal doctor to print the installed fal and isolate versions, Python version, platform, FAL_HOST, and active FAL_KEY prefix. Attach the output to bug reports. ```bash theme={null} Usage: fal doctor [-h] [--debug] [--pdb] [--cprofile] [--output {pretty,json}] [--json] fal version and misc environment information. Options: -h, --help show this help message and exit Output: --output {pretty,json} Modify the command output --json Output in JSON format (same as --output json) ``` Outputs the installed `fal` and `isolate` versions, the Python version and platform, and the configured `FAL_HOST` and the prefix of the active `FAL_KEY`. Useful when filing bug reports. # fal environments Source: https://fal.ai/docs/api-reference/cli/environments Create, list, and delete fal environments such as staging with fal environments. Then target one with --env when you deploy apps, set secrets, or run code. ```bash theme={null} Usage: fal environments [-h] [--debug] [--pdb] [--cprofile] command ... Manage fal environments. Options: -h, --help show this help message and exit Commands: command list List environments. create Create an environment. delete Delete an environment. ``` > [!NOTE] > > The `environments` command also has an alias `envs` for convenience: > > ```bash theme={null} > fal envs list > ``` ## List ```bash theme={null} Usage: fal environments list [-h] [--debug] [--pdb] [--cprofile] [--output {pretty,json}] [--json] List environments. Options: -h, --help show this help message and exit Output: --output {pretty,json} Modify the command output --json Output in JSON format (same as --output json) Examples: fal environments list fal envs list --output json ``` ## Create ```bash theme={null} Usage: fal environments create [-h] [--debug] [--pdb] [--cprofile] [--description DESCRIPTION] name Create an environment. Positional Arguments: name Environment name. Options: -h, --help show this help message and exit --description DESCRIPTION Environment description. Examples: fal environments create staging fal envs create dev --description "Development environment" ``` ## Delete ```bash theme={null} Usage: fal environments delete [-h] [--debug] [--pdb] [--cprofile] [--yes] name Delete an environment. Positional Arguments: name Environment name. Options: -h, --help show this help message and exit --yes Skip confirmation prompt. Debug: --debug Show verbose errors. --pdb Start pdb on error. --cprofile Show cProfile report. ``` > [!WARNING] > > Deleting an environment permanently removes all apps and secrets in that environment. You will be prompted to confirm by typing the environment name unless `--yes` is provided. ## Using Environments with Other Commands Once you've created environments, you can target them using the `--env` flag in other commands: ```bash theme={null} # Deploy to an environment fal deploy path/to/myapp.py::MyApp --env staging # Manage secrets per environment fal secrets set API_KEY=value --env staging fal secrets list --env staging # Manage apps per environment fal apps list --env staging fal apps scale my-app --min-concurrency 1 --env staging fal apps runners my-app --env staging fal apps delete my-app --env staging # Run functions with environment-specific secrets fal run path/to/myapp.py::MyApp --env staging ``` # fal files Source: https://fal.ai/docs/api-reference/cli/files Manage files in fal storage from the CLI. List, upload, and download files, upload from a URL, and move or remove remote files and directories with fal files. ```bash theme={null} fal files [-h] [--debug] [--pdb] [--cprofile] command ... Manage fal files. Options: -h, --help show this help message and exit Commands: command list (ls) List files. download Download files. upload Upload files. upload-url Upload file from URL. mv Move or rename a remote file or directory. rm Recursively remove a remote file or directory. ``` ## List ```bash theme={null} fal files list [-h] [--debug] [--pdb] [--cprofile] [--team TEAM] [path] List files. Positional Arguments: path The path to list Options: -h, --help show this help message and exit --team TEAM The team to use. ``` ## Download ```bash theme={null} fal files download [-h] [--debug] [--pdb] [--cprofile] [--team TEAM] remote_path local_path Download files. Positional Arguments: remote_path Remote path to download local_path Local path to download to Options: -h, --help show this help message and exit --team TEAM The team to use. ``` ## Upload ```bash theme={null} fal files upload [-h] [--debug] [--pdb] [--cprofile] [--team TEAM] local_path remote_path Upload files. Positional Arguments: local_path Local path to upload remote_path Remote path to upload to Options: -h, --help show this help message and exit --team TEAM The team to use. ``` ## Upload URL ```bash theme={null} fal files upload-url [-h] [--debug] [--pdb] [--cprofile] [--team TEAM] url remote_path Upload file from URL. Positional Arguments: url URL to upload remote_path Remote path to upload to Options: -h, --help show this help message and exit --team TEAM The team to use. ``` ## Move ```bash theme={null} fal files mv [-h] [--team TEAM] source destination Move or rename a remote file or directory. Positional Arguments: source Remote source path destination Remote destination path Options: -h, --help show this help message and exit --team TEAM The team to use. ``` ## Remove ```bash theme={null} fal files rm [-h] [--team TEAM] path Recursively remove a remote file or directory. Positional Arguments: path Remote path Options: -h, --help show this help message and exit --team TEAM The team to use. ``` # CLI Reference Source: https://fal.ai/docs/api-reference/cli/index Complete reference for the fal command-line interface The fal CLI is the primary tool for deploying and managing your fal applications. ## Installation ```bash theme={null} pip install fal ``` ## Authentication ```bash theme={null} fal auth login ``` ## Commands | Command | Description | | - | - | | [`fal auth`](/docs/api-reference/cli/auth) | Authenticate with fal | | [`fal deploy`](/docs/api-reference/cli/deploy) | Deploy an application | | [`fal run`](/docs/api-reference/cli/run) | Run a function | | [`fal apps`](/docs/api-reference/cli/apps/list) | Manage applications | | [`fal environments`](/docs/api-reference/cli/environments) | Manage environments | | [`fal keys`](/docs/api-reference/cli/keys) | Manage API keys | | [`fal secrets`](/docs/api-reference/cli/secrets) | Manage secrets | | [`fal files`](/docs/api-reference/cli/files) | Manage files in /data | | [`fal queue`](/docs/api-reference/cli/queue) | Manage queued requests | | [`fal runners`](/docs/api-reference/cli/runners) | Manage runners | | [`fal api`](/docs/api-reference/cli/api) | Call a fal API endpoint directly | | [`fal account`](/docs/api-reference/cli/teams) | Manage accounts | | [`fal doctor`](/docs/api-reference/cli/doctor) | Diagnose issues | | [`fal create`](/docs/api-reference/cli/create) | Create a new project | | [`fal profile`](/docs/api-reference/cli/profile) | Manage profiles | # Installation Source: https://fal.ai/docs/api-reference/cli/installation Install the fal CLI and Python SDK with pip. Install the latest release, or install a development version from a git revision, tag, or branch of the fal repo. ## Install latest official version ```bash theme={null} pip install fal ``` ## Install upstream version ```bash theme={null} pip install git+https://github.com/fal-ai/fal#subdirectory=projects/fal ``` ## Install development version from a git revision ```bash theme={null} pip install git+https://github.com/fal-ai/fal@75fe22f19cf61c7b6488d919d9a8c4bcb3433b42#subdirectory=projects/fal ``` ## Install development version from a git tag ```bash theme={null} pip install git+https://github.com/fal-ai/fal@fal_v1.10.0#subdirectory=projects/fal ``` ## Install development version from a git branch ```bash theme={null} pip install git+https://github.com/fal-ai/fal@main#subdirectory=projects/fal ``` # fal keys Source: https://fal.ai/docs/api-reference/cli/keys Create, list, and revoke fal API keys from the command line with fal keys. Choose the ADMIN or API scope for each key, and add an optional key description. ```bash theme={null} Usage: fal keys [-h] [--debug] [--pdb] [--cprofile] command ... Manage fal keys. Options: -h, --help show this help message and exit Commands: command create Create a key. list List keys. revoke Revoke key. ``` ## Create ```bash theme={null} Usage: fal keys create [-h] [--debug] [--pdb] [--cprofile] --scope {ADMIN,API} [--desc DESC] Create a key. Options: -h, --help show this help message and exit --scope {ADMIN,API} The privilege scope of the key. --desc DESC Key description (e.g. "My Test Key") ``` ## List ```bash theme={null} Usage: fal keys list [-h] [--debug] [--pdb] [--cprofile] List keys. Options: -h, --help show this help message and exit ``` ## Revoke ```bash theme={null} Usage: fal keys revoke [-h] [--debug] [--pdb] [--cprofile] key_id Revoke key. Positional Arguments: key_id Key ID. Options: -h, --help show this help message and exit ``` # fal profile Source: https://fal.ai/docs/api-reference/cli/profile Use fal profile to manage several fal accounts on one machine. Create profiles, set a key and host for each, list them, choose the default, and delete them. ### Managing Profiles The `fal` CLI allows you to manage multiple profiles, making it easy to switch between different fal accounts. This is particularly useful if you have multiple environments or projects. #### Adding a New Profile To add a new profile, set it as the default and then add the key: ```sh theme={null} ❯ fal profile set example Default profile set to example. No key set for profile. Use fal profile key to set a key. ❯ fal profile key Enter the key: invalid Invalid key. The key must be in the format key:value. Enter the key: 112f05b4-6ee8-4d06-bdb1-7ba38789ef8e:954285993fa8e651dac37a03ea2efbc9 Key set for profile example. ``` > [!NOTE] > > **Note:** > > The key used in the example above is no longer valid. 😉 #### Listing Profiles To list all available profiles, use the `fal profile list` command: ```sh theme={null} ❯ fal profile list ``` | Default | Profile | Settings | | - | - | - | | | me | key | | | comfy | key | | \* | example | key | #### Setting a Default Profile To set a default profile, use the `fal profile set` command followed by the profile name: ```sh theme={null} ❯ fal profile set comfy Default profile set to comfy. ❯ fal profile list ``` | Default | Profile | Settings | | - | - | - | | | me | key | | \* | comfy | key | | | example | key | After setting the default profile, you can directly access the account information without specifying the profile name. ```sh theme={null} ❯ fal app list ``` | Name | Revision | Auth | Min Concurrency | Max Concurrency | Max Multiplexing | Keep Alive | Request Timeout | Startup Timeout | Machine Type | Runners | Regions | | - | - | - | - | - | - | - | - | - | - | - | - | | my-app | 11111111-2222-333… | shared | 0 | 10 | 1 | 300 | 3600 | 600 | ........ | 0 | | #### Deleting a Profile To delete a profile, use the `fal profile delete` command followed by the profile name: ```sh theme={null} ❯ fal profile delete example Profile example deleted. ``` ## Command Reference ```bash theme={null} Usage: fal profile [-h] command ... Profile management. Commands: command list List all profiles. set Set default profile. If the profile doesn't exist, you'll be prompted to create it. unset Unset default profile. key Set key for profile. host Set fal host. create Create a new profile. delete Delete profile. ``` > [!NOTE] > > `fal profiles` is an alias for `fal profile`. ### create Create a new named profile and set it as the default: ```bash theme={null} fal profile create ``` If the profile already exists the command is a no-op. After creation you'll typically run `fal profile key` to attach an API key. ### unset Clear the default profile selection: ```bash theme={null} fal profile unset ``` After unsetting, `fal` falls back to environment variables (`FAL_KEY`, `FAL_HOST`). ### host Override the fal API host for the active profile. Most users don't need this — it's primarily useful for self-hosted or staging deployments: ```bash theme={null} fal profile host ``` ### list ```bash theme={null} Usage: fal profile list [-h] [--output {pretty,json}] [--json] ``` Supports JSON output for scripting: ```bash theme={null} fal profile list --json ``` # fal queue Source: https://fal.ai/docs/api-reference/cli/queue Manage application queues. ```bash theme={null} Usage: fal queue [-h] command ... Manage application queues. Options: -h, --help show this help message and exit Commands: command size Get queue size for an application. flush Flush all pending requests in an application queue. ``` ## Size ```bash theme={null} Usage: fal queue size [-h] [--output {pretty,json}] [--json] [--team TEAM] [--by-user] app_name Get queue size for an application. Positional Arguments: app_name Application name (do not prefix with owner). Options: -h, --help show this help message and exit --team TEAM The team to use. --by-user Group queue size by user. Output: --output {pretty,json} Modify the command output --json Output in JSON format (same as --output json) ``` ## Flush ```bash theme={null} Usage: fal queue flush [-h] [--team TEAM] [--caller-user-id CALLER_USER_ID] app_name Flush all pending requests in an application queue. Positional Arguments: app_name Application name. Options: -h, --help show this help message and exit --team TEAM The team to use. --caller-user-id CALLER_USER_ID Only flush requests from this user ID. If not provided, all requests will be flushed. ``` # fal run Source: https://fal.ai/docs/api-reference/cli/run Run a fal function or app on a temporary runner with fal run. Choose the auth mode, environment, and machine type, or use --local to run it on your machine. ```bash theme={null} Usage: fal run [-h] [--team TEAM] [--no-cache] [--app-name APP_NAME] [--auth AUTH] [--env ENV] [--local] [--exposed-port PORT] [--exposed-metrics-port PORT] [--machine-type MACHINE_TYPE] [--limit-max-requests LIMIT_MAX_REQUESTS] func_ref Run fal function. Positional Arguments: func_ref Function reference. Configure team in pyproject.toml for app names. Options: -h, --help show this help message and exit --team TEAM The team to use. --no-cache Do not use the cache for the environment build. --app-name APP_NAME Application name to run with. --auth AUTH Application authentication mode (private, public, shared), defaults to public. --env ENV Target environment (defaults to main). --local Run locally without serverless. --exposed-port PORT Port for the --local app server (default: 8080). --exposed-metrics-port PORT Port for the --local metrics server (default: 9090). --machine-type MACHINE_TYPE Machine type to use for this run. --limit-max-requests LIMIT_MAX_REQUESTS For fal.App runs, gracefully stop the server after serving N requests. Examples: fal run path/to/myfile.py::myfunc fal run path/to/myfile.py::myfunc --env staging fal run path/to/myfile.py::MyApp --auth private fal run path/to/myfile.py::MyApp --local fal run path/to/myfile.py::MyApp --machine-type GPU-A100 ``` > [!WARNING] > > `fal run` ignores the `auth` set on `fal.App` and in `pyproject.toml` and defaults to `public` so the app is reachable for testing. Pass `--auth` to override. In a future major release the default will become `private` and the `fal.App`/`pyproject.toml` value will be respected. ## Authentication Modes The `--auth` flag controls who can access your app while it's running: * **`public`** (default for `fal run`): Anyone can call your app without authentication. You pay for all usage. * **`private`**: Only you (or your team) can call the app. Requires a valid API key. * **`shared`**: Any authenticated fal user can call the app. By default, `fal run` uses `public` mode for easy testing during development. # fal runners Source: https://fal.ai/docs/api-reference/cli/runners Manage fal runners from the CLI. List runners by state, read their logs, and show GPU usage. Stop a runner, or open a shell on it. ```bash theme={null} Usage: fal runners [-h] command ... Manage fal runners. Options: -h, --help show this help message and exit Commands: command stop Stop a runner gracefully. kill Kill a runner. list List runners. gpus Show GPU usage summary across runners. logs (log) Show logs for a runner. shell Open a shell on a runner. exec Execute a command on a runner. ``` ## List ```bash theme={null} Usage: fal runners list [-h] [--team TEAM] [--since SINCE] [--state {all,idle,running,pending,setup,crash_backoff,terminated} [...]] [--output {pretty,json}] [--json] List runners. Options: -h, --help show this help message and exit --team TEAM The team to use. --since SINCE Show terminated runners since the given time. Accepts 'now', relative like '30m', '1h', '1d', or an ISO timestamp. Max 24 hours. --state {all,idle,running,pending,setup,crash_backoff,terminated} [{all,idle,running,pending,setup,crash_backoff,terminated} ...] Filter by runner state(s). Choose one or more, or 'all' (default). Output: --output {pretty,json} Modify the command output --json Output in JSON format (same as --output json) ``` The runner table displays the following columns: * **Alias** — Application name * **Machine Type** — Hardware type (e.g. `GPU-A100`, `GPU-H100`) * **Runner ID** — Unique runner identifier * **In Flight Requests** — Number of active requests * **Expires In** — Time until runner expires * **Uptime** — How long the runner has been running * **Revision** — Application revision * **State** — Current runner state ## Logs ```bash theme={null} Usage: fal runners logs [-h] [--output {pretty,json}] [--json] [--team TEAM] [--search SEARCH] [--since SINCE] [--until UNTIL] [--follow] [--lines LINES] id Show logs for a runner. Positional Arguments: id Runner ID. Options: -h, --help show this help message and exit --team TEAM The team to use. --search SEARCH Search for string in logs. --since SINCE Show logs since the given time. Accepts 'now', relative like '30m', '1h', or an ISO timestamp. Defaults to runner start time or to '1m ago' in --follow mode. --until UNTIL Show logs until the given time. Accepts 'now', relative like '30m', '1h', or an ISO timestamp. Defaults to runner finish time or 'now' if it is still running. --follow, -f Follow logs live. If --since is not specified, implies '--since 1m ago'. --lines, -n LINES Only show latest N log lines. If '+' prefix is used, show oldest N log lines. Ignored if --follow is used. Output: --output {pretty,json} Modify the command output --json Output in JSON format (same as --output json) ``` ## Stop ```bash theme={null} Usage: fal runners stop [-h] [--team TEAM] id Stop a runner gracefully. Positional Arguments: id Runner ID. Options: -h, --help show this help message and exit --team TEAM The team to use. ``` ## Kill ```bash theme={null} Usage: fal runners kill [-h] [--team TEAM] id Kill a runner. Positional Arguments: id Runner ID. Options: -h, --help show this help message and exit --team TEAM The team to use. ``` ## Shell ```bash theme={null} Usage: fal runners shell [-h] [--team TEAM] id Open an interactive shell session inside a running runner. Positional Arguments: id Runner ID. Options: -h, --help show this help message and exit --team TEAM The team to use. ``` ### Use Cases * **Debug running code**: Inspect the runtime environment of a live runner * **Check dependencies**: Verify installed packages and their versions * **Examine state**: Inspect files, environment variables, and runtime state * **Troubleshoot issues**: Diagnose problems in production runners ### Example Connect to a running runner: ```bash theme={null} # Get runner ID from runners list fal runners list # Connect to the runner fal runners shell runner_abc123xyz ``` Once connected, you have full shell access within the runner's container environment. Press `Ctrl+D` or type `exit` to disconnect. ## Exec Run a one-off command on a runner without opening an interactive shell. ```bash theme={null} Usage: fal runners exec [-h] [--team TEAM] [-it] id [command ...] Execute a command on a runner. Positional Arguments: id Runner ID. command Command to execute (after `--`). Options: -h, --help show this help message and exit --team TEAM The team to use. -it, --interactive Allocate a TTY and attach stdin (interactive mode). ``` The command and its arguments are passed after a `--` separator so they aren't parsed as flags by the `fal` CLI. ### Examples ```bash theme={null} # Print environment variables on the runner fal runners exec runner_abc123xyz -- env # Tail an arbitrary log file inside the container fal runners exec runner_abc123xyz -- tail -f /var/log/my-app.log # Run an interactive Python REPL fal runners exec runner_abc123xyz -it -- python ``` *** ## GPUs Show a GPU usage summary across all runners in the account. ```bash theme={null} Usage: fal runners gpus [-h] [--output {pretty,json}] [--json] [--team TEAM] Show GPU usage summary across runners. Options: -h, --help show this help message and exit --team TEAM The team to use. Output: --output {pretty,json} Modify the command output --json Output in JSON format (same as --output json) ``` For the GPUs behind a single application rather than the whole account, see [`fal apps gpus`](/docs/api-reference/cli/apps/gpus). # fal secrets Source: https://fal.ai/docs/api-reference/cli/secrets Set, list, and unset secrets for your fal apps with fal secrets. Store values such as HF_TOKEN as NAME=VALUE pairs, and scope each secret to an environment. ```bash theme={null} Usage: fal secrets [-h] [--debug] [--pdb] [--cprofile] command ... Manage fal secrets. Options: -h, --help show this help message and exit Commands: command set Set a secret. list List secrets. unset Unset a secret. ``` ## Set ```bash theme={null} Usage: fal secrets set [-h] [--debug] [--pdb] [--cprofile] [--env ENV] NAME=VALUE [NAME=VALUE ...] Set a secret. Positional Arguments: NAME=VALUE Secret NAME=VALUE pairs. Options: -h, --help show this help message and exit --env ENV Target environment (defaults to main). Examples: fal secrets set HF_TOKEN=hf_*** fal secrets set API_KEY=key123 --env staging ``` ## List ```bash theme={null} Usage: fal secrets list [-h] [--debug] [--pdb] [--cprofile] [--env ENV] List secrets. Options: -h, --help show this help message and exit --env ENV Target environment (defaults to main). Examples: fal secrets list fal secrets list --env staging ``` ## Unset ```bash theme={null} Usage: fal secrets unset [-h] [--debug] [--pdb] [--cprofile] [--env ENV] NAME Unset a secret. Positional Arguments: NAME Secret's name. Options: -h, --help show this help message and exit --env ENV Target environment (defaults to main). Debug: --debug Show verbose errors. --pdb Start pdb on error. --cprofile Show cProfile report. Examples: fal secrets unset HF_TOKEN fal secrets unset API_KEY --env staging ``` # fal account Source: https://fal.ai/docs/api-reference/cli/teams Use fal account to list the personal, team, and organization accounts you belong to. Switch the active account for CLI commands, or go back to your own. Manage and switch between the personal, team, and organization accounts you belong to. Useful when you're a member of multiple accounts and need to deploy or manage apps under a specific one. ## fal account list List all accounts you belong to: ```bash theme={null} fal account list ``` Shows your personal account along with any team and organization accounts, indicating which is currently active. Supports `--output {pretty,json}` and `--json` for machine-readable output. ## fal account set Switch to a specific account: ```bash theme={null} fal account set ``` `` may be either an account nickname or the index shown by `fal account list`. After switching, all CLI operations (`fal deploy`, `fal apps`, `fal secrets`, etc.) run under the selected account. If no `` is provided, you'll be prompted interactively. **Arguments:** | Argument | Description | | - | - | | `account` | The account nickname (or list index) to switch to | **Example:** ```bash theme={null} # Switch to your company team fal account set my-company # Deploy under that team fal deploy my_app.py::MyApp ``` ## fal account unset Switch back to your personal account: ```bash theme={null} fal account unset ``` # Dart Client Source: https://fal.ai/docs/api-reference/client-libraries/dart/index fal client library for Flutter applications The `fal_client` package provides a Dart interface for calling fal AI models in Flutter applications. ## Installation ```bash theme={null} flutter pub add fal_client ``` ## Quick Start ```dart theme={null} import 'package:fal_client/fal_client.dart'; final fal = FalClient.withCredentials("YOUR_FAL_KEY"); final result = await fal.subscribe("fal-ai/flux/dev", input: { "prompt": "a cat", "seed": 6252023, "image_size": "landscape_4_3", "num_images": 4 }); print(result); ``` ## Supported Platforms * Flutter (iOS, Android, Web, Desktop) * Dart (standalone) ## API Reference > [card] [Dart API Reference](https://pub.dev/documentation/fal_client/latest) > > Full API documentation on pub.dev > [card] [GitHub Repository](https://github.com/fal-ai/fal-dart) > > Source code and examples > [card] [Example App](https://pub.dev/packages/fal_client/example) > > Simple Flutter app using fal image inference # Client Libraries Source: https://fal.ai/docs/api-reference/client-libraries/index Libraries for calling fal AI models from your applications Use these libraries to call fal AI models from your applications. Available for multiple languages and platforms. > [card] [Python](/docs/reference/client-libraries/python) > > Python client for fal AI models > [card] [JavaScript](/docs/reference/client-libraries/javascript) > > JS/TS client for web and Node.js ## Mobile & Other Platforms > [card] [Swift](/docs/reference/client-libraries/swift) > > iOS, macOS, tvOS, watchOS > [card] [Kotlin / Java](/docs/reference/client-libraries/kotlin) > > Android and JVM > [card] [Dart](/docs/reference/client-libraries/dart) > > Flutter apps # auth Source: https://fal.ai/docs/api-reference/client-libraries/javascript/auth API reference for @fal-ai/client auth *** ## Functions ### getTemporaryAuthToken ```typescript theme={null} async function getTemporaryAuthToken(app: string, config: RequiredConfig): Promise ``` Get a token to connect to the realtime endpoint. | Parameter | Type | Description | | :- | :- | :- | | `app` | `string` | - | | `config` | `RequiredConfig` | - | **Returns:** `Promise` *** ## Types ### TokenProvider ```typescript theme={null} type TokenProvider = (app: string) => Promise ``` A function that provides a temporary authentication token. # client Source: https://fal.ai/docs/api-reference/client-libraries/javascript/client API reference for @fal-ai/client client ## Classes & Interfaces ### FalClient ```typescript theme={null} interface FalClient ``` The main client type, it provides access to simple API model usage, as well as access to the `queue` and `storage` APIs. > [accordion] Properties > > | Name | Type | Description | > | :- | :- | :- | > | `queue` | `QueueClient` | The queue client to interact with the queue API. | > | `realtime` | `RealtimeClient` | The realtime client to interact with the realtime API and receive updates in real-time. | > | `storage` | `StorageClient` | The storage client to interact with the storage API. | > | `streaming` | `StreamingClient` | The streaming client to interact with the streaming API. | > | `stream` | `StreamingClient["stream"]` | Calls a fal app that supports streaming and provides a streaming-capable object as a result, that can be used to get partial results through either `AsyncIterator` or through an event listener. | > [accordion] Methods > > #### run > > ```typescript theme={null} > run(endpointId: Id, options: RunOptions>): Promise>> > ``` > > Runs a fal endpoint identified by its `endpointId`. > > | Parameter | Type | Description | > | :- | :- | :- | > | `endpointId` | `Id` | The endpoint id, e.g. `fal-ai/fast-sdxl`. | > | `options` | `RunOptions>` | The request options, including the input payload. | > > **Returns:** `Promise>>` > > #### subscribe > > ```typescript theme={null} > subscribe(endpointId: Id, options: RunOptions> & QueueSubscribeOptions): Promise>> > ``` > > Subscribes to updates for a specific request in the queue. > > | Parameter | Type | Description | > | :- | :- | :- | > | `endpointId` | `Id` | - The ID of the API endpoint. | > | `options` | `RunOptions> & QueueSubscribeOptions` | - Options to configure how the request is run and how updates are received. | > > **Returns:** `Promise>>` *** ## Functions ### createFalClient ```typescript theme={null} function createFalClient(userConfig?: Config): FalClient ``` Creates a new reference of the `FalClient`. | Parameter | Type | Description | | :- | :- | :- | | `userConfig` | `Config` | Optional configuration to override the default settings. | **Returns:** `FalClient` # config Source: https://fal.ai/docs/api-reference/client-libraries/javascript/config API reference for @fal-ai/client config *** ## Functions ### resolveDefaultFetch ```typescript theme={null} function resolveDefaultFetch(): FetchType ``` **Returns:** `FetchType` ### createConfig ```typescript theme={null} function createConfig(config: Config): RequiredConfig ``` Configures the fal client. | Parameter | Type | Description | | :- | :- | :- | | `config` | `Config` | the new configuration. | **Returns:** `RequiredConfig` ### getRestApiUrl ```typescript theme={null} function getRestApiUrl(): string ``` **Returns:** `string` *** ## Types ### CredentialsResolver ```typescript theme={null} type CredentialsResolver = () => string | undefined ``` ### ProxyUrlConfig ```typescript theme={null} type ProxyUrlConfig = { /** * The URL of the proxy server. The proxy server should forward the * requests to the fal api. */ url: string; /** * When the proxy middleware should apply. Defaults to `"browser"`. * @see ProxyRuntimeGate */ when?: ProxyRuntimeGate; } ``` Full configuration for the proxy middleware. Use this object form of `proxyUrl` to control when the proxy applies in non-browser runtimes. ### Config ````typescript theme={null} type Config = { /** * The credentials to use for the fal client. When using the * client in the browser, it's recommended to use a proxy server to avoid * exposing the credentials in the client's environment. * * By default it tries to use the `FAL_KEY` environment variable, when * `process.env` is defined. * * @see https://fal.ai/docs/model-endpoints/server-side * @see #suppressLocalCredentialsWarning */ credentials?: undefined | string | CredentialsResolver; /** * Suppresses the warning when the fal credentials are exposed in the * browser's environment. Make sure you understand the security implications * before enabling this option. */ suppressLocalCredentialsWarning?: boolean; /** * The proxy server to use for the client requests. The proxy server should * forward the requests to the fal api. * * Pass a `string` for the common browser-only case — the middleware rewrites * requests to this URL when a DOM `window` is available and does nothing * otherwise (the default, recommended for standard web apps). * * Pass a {@link ProxyUrlConfig} object to opt into non-browser runtimes * (Electron, server, edge/worker, Bun, etc.) via the `when` gate. * * @example Browser-only (unchanged behavior): * ```ts * fal.config({ proxyUrl: "/api/fal/proxy" }); * ``` * * @example Always apply, regardless of runtime: * ```ts * fal.config({ * proxyUrl: { url: "/api/fal/proxy", when: "always" }, * }); * ``` * * @example Custom predicate (e.g. Electron renderer only): * ```ts * fal.config({ * proxyUrl: { * url: "/api/fal/proxy", * when: ({ isBrowser }) => isBrowser || process.type === "renderer", * }, * }); * ``` */ proxyUrl?: string | ProxyUrlConfig; /** * The request middleware to use for the client requests. By default it * doesn't apply any middleware. */ requestMiddleware?: RequestMiddleware; /** * The response handler to use for the client requests. By default it uses * a built-in response handler that returns the JSON response. */ responseHandler?: ResponseHandler; /** * The fetch implementation to use for the client requests. By default it uses * the global `fetch` function. */ fetch?: FetchType; /** * Retry configuration for handling transient errors like rate limiting and server errors. * When not specified, a default retry configuration is used. */ retry?: Partial; } ```` ### RequiredConfig ```typescript theme={null} type RequiredConfig = Required ``` # JavaScript Client Source: https://fal.ai/docs/api-reference/client-libraries/javascript/index API reference for @fal-ai/client The `@fal-ai/client` package provides a TypeScript/JavaScript interface for calling fal AI models. ## Installation ```bash theme={null} npm install @fal-ai/client ``` ## Quick Start ```typescript theme={null} import { fal } from "@fal-ai/client"; const result = await fal.subscribe("fal-ai/flux/dev", { input: { prompt: "a cat wearing a hat", image_size: "landscape_4_3" }, logs: true, onQueueUpdate: (status) => console.log(`Status: ${status.status}`) }); console.log(result.data.images[0].url); ``` ## API Overview | Method | Description | | :- | :- | | `fal.run()` | Run a model synchronously | | `fal.subscribe()` | Run via queue with status updates | | `fal.stream()` | Stream partial results | | `fal.queue.submit()` | Submit to queue, get request ID | | `fal.queue.status()` | Check request status | | `fal.queue.result()` | Get completed result | | `fal.realtime.connect()` | Open realtime WebSocket connection | | `fal.storage.upload()` | Upload file to fal CDN | ## API Reference The following pages contain the auto-generated API reference for all public classes and functions in the `@fal-ai/client` package. # middleware Source: https://fal.ai/docs/api-reference/client-libraries/javascript/middleware API reference for @fal-ai/client middleware *** ## Functions ### withMiddleware ```typescript theme={null} function withMiddleware(middlewares: RequestMiddleware[]): RequestMiddleware ``` Setup a execution chain of middleware functions. | Parameter | Type | Description | | :- | :- | :- | | `middlewares` | `RequestMiddleware[]` | one or more middleware functions. | **Returns:** `RequestMiddleware` ### withProxy ```typescript theme={null} function withProxy(config: RequestProxyConfig): RequestMiddleware ``` | Parameter | Type | Description | | :- | :- | :- | | `config` | `RequestProxyConfig` | - | **Returns:** `RequestMiddleware` *** ## Types ### RequestConfig ```typescript theme={null} type RequestConfig = { url: string; method: string; headers?: Record; } ``` A request configuration object. **Note:** This is a simplified version of the `RequestConfig` type from the `fetch` API. It contains only the properties that are relevant for the fal client. It also works around the fact that the `fetch` API `Request` does not support mutability, its clone method has critical limitations to our use case. ### RequestMiddleware ```typescript theme={null} type RequestMiddleware = ( request: RequestConfig, ) => Promise ``` ### ProxyRuntimeEnv ```typescript theme={null} type ProxyRuntimeEnv = { isBrowser: boolean; } ``` Runtime information passed to a user-provided predicate so it can decide whether the proxy middleware should apply. ### ProxyRuntimeGate ```typescript theme={null} type ProxyRuntimeGate = | "browser" | "always" | ((env: ProxyRuntimeEnv) => boolean) ``` Controls when the proxy middleware applies: * `"browser"` — only when a DOM `window` is available (default). * `"always"` — in every runtime (Node, Electron, Bun, workers, etc.). * A predicate receiving — full control per call. ### RequestProxyConfig ```typescript theme={null} type RequestProxyConfig = { targetUrl: string; when?: ProxyRuntimeGate; } ``` # queue Source: https://fal.ai/docs/api-reference/client-libraries/javascript/queue API reference for @fal-ai/client queue ## Classes & Interfaces ### QueueClient ```typescript theme={null} interface QueueClient ``` Represents a request queue with methods for submitting requests, checking their status, retrieving results, and subscribing to updates. > [accordion] Methods > > #### submit > > ```typescript theme={null} > submit(endpointId: Id, options: SubmitOptions>): Promise > ``` > > Submits a request to the queue. > > | Parameter | Type | Description | > | :- | :- | :- | > | `endpointId` | `Id` | - The ID of the function web endpoint. | > | `options` | `SubmitOptions>` | - Options to configure how the request is run. | > > **Returns:** `Promise` > > #### status > > ```typescript theme={null} > status(endpointId: string, options: QueueStatusOptions): Promise > ``` > > Retrieves the status of a specific request in the queue. > > | Parameter | Type | Description | > | :- | :- | :- | > | `endpointId` | `string` | - The ID of the function web endpoint. | > | `options` | `QueueStatusOptions` | - Options to configure how the request is run. | > > **Returns:** `Promise` > > #### streamStatus > > ```typescript theme={null} > streamStatus(endpointId: string, options: QueueStatusStreamOptions): Promise> > ``` > > Subscribes to updates for a specific request in the queue using HTTP streaming events. > > | Parameter | Type | Description | > | :- | :- | :- | > | `endpointId` | `string` | - The ID of the function web endpoint. | > | `options` | `QueueStatusStreamOptions` | - Options to configure how the request is run and how updates are received. | > > **Returns:** `Promise>` > > #### subscribeToStatus > > ```typescript theme={null} > subscribeToStatus(endpointId: string, options: QueueStatusSubscriptionOptions): Promise > ``` > > Subscribes to updates for a specific request in the queue using polling or streaming. > See `options.mode` for more details. > > | Parameter | Type | Description | > | :- | :- | :- | > | `endpointId` | `string` | - The ID of the function web endpoint. | > | `options` | `QueueStatusSubscriptionOptions` | - Options to configure how the request is run and how updates are received. | > > **Returns:** `Promise` > > #### result > > ```typescript theme={null} > result(endpointId: Id, options: BaseQueueOptions): Promise>> > ``` > > Retrieves the result of a specific request from the queue. > > | Parameter | Type | Description | > | :- | :- | :- | > | `endpointId` | `Id` | - The ID of the function web endpoint. | > | `options` | `BaseQueueOptions` | - Options to configure how the request is run. | > > **Returns:** `Promise>>` > > #### cancel > > ```typescript theme={null} > cancel(endpointId: string, options: BaseQueueOptions): Promise > ``` > > Cancels a request in the queue. > > | Parameter | Type | Description | > | :- | :- | :- | > | `endpointId` | `string` | - The ID of the function web endpoint. | > | `options` | `BaseQueueOptions` | - Options to configure how the request is run and how updates are received. | > > **Returns:** `Promise` *** ## Types ### QueuePriority ```typescript theme={null} type QueuePriority = "low" | "normal" ``` ### QueueStatusSubscriptionOptions ```typescript theme={null} type QueueStatusSubscriptionOptions = QueueStatusOptions & QueueModeOptions & Omit ``` ### QueueSubscribeOptions ```typescript theme={null} type QueueSubscribeOptions = QueueCommonSubscribeOptions & QueueModeOptions ``` Options for subscribing to the request queue. ### SubmitOptions ```typescript theme={null} type SubmitOptions = RunOptions & { /** * The URL to send a webhook notification to when the request is completed. * @see WebHookResponse */ webhookUrl?: string; /** * The priority of the request. It defaults to `normal`. * This will be sent as the `x-fal-queue-priority` header. * * @see QueuePriority */ priority?: QueuePriority; /** * A hint for the runner to use when processing the request. * This will be sent as the `x-fal-runner-hint` header. */ hint?: string; /** * Server-side request timeout in seconds. Limits total time spent waiting * before processing starts (includes queue wait, retries, and routing). * Does not apply once the application begins processing. * * This will be sent as the `x-fal-request-start-timeout` header. */ startTimeout?: number; /** * Additional HTTP headers to include in the submit request. * * Note: `priority`, `hint`, `startTimeout`, and `objectLifecycle` will override the following headers: * - `x-fal-queue-priority` * - `x-fal-runner-hint` * - `x-fal-request-start-timeout` * - `x-fal-object-lifecycle-preference` */ headers?: Record; } ``` Options for submitting a request to the queue. ### QueueStatusOptions ```typescript theme={null} type QueueStatusOptions = BaseQueueOptions & { /** * If `true`, the response will include the logs for the request. * Defaults to `false`. */ logs?: boolean; } ``` ### QueueStatusStreamOptions ```typescript theme={null} type QueueStatusStreamOptions = QueueStatusOptions & { /** * The connection mode to use for streaming updates. It defaults to `server`. * Set to `client` if your server proxy doesn't support streaming. */ connectionMode?: StreamingConnectionMode; } ``` # realtime Source: https://fal.ai/docs/api-reference/client-libraries/javascript/realtime API reference for @fal-ai/client realtime ## Classes & Interfaces ### RealtimeConnection ```typescript theme={null} interface RealtimeConnection ``` A connection object that allows you to `send` request payloads to a realtime endpoint. > [accordion] Methods > > #### send > > ```typescript theme={null} > send(input: Input & Partial): void > ``` > > | Parameter | Type | Description | > | :- | :- | :- | > | `input` | `Input & Partial` | - | > > #### close > > ```typescript theme={null} > close(): void > ``` ### RealtimeConnectionHandler ```typescript theme={null} interface RealtimeConnectionHandler ``` Options for connecting to the realtime endpoint. > [accordion] Properties > > | Name | Type | Description | > | :- | :- | :- | > | `connectionKey?` | `string` | The connection key. This is used to reuse the same connection across multiple calls to `connect`. This is particularly useful in contexts where the connection is established as part of a component lifecycle (e.g. React) and the component is re-rendered multiple times. | > | `clientOnly?` | `boolean` | If `true`, the connection will only be established on the client side. This is useful for frameworks that reuse code for both server-side rendering and client-side rendering (e.g. Next.js). This is set to `true` by default when running on React in the server. Otherwise, it is set to `false`. Note that more SSR frameworks might be automatically detected in the future. In the meantime, you can set this to `true` when needed. | > | `throttleInterval?` | `number` | The throtle duration in milliseconds. This is used to throtle the calls to the `send` function. Realtime apps usually react to user input, which can be very frequent (e.g. fast typing or mouse/drag movements). The default value is `128` milliseconds. | > | `maxBuffering?` | `number` | Configures the maximum amount of frames to store in memory before starting to drop old ones for in favor of the newer ones. It must be between `1` and `60`. The recommended is `2`. The default is `undefined` so it can be determined by the app (normally is set to the recommended setting). | > | `path?` | `string` | Optional path to append after the app id. Defaults to `/realtime`. | > | `encodeMessage?` | `(input: any) => Uint8Array \| string` | Optional encoder for outgoing messages. Defaults to msgpack. Should return either a `Uint8Array` (binary) or string (text frame). | > | `decodeMessage?` | `(data: any) => Promise \| any` | Optional decoder for incoming messages. Defaults to msgpack with JSON support for string payloads. | > | `tokenProvider?` | `TokenProvider` | A custom token provider function. When provided, this function will be used to fetch authentication tokens instead of the default internal token fetching mechanism. This is useful when you want to fetch tokens through your own backend proxy. If not provided, the default `getTemporaryAuthToken` will be used. | > | `tokenExpirationSeconds?` | `number` | The token expiration time in seconds. This is used to determine when to refresh the token. The token will be refreshed at 90% of this value. Only relevant when using a custom `tokenProvider`. If a custom `tokenProvider` is used without specifying this value, automatic token refresh will be disabled. | > [accordion] Methods > > #### onResult > > ```typescript theme={null} > onResult(result: Output & WithRequestId): void > ``` > > Callback function that is called when a result is received. > > | Parameter | Type | Description | > | :- | :- | :- | > | `result` | `Output & WithRequestId` | - The result of the request. | > > #### onError > > ```typescript theme={null} > onError(error: ApiError): void > ``` > > Callback function that is called when an error occurs. > > | Parameter | Type | Description | > | :- | :- | :- | > | `error` | `ApiError` | - The error that occurred. | ### RealtimeClient ```typescript theme={null} interface RealtimeClient ``` > [accordion] Methods > > #### connect > > ```typescript theme={null} > connect(app: string, handler: RealtimeConnectionHandler): RealtimeConnection > ``` > > Connect to the realtime endpoint. The default implementation uses > WebSockets to connect to fal function endpoints that support WSS. > > | Parameter | Type | Description | > | :- | :- | :- | > | `app` | `string` | the app alias or identifier. | > | `handler` | `RealtimeConnectionHandler` | the connection handler. | > > **Returns:** `RealtimeConnection` *** ## Functions ### createRealtimeClient ```typescript theme={null} function createRealtimeClient({ config, }: RealtimeClientDependencies): RealtimeClient ``` | Parameter | Type | Description | | :- | :- | :- | | `{ config, }` | `RealtimeClientDependencies` | - | **Returns:** `RealtimeClient` # response Source: https://fal.ai/docs/api-reference/client-libraries/javascript/response API reference for @fal-ai/client response ## Classes & Interfaces ### ApiError ```typescript theme={null} interface ApiError ``` > [accordion] Properties > > | Name | Type | Description | > | :- | :- | :- | > | `status` | `number` | - | > | `body` | `Body` | - | > | `requestId` | `string` | - | > | `timeoutType?` | `string` | - | ### ValidationError ```typescript theme={null} interface ValidationError ``` > [accordion] Methods > > #### getFieldErrors > > ```typescript theme={null} > getFieldErrors(field: string): ValidationErrorInfo[] > ``` > > | Parameter | Type | Description | > | :- | :- | :- | > | `field` | `string` | - | > > **Returns:** `ValidationErrorInfo[]` *** ## Functions ### defaultResponseHandler ```typescript theme={null} async function defaultResponseHandler(response: Response): Promise ``` | Parameter | Type | Description | | :- | :- | :- | | `response` | `Response` | - | **Returns:** `Promise` ### resultResponseHandler ```typescript theme={null} async function resultResponseHandler(response: Response): Promise> ``` | Parameter | Type | Description | | :- | :- | :- | | `response` | `Response` | - | **Returns:** `Promise>` *** ## Types ### ResponseHandler ```typescript theme={null} type ResponseHandler = (response: Response) => Promise ``` ### ResponseHandlerCreator ```typescript theme={null} type ResponseHandlerCreator = ( config: RequiredConfig, ) => ResponseHandler ``` # retry Source: https://fal.ai/docs/api-reference/client-libraries/javascript/retry API reference for @fal-ai/client retry ## Classes & Interfaces ### RetryMetrics ```typescript theme={null} interface RetryMetrics ``` Retry metrics for tracking retry attempts > [accordion] Properties > > | Name | Type | Description | > | :- | :- | :- | > | `totalAttempts` | `number` | - | > | `totalDelay` | `number` | - | > | `lastError?` | `any` | - | *** ## Functions ### isRetryableNetworkError ```typescript theme={null} function isRetryableNetworkError(error: unknown): boolean ``` Returns true for transient transport-level failures (connection resets, DNS hiccups, socket timeouts, etc.). Mirrors the Python client's behavior of retrying `httpx.TransportError` and `httpx.TimeoutException`. | Parameter | Type | Description | | :- | :- | :- | | `error` | `unknown` | - | **Returns:** `boolean` ### isRetryableError ```typescript theme={null} function isRetryableError(error: any, retryableStatusCodes: number[]): boolean ``` Determines if an error is retryable based on the status code or, for non-HTTP failures, on the underlying transport error. User-specified timeouts (504 with X-Fal-Request-Timeout-Type: user) are NOT retryable. | Parameter | Type | Description | | :- | :- | :- | | `error` | `any` | - | | `retryableStatusCodes` | `number[]` | - | **Returns:** `boolean` ### calculateBackoffDelay ```typescript theme={null} function calculateBackoffDelay(attempt: number, baseDelay: number, maxDelay: number, backoffMultiplier: number, enableJitter: boolean): number ``` Calculates the backoff delay for a given attempt using exponential backoff | Parameter | Type | Description | | :- | :- | :- | | `attempt` | `number` | - | | `baseDelay` | `number` | - | | `maxDelay` | `number` | - | | `backoffMultiplier` | `number` | - | | `enableJitter` | `boolean` | - | **Returns:** `number` ### executeWithRetry ```typescript theme={null} async function executeWithRetry(operation: () => Promise, options: RetryOptions, onRetry?: (attempt: number, error: any, delay: number) => void): Promise<{ result: T; metrics: RetryMetrics }> ``` Executes an operation with retry logic and returns both result and metrics | Parameter | Type | Description | | :- | :- | :- | | `operation` | `() => Promise` | - | | `options` | `RetryOptions` | - | | `onRetry` | `(attempt: number, error: any, delay: number) => void` | - | **Returns:** `Promise<{ result: T; metrics: RetryMetrics }>` *** ## Types ### RetryOptions ```typescript theme={null} type RetryOptions = { maxRetries: number; baseDelay: number; maxDelay: number; backoffMultiplier: number; retryableStatusCodes: number[]; enableJitter: boolean; } ``` # storage Source: https://fal.ai/docs/api-reference/client-libraries/javascript/storage API reference for @fal-ai/client storage ## Classes & Interfaces ### StorageACLRule ```typescript theme={null} interface StorageACLRule ``` > [accordion] Properties > > | Name | Type | Description | > | :- | :- | :- | > | `user` | `string` | - | > | `decision` | `StorageACLDecision` | - | ### StorageACL ```typescript theme={null} interface StorageACL ``` > [accordion] Properties > > | Name | Type | Description | > | :- | :- | :- | > | `default?` | `StorageACLDecision` | - | > | `rules?` | `StorageACLRule[]` | - | ### StorageSettings ```typescript theme={null} interface StorageSettings ``` Configuration for object lifecycle and storage behavior. > [accordion] Properties > > | Name | Type | Description | > | :- | :- | :- | > | `expiresIn?` | `ObjectExpiration` | The expiration time for the stored files (images, videos, etc.). You can specify one of the enumerated values or a number of seconds. | > | `initialAcl?` | `StorageACL` | Optional ACL configuration applied to the uploaded object. | ### StorageClient ```typescript theme={null} interface StorageClient ``` File support for the client. This interface establishes the contract for uploading files to the server and transforming the input to replace file objects with URLs. > [accordion] Properties > > | Name | Type | Description | > | :- | :- | :- | > | `upload` | `(file: Blob, options?: UploadOptions) => Promise` | Upload a file to the server. Returns the URL of the uploaded file. | > | `transformInput` | `(input: Record) => Promise>` | Transform the input to replace file objects with URLs. This is used to transform the input before sending it to the server and ensures that the server receives URLs instead of file objects. | *** ## Functions ### getExpirationDurationSeconds ```typescript theme={null} function getExpirationDurationSeconds(lifecycle: StorageSettings): number | undefined ``` Converts an `StorageSettings` to the expiration duration in seconds. | Parameter | Type | Description | | :- | :- | :- | | `lifecycle` | `StorageSettings` | the lifecycle preference | **Returns:** `number | undefined` ### buildObjectLifecycleHeaders ```typescript theme={null} function buildObjectLifecycleHeaders(lifecycle: StorageSettings | undefined): Record ``` Builds the headers for the Object Lifecycle preference to be used in API requests. This is used by the queue and run APIs to control the lifecycle of generated objects. | Parameter | Type | Description | | :- | :- | :- | | `lifecycle` | `StorageSettings \| undefined` | the lifecycle preference | **Returns:** `Record` ### createStorageClient ```typescript theme={null} function createStorageClient({ config, }: StorageClientDependencies): StorageClient ``` | Parameter | Type | Description | | :- | :- | :- | | `{ config, }` | `StorageClientDependencies` | - | **Returns:** `StorageClient` *** ## Types ### UploadOptions ```typescript theme={null} type UploadOptions = { /** * Custom lifecycle configuration for the uploaded file. * This object will be sent as the X-Fal-Object-Lifecycle header. */ lifecycle?: StorageSettings; } ``` Options for uploading a file. # streaming Source: https://fal.ai/docs/api-reference/client-libraries/javascript/streaming API reference for @fal-ai/client streaming ## Classes & Interfaces ### FalStream ```typescript theme={null} interface FalStream ``` The class representing a streaming response. With t > [accordion] Properties > > | Name | Type | Description | > | :- | :- | :- | > | `config` | `RequiredConfig` | - | > | `endpointId` | `string` | - | > | `url` | `string` | - | > | `options` | `StreamOptions` | - | > | `listeners` | `Map` | - | > | `buffer` | `Output[]` | - | > | `currentData` | `Output \| undefined` | - | > | `lastEventTimestamp` | `any` | - | > | `streamClosed` | `any` | - | > | `_requestId` | `string \| null` | - | > | `donePromise` | `Promise` | - | > | `abortController` | `any` | - | > | `start` | `any` | - | > | `handleResponse` | `any` | - | > | `handleError` | `any` | - | > | `on` | `any` | - | > | `emit` | `any` | - | > | `done` | `any` | Gets a reference to the `Promise` that indicates whether the streaming is done or not. Developers should always call this in their apps to ensure the request is over. An alternative to this, is to use `on('done')` in case your application architecture works best with event listeners. | > | `abort` | `any` | Aborts the streaming request. **Note:** This method is noop in case the request is already done. | > [accordion] Methods > > #### `[Symbol.asyncIterator]` > > ```typescript theme={null} > async [Symbol.asyncIterator](): any > ``` > > **Returns:** `any` ### StreamingClient ```typescript theme={null} interface StreamingClient ``` The streaming client interface. > [accordion] Methods > > #### stream > > ```typescript theme={null} > stream(endpointId: Id, options: StreamOptions>): Promise, OutputType>> > ``` > > Calls a fal app that supports streaming and provides a streaming-capable > object as a result, that can be used to get partial results through either > `AsyncIterator` or through an event listener. > > | Parameter | Type | Description | > | :- | :- | :- | > | `endpointId` | `Id` | the endpoint id, e.g. `fal-ai/llavav15-13b`. | > | `options` | `StreamOptions>` | the request options, including the input payload. | > > **Returns:** `Promise, OutputType>>` *** ## Functions ### createStreamingClient ```typescript theme={null} function createStreamingClient({ config, storage, }: StreamingClientDependencies): StreamingClient ``` | Parameter | Type | Description | | :- | :- | :- | | `{ config, storage, }` | `StreamingClientDependencies` | - | **Returns:** `StreamingClient` *** ## Types ### StreamingConnectionMode ```typescript theme={null} type StreamingConnectionMode = "client" | "server" ``` ### StreamOptions ```typescript theme={null} type StreamOptions = { /** * The endpoint URL. If not provided, it will be generated from the * `endpointId` and the `queryParams`. */ readonly url?: string; /** * The API input payload. */ readonly input?: Input; /** * The query parameters to be sent with the request. */ readonly queryParams?: Record; /** * The maximum time interval in milliseconds between stream chunks. Defaults to 15s. */ readonly timeout?: number; /** * Whether it should auto-upload File-like types to fal's storage * or not. */ readonly autoUpload?: boolean; /** * The HTTP method, defaults to `post`; */ readonly method?: "get" | "post" | "put" | "delete" | string; /** * The content type the client accepts as response. * By default this is set to `text/event-stream`. */ readonly accept?: string; /** * The streaming connection mode. This is used to determine * whether the streaming will be done from the browser itself (client) * or through your own server, either when running on NodeJS or when * using a proxy that supports streaming. * * It defaults to `server`. Set to `client` if your server proxy doesn't * support streaming. */ readonly connectionMode?: StreamingConnectionMode; /** * The signal to abort the request. */ readonly signal?: AbortSignal; /** * A custom token provider function. Only used when `connectionMode` is `"client"`. * When provided, this function will be used to fetch authentication tokens * instead of the default internal token fetching mechanism. */ readonly tokenProvider?: TokenProvider; } ``` The stream API options. It requires the API input and also offers configuration options. # types.client Source: https://fal.ai/docs/api-reference/client-libraries/javascript/types.client API reference for @fal-ai/client types.client *** ## Types ### EndpointType ```typescript theme={null} type EndpointType = keyof EndpointTypeMap | (string & {}) ``` ### InputType ```typescript theme={null} type InputType = T extends keyof EndpointTypeMap ? EndpointTypeMap[T]["input"] : Record ``` ### OutputType ```typescript theme={null} type OutputType = T extends keyof EndpointTypeMap ? EndpointTypeMap[T]["output"] : any ``` # types.common Source: https://fal.ai/docs/api-reference/client-libraries/javascript/types.common API reference for @fal-ai/client types.common ## Classes & Interfaces ### InQueueQueueStatus ```typescript theme={null} interface InQueueQueueStatus ``` > [accordion] Properties > > | Name | Type | Description | > | :- | :- | :- | > | `status` | `"IN_QUEUE"` | - | > | `queue_position` | `number` | - | ### InProgressQueueStatus ```typescript theme={null} interface InProgressQueueStatus ``` > [accordion] Properties > > | Name | Type | Description | > | :- | :- | :- | > | `status` | `"IN_PROGRESS"` | - | > | `logs` | `RequestLog[]` | - | ### CompletedQueueStatus ```typescript theme={null} interface CompletedQueueStatus ``` > [accordion] Properties > > | Name | Type | Description | > | :- | :- | :- | > | `status` | `"COMPLETED"` | - | > | `logs` | `RequestLog[]` | - | > | `metrics?` | `Metrics` | - | *** ## Functions ### isQueueStatus ```typescript theme={null} function isQueueStatus(obj: any): obj is QueueStatus ``` | Parameter | Type | Description | | :- | :- | :- | | `obj` | `any` | - | **Returns:** `obj is QueueStatus` ### isCompletedQueueStatus ```typescript theme={null} function isCompletedQueueStatus(obj: any): obj is CompletedQueueStatus ``` | Parameter | Type | Description | | :- | :- | :- | | `obj` | `any` | - | **Returns:** `obj is CompletedQueueStatus` *** ## Types ### Result ```typescript theme={null} type Result = { data: T; requestId: string; } ``` Represents an API result, containing the data, the request ID and any other relevant information. ### RunOptions ```typescript theme={null} type RunOptions = { /** * The function input. It will be submitted either as query params * or the body payload, depending on the `method`. */ readonly input?: Input; /** * The HTTP method, defaults to `post`; */ readonly method?: "get" | "post" | "put" | "delete" | string; /** * The abort signal to cancel the request. */ readonly abortSignal?: AbortSignal; /** * Object lifecycle configuration for controlling how long generated objects * (images, files, etc.) remain available before expiring. * * @see StorageSettings * @see https://docs.fal.ai/model-apis/model-endpoints/queue#object-lifecycle */ readonly storageSettings?: StorageSettings; /** * Server-side request timeout in seconds. Limits total time spent waiting * before processing starts (includes queue wait, retries, and routing). * Does not apply once the application begins processing. * * This will be sent as the `x-fal-request-start-timeout` header. */ readonly startTimeout?: number; } ``` The function input and other configuration when running the function, such as the HTTP method to use. ### UrlOptions ```typescript theme={null} type UrlOptions = { /** * If `true`, the function will use the queue to run the function * asynchronously and return the result in a separate call. This * influences how the URL is built. */ readonly subdomain?: string; /** * The query parameters to include in the URL. */ readonly query?: Record; /** * The path to append to the function URL. */ path?: string; } ``` ### RequestLog ```typescript theme={null} type RequestLog = { message: string; level: "STDERR" | "STDOUT" | "ERROR" | "INFO" | "WARN" | "DEBUG"; source: "USER"; timestamp: string; // Using string to represent date-time format, but you could also use 'Date' type if you're going to construct Date objects. } ``` ### Metrics ```typescript theme={null} type Metrics = { inference_time: number | null; } ``` ### QueueStatus ```typescript theme={null} type QueueStatus = | InProgressQueueStatus | CompletedQueueStatus | InQueueQueueStatus ``` ### ValidationErrorInfo ```typescript theme={null} type ValidationErrorInfo = { msg: string; loc: Array; type: string; } ``` ### WebHookResponse ```typescript theme={null} type WebHookResponse = | { /** Indicates a successful response. */ status: "OK"; /** The payload of the response, structure determined by the Payload type. */ payload: Payload; /** Error is never present in a successful response. */ error: never; /** The unique identifier for the request. */ request_id: string; } | { /** Indicates an unsuccessful response. */ status: "ERROR"; /** The payload of the response, structure determined by the Payload type. */ payload: Payload; /** Description of the error that occurred. */ error: string; /** The unique identifier for the request. */ request_id: string; } ``` Represents the response from a WebHook request. This is a union type that varies based on the `status` property. # utils Source: https://fal.ai/docs/api-reference/client-libraries/javascript/utils API reference for @fal-ai/client utils *** ## Functions ### ensureEndpointIdFormat ```typescript theme={null} function ensureEndpointIdFormat(id: string): string ``` | Parameter | Type | Description | | :- | :- | :- | | `id` | `string` | - | **Returns:** `string` ### parseEndpointId ```typescript theme={null} function parseEndpointId(id: string): EndpointId ``` | Parameter | Type | Description | | :- | :- | :- | | `id` | `string` | - | **Returns:** `EndpointId` ### resolveEndpointPath ```typescript theme={null} function resolveEndpointPath(app: string, path: string | undefined, defaultPath: string): string | undefined ``` Resolves the endpoint path, normalizing it and applying a default. If no explicit path is provided and the app already ends with the default path, returns undefined to avoid duplication. | Parameter | Type | Description | | :- | :- | :- | | `app` | `string` | - The app/endpoint identifier | | `path` | `string \| undefined` | - An explicitly provided path (always used if present) | | `defaultPath` | `string` | - The default path to use (e.g. "/realtime") | **Returns:** `string | undefined` ### isValidUrl ```typescript theme={null} function isValidUrl(url: string): any ``` | Parameter | Type | Description | | :- | :- | :- | | `url` | `string` | - | **Returns:** `any` ### throttle ```typescript theme={null} function throttle(func: T, limit: number, leading?: any): (...funcArgs: Parameters) => ReturnType | void ``` | Parameter | Type | Description | | :- | :- | :- | | `func` | `T` | - | | `limit` | `number` | - | | `leading` | `any` | - | **Returns:** `(...funcArgs: Parameters) => ReturnType | void` ### isReact ```typescript theme={null} function isReact(): any ``` Not really the most optimal way to detect if we're running in React, but the idea here is that we can support multiple rendering engines (starting with React), with all their peculiarities, without having to add a dependency or creating custom integrations (e.g. custom hooks). Yes, a bit of magic to make things works out-of-the-box. **Returns:** `any` ### isPlainObject ```typescript theme={null} function isPlainObject(value: any): boolean ``` Check if a value is a plain object. | Parameter | Type | Description | | :- | :- | :- | | `value` | `any` | - The value to check. | **Returns:** `boolean` ### sleep ```typescript theme={null} async function sleep(ms: number): Promise ``` Utility function to sleep for a given number of milliseconds | Parameter | Type | Description | | :- | :- | :- | | `ms` | `number` | - | **Returns:** `Promise` *** ## Types ### EndpointId ```typescript theme={null} type EndpointId = { readonly owner: string; readonly alias: string; readonly path?: string; readonly namespace?: EndpointNamespace; } ``` # Kotlin / Java Client Source: https://fal.ai/docs/api-reference/client-libraries/kotlin/index fal client library for Android and JVM applications The `fal-client` packages provide Kotlin and Java interfaces for calling fal AI models on Android and JVM platforms. ## Installation ```groovy Gradle (Kotlin) theme={null} implementation 'ai.fal.client:fal-client-kotlin:0.7.1' ``` ```groovy Gradle (Java) theme={null} implementation 'ai.fal.client:fal-client:0.7.1' ``` ```xml Maven (Kotlin) theme={null} ai.fal.client fal-client-kotlin 0.7.1 ``` ```xml Maven (Java) theme={null} ai.fal.client fal-client 0.7.1 ``` > [!NOTE] > > **Java Async Support** > > If your code relies on asynchronous operations via `CompletableFuture` or `Future`, use the `ai.fal.client:fal-client-async` artifact instead. ## Quick Start ```kotlin Kotlin theme={null} import ai.fal.client.kt val fal = createFalClient() val input = mapOf( "prompt" to "a cat", "seed" to 6252023, "image_size" to "landscape_4_3", "num_images" to 4 ) val result = fal.subscribe("fal-ai/flux/dev", input, options = SubscribeOptions( logs = true )) { update -> if (update is QueueStatus.InProgress) { println(update.logs) } } ``` ```java Java theme={null} import ai.fal.client.*; import ai.fal.client.queue.*; var fal = FalClient.withEnvCredentials(); var input = Map.of( "prompt", "a cat", "seed", 6252023, "image_size", "landscape_4_3", "num_images", 4 ); var result = fal.subscribe("fal-ai/flux/dev", SubscribeOptions.builder() .input(input) .logs(true) .resultType(JsonObject.class) .onQueueUpdate(update -> { if (update instanceof QueueStatus.InProgress) { System.out.println(((QueueStatus.InProgress) update).getLogs()); } }) .build() ); ``` ## Supported Platforms * Android (API 21+) * JVM (Java 11+) * Kotlin Multiplatform (JVM target) ## API Reference > [card] [Java API Reference](https://fal-ai.github.io/fal-java/fal-client/index.html) > > JavaDoc documentation > [card] [Kotlin API Reference](https://fal-ai.github.io/fal-java/fal-client-kotlin/fal-client-kotlin/ai.fal.client.kt/index.html) > > KDoc documentation > [card] [GitHub Repository](https://github.com/fal-ai/fal-java) > > Source code and examples # fal_client Source: https://fal.ai/docs/api-reference/client-libraries/python/fal_client API reference for fal_client ```python theme={null} from fal_client import ( SyncClient, AsyncClient, RealtimeConnection, AsyncRealtimeConnection, Status, Queued, InProgress, Completed, FalClientError, FalClientHTTPError, FalClientTimeoutError, StorageACL, StorageACLRule, StorageSettings, SyncRequestHandle, AsyncRequestHandle, run, subscribe_async, subscribe, submit, stream, run_async, submit_async, stream_async, realtime, realtime_async, cancel, cancel_async, status, status_async, result, result_async, encode, encode_file, encode_image, set_get_current_app, ) ``` ## Classes ### SyncClient ```python theme={null} class fal_client.SyncClient ``` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `key` | `Optional[str]` | `None` | - | > | `default_timeout` | `float` | `120.0` | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `key` | `str \| None` | `None` | - | > | `default_timeout` | `float` | `120.0` | - | > [accordion] Properties > > | Name | Type | Description | > | :- | :- | :- | > | `_executor` | `ThreadPoolExecutor` | - | > [accordion] Methods > > #### cancel > > ```python theme={null} > def cancel(self, application: 'str', request_id: 'str') -> 'None' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `application` | `str` | - | - | > | `request_id` | `str` | - | - | > > **Returns:** `NoneType` > > #### get\_handle > > ```python theme={null} > def get_handle(self, application: 'str', request_id: 'str') -> 'SyncRequestHandle' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `application` | `str` | - | - | > | `request_id` | `str` | - | - | > > **Returns:** `SyncRequestHandle` > > #### realtime > > ```python theme={null} > def realtime(self, application: 'str', *, use_jwt: 'bool' = True, path: 'str' = '/realtime', max_buffering: 'int | None' = None, token_expiration: 'int' = 120, encode_message: 'Callable[[Any], bytes] | None' = None, decode_message: 'Callable[[bytes], Any] | None' = None) -> 'Iterator[RealtimeConnection]' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `application` | `str` | - | - | > | `use_jwt` | `bool` | `True` | - | > | `path` | `str` | `'/realtime'` | - | > | `max_buffering` | `Optional[int]` | `None` | - | > | `token_expiration` | `int` | `120` | - | > | `encode_message` | `Optional[Callable[Any, bytes]]` | `None` | - | > | `decode_message` | `Optional[Callable[bytes, Any]]` | `None` | - | > > **Returns:** `Iterator[RealtimeConnection]` > > #### result > > ```python theme={null} > def result(self, application: 'str', request_id: 'str') -> 'AnyJSON' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `application` | `str` | - | - | > | `request_id` | `str` | - | - | > > **Returns:** `dict[str, Any]` > > #### run > > ```python theme={null} > def run(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', timeout: 'Optional[Union[int, float]]' = None, start_timeout: 'Optional[Union[int, float]]' = None, hint: 'str | None' = None, headers: 'dict[str, str]' = {}) -> 'AnyJSON' > ``` > > Run an application with the given arguments (which will be JSON serialized). > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `application` | `str` | - | - | > | `arguments` | `dict[str, Any]` | - | - | > | `path` | `str` | `''` | - | > | `timeout` | `int \| float \| NoneType` | `None` | Client-side HTTP timeout in seconds. Controls how long the HTTP client waits for a response. Defaults to the client's default\_timeout. | > | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts. Does not apply once the application begins processing. | > | `hint` | `Optional[str]` | `None` | - | > | `headers` | `dict[str, str]` | `\{\}` | - | > > **Returns:** `dict[str, Any]` > > #### status > > ```python theme={null} > def status(self, application: 'str', request_id: 'str', *, with_logs: 'bool' = False) -> 'Status' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `application` | `str` | - | - | > | `request_id` | `str` | - | - | > | `with_logs` | `bool` | `False` | - | > > **Returns:** `Status` > > #### stream > > ```python theme={null} > def stream(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '/stream', timeout: 'float | None' = None, headers: 'dict[str, str]' = {}) -> 'Iterator[dict[str, Any]]' > ``` > > Stream the output of an application with the given arguments (which will be JSON serialized). This is only supported at a few select applications at the moment, so be sure to first consult with the documentation of individual applications > to see if this is supported. > > The function will iterate over each event that is streamed from the server. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `application` | `str` | - | - | > | `arguments` | `dict[str, Any]` | - | - | > | `path` | `str` | `'/stream'` | - | > | `timeout` | `Optional[float]` | `None` | - | > | `headers` | `dict[str, str]` | `\{\}` | - | > > **Returns:** `Iterator[dict[str, Any]]` > > #### submit > > ```python theme={null} > def submit(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', hint: 'str | None' = None, webhook_url: 'str | None' = None, priority: 'Optional[Priority]' = None, headers: 'dict[str, str]' = {}, start_timeout: 'Optional[Union[int, float]]' = None) -> 'SyncRequestHandle' > ``` > > Submit an application with the given arguments (which will be JSON serialized). > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `application` | `str` | - | - | > | `arguments` | `dict[str, Any]` | - | - | > | `path` | `str` | `''` | - | > | `hint` | `Optional[str]` | `None` | - | > | `webhook_url` | `Optional[str]` | `None` | - | > | `priority` | `Optional[Literal[normal, low]]` | `None` | - | > | `headers` | `dict[str, str]` | `\{\}` | - | > | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts (includes queue wait, retries, and routing). Does not apply once the application begins processing. | > > **Returns:** `SyncRequestHandle` > > #### subscribe > > ```python theme={null} > def subscribe(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', hint: 'str | None' = None, with_logs: 'bool' = False, interval: 'float' = 0.1, on_enqueue: 'Optional[Callable[[str], None]]' = None, on_queue_update: 'Optional[Callable[[Status], None]]' = None, priority: 'Optional[Priority]' = None, headers: 'dict[str, str]' = {}, start_timeout: 'Optional[Union[int, float]]' = None, client_timeout: 'Optional[Union[int, float]]' = None) -> 'AnyJSON' > ``` > > Subscribe to an application and wait for the result. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `application` | `str` | - | - | > | `arguments` | `dict[str, Any]` | - | - | > | `path` | `str` | `''` | - | > | `hint` | `Optional[str]` | `None` | - | > | `with_logs` | `bool` | `False` | - | > | `interval` | `float` | `0.1` | Polling interval in seconds while waiting for request updates. | > | `on_enqueue` | `Optional[Callable[str, NoneType]]` | `None` | - | > | `on_queue_update` | `Optional[Callable[Status, NoneType]]` | `None` | - | > | `priority` | `Optional[Literal[normal, low]]` | `None` | - | > | `headers` | `dict[str, str]` | `\{\}` | - | > | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts (includes queue wait, retries, and routing). Does not apply once the application begins processing. | > | `client_timeout` | `int \| float \| NoneType` | `None` | Client-side total timeout in seconds. Limits the total time spent waiting for the entire request to complete (including queue wait and processing). If not set, waits indefinitely. | > > **Returns:** `dict[str, Any]` > > #### upload > > ```python theme={null} > def upload(self, data: 'str | bytes', content_type: 'str', file_name: 'str | None' = None, *, repository: 'UploadRepositoryId | None' = None, fallback_repository: 'UploadRepositoryId | list[UploadRepositoryId] | None' = None, lifecycle: 'StorageSettings | None' = None) -> 'str' > ``` > > Upload the given data blob and return the access URL. The content type should be specified as the second argument. Use > `upload_file()` or `upload_image()` for convenience. Pass `lifecycle` to > control uploaded object expiration and initial ACL settings. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `data` | `str \| bytes` | - | - | > | `content_type` | `str` | - | - | > | `file_name` | `Optional[str]` | `None` | - | > | `repository` | `Optional[Literal[fal_v3, cdn, fal]]` | `None` | - | > | `fallback_repository` | `Literal[fal_v3, cdn, fal] \| list[Literal[fal_v3, cdn, fal]] \| NoneType` | `None` | - | > | `lifecycle` | `Optional[StorageSettings]` | `None` | - | > > **Returns:** `str` > > #### upload\_file > > ```python theme={null} > def upload_file(self, path: 'os.PathLike', *, repository: 'UploadRepositoryId | None' = None, fallback_repository: 'UploadRepositoryId | list[UploadRepositoryId] | None' = None, lifecycle: 'StorageSettings | None' = None) -> 'str' > ``` > > Upload a local file and return the access URL. Pass `lifecycle` to control uploaded object expiration and initial ACL > settings. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `path` | `PathLike` | - | - | > | `repository` | `Optional[Literal[fal_v3, cdn, fal]]` | `None` | - | > | `fallback_repository` | `Literal[fal_v3, cdn, fal] \| list[Literal[fal_v3, cdn, fal]] \| NoneType` | `None` | - | > | `lifecycle` | `Optional[StorageSettings]` | `None` | - | > > **Returns:** `str` > > #### upload\_image > > ```python theme={null} > def upload_image(self, image: 'Image.Image', format: 'str' = 'jpeg', *, repository: 'UploadRepositoryId | None' = None, fallback_repository: 'UploadRepositoryId | list[UploadRepositoryId] | None' = None, lifecycle: 'StorageSettings | None' = None) -> 'str' > ``` > > Upload a Pillow image object and return the access URL. Pass `lifecycle` to control uploaded object expiration and initial ACL > settings. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `image` | `Image.Image` | - | - | > | `format` | `str` | `'jpeg'` | - | > | `repository` | `UploadRepositoryId \| None` | `None` | - | > | `fallback_repository` | `UploadRepositoryId \| list[UploadRepositoryId] \| None` | `None` | - | > | `lifecycle` | `StorageSettings \| None` | `None` | - | > > #### ws\_connect > > ```python theme={null} > def ws_connect(self, application: 'str', *, use_jwt: 'bool' = True, path: 'str' = '', max_buffering: 'int | None' = None, token_expiration: 'int' = 120) -> "Iterator['Connection']" > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `application` | `str` | - | - | > | `use_jwt` | `bool` | `True` | - | > | `path` | `str` | `''` | - | > | `max_buffering` | `int \| None` | `None` | - | > | `token_expiration` | `int` | `120` | - | ### AsyncClient ```python theme={null} class fal_client.AsyncClient ``` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `key` | `Optional[str]` | `None` | - | > | `default_timeout` | `float` | `120.0` | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `key` | `str \| None` | `None` | - | > | `default_timeout` | `float` | `120.0` | - | > [accordion] Methods > > #### cancel > > ```python theme={null} > async def cancel(self, application: 'str', request_id: 'str') -> 'None' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `application` | `str` | - | - | > | `request_id` | `str` | - | - | > > **Returns:** `NoneType` > > #### get\_handle > > ```python theme={null} > async def get_handle(self, application: 'str', request_id: 'str') -> 'AsyncRequestHandle' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `application` | `str` | - | - | > | `request_id` | `str` | - | - | > > **Returns:** `AsyncRequestHandle` > > #### realtime > > ```python theme={null} > def realtime(self, application: 'str', *, use_jwt: 'bool' = True, path: 'str' = '/realtime', max_buffering: 'int | None' = None, token_expiration: 'int' = 120, encode_message: 'Callable[[Any], bytes] | None' = None, decode_message: 'Callable[[bytes], Any] | None' = None) -> 'AsyncIterator[AsyncRealtimeConnection]' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `application` | `str` | - | - | > | `use_jwt` | `bool` | `True` | - | > | `path` | `str` | `'/realtime'` | - | > | `max_buffering` | `Optional[int]` | `None` | - | > | `token_expiration` | `int` | `120` | - | > | `encode_message` | `Optional[Callable[Any, bytes]]` | `None` | - | > | `decode_message` | `Optional[Callable[bytes, Any]]` | `None` | - | > > **Returns:** `AsyncIterator[AsyncRealtimeConnection]` > > #### result > > ```python theme={null} > async def result(self, application: 'str', request_id: 'str') -> 'AnyJSON' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `application` | `str` | - | - | > | `request_id` | `str` | - | - | > > **Returns:** `dict[str, Any]` > > #### run > > ```python theme={null} > async def run(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', timeout: 'Optional[Union[int, float]]' = None, start_timeout: 'Optional[Union[int, float]]' = None, hint: 'str | None' = None, headers: 'dict[str, str]' = {}) -> 'AnyJSON' > ``` > > Run an application with the given arguments (which will be JSON serialized). The path parameter can be used to specify a subpath when applicable. This method will return the result of the inference call directly. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `application` | `str` | - | - | > | `arguments` | `dict[str, Any]` | - | - | > | `path` | `str` | `''` | - | > | `timeout` | `int \| float \| NoneType` | `None` | Client-side HTTP timeout in seconds. Controls how long the HTTP client waits for a response. Defaults to the client's default\_timeout. | > | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts. Does not apply once the application begins processing. | > | `hint` | `Optional[str]` | `None` | - | > | `headers` | `dict[str, str]` | `\{\}` | - | > > **Returns:** `dict[str, Any]` > > #### status > > ```python theme={null} > async def status(self, application: 'str', request_id: 'str', *, with_logs: 'bool' = False) -> 'Status' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `application` | `str` | - | - | > | `request_id` | `str` | - | - | > | `with_logs` | `bool` | `False` | - | > > **Returns:** `Status` > > #### stream > > ```python theme={null} > def stream(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '/stream', timeout: 'float | None' = None, headers: 'dict[str, str]' = {}) -> 'AsyncIterator[dict[str, Any]]' > ``` > > Stream the output of an application with the given arguments (which will be JSON serialized). This is only supported at a few select applications at the moment, so be sure to first consult with the documentation of individual applications > to see if this is supported. > > The function will iterate over each event that is streamed from the server. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `application` | `str` | - | - | > | `arguments` | `dict[str, Any]` | - | - | > | `path` | `str` | `'/stream'` | - | > | `timeout` | `Optional[float]` | `None` | - | > | `headers` | `dict[str, str]` | `\{\}` | - | > > **Returns:** `AsyncIterator[dict[str, Any]]` > > #### submit > > ```python theme={null} > async def submit(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', hint: 'str | None' = None, webhook_url: 'str | None' = None, priority: 'Optional[Priority]' = None, headers: 'dict[str, str]' = {}, start_timeout: 'Optional[Union[int, float]]' = None) -> 'AsyncRequestHandle' > ``` > > Submit an application with the given arguments (which will be JSON serialized). The path parameter can be used to specify a subpath when applicable. This method will return a handle to the request that can be used to check the status > and retrieve the result of the inference call when it is done. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `application` | `str` | - | - | > | `arguments` | `dict[str, Any]` | - | - | > | `path` | `str` | `''` | - | > | `hint` | `Optional[str]` | `None` | - | > | `webhook_url` | `Optional[str]` | `None` | - | > | `priority` | `Optional[Literal[normal, low]]` | `None` | - | > | `headers` | `dict[str, str]` | `\{\}` | - | > | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts (includes queue wait, retries, and routing). Does not apply once the application begins processing. | > > **Returns:** `AsyncRequestHandle` > > #### subscribe > > ```python theme={null} > async def subscribe(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', hint: 'str | None' = None, with_logs: 'bool' = False, interval: 'float' = 0.1, on_enqueue: 'Optional[Callable[[str], None | Awaitable[None]]]' = None, on_queue_update: 'Optional[Callable[[Status], None | Awaitable[None]]]' = None, priority: 'Optional[Priority]' = None, headers: 'dict[str, str]' = {}, start_timeout: 'Optional[Union[int, float]]' = None, client_timeout: 'Optional[Union[int, float]]' = None) -> 'AnyJSON' > ``` > > Subscribe to an application and wait for the result. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `application` | `str` | - | - | > | `arguments` | `dict[str, Any]` | - | - | > | `path` | `str` | `''` | - | > | `hint` | `Optional[str]` | `None` | - | > | `with_logs` | `bool` | `False` | - | > | `interval` | `float` | `0.1` | Polling interval in seconds while waiting for request updates. | > | `on_enqueue` | `Optional[Callable[str, Optional[Awaitable[NoneType]]]]` | `None` | - | > | `on_queue_update` | `Optional[Callable[Status, Optional[Awaitable[NoneType]]]]` | `None` | - | > | `priority` | `Optional[Literal[normal, low]]` | `None` | - | > | `headers` | `dict[str, str]` | `\{\}` | - | > | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts (includes queue wait, retries, and routing). Does not apply once the application begins processing. | > | `client_timeout` | `int \| float \| NoneType` | `None` | Client-side total timeout in seconds. Limits the total time spent waiting for the entire request to complete (including queue wait and processing). If not set, waits indefinitely. | > > **Returns:** `dict[str, Any]` > > #### upload > > ```python theme={null} > async def upload(self, data: 'str | bytes', content_type: 'str', file_name: 'str | None' = None, *, repository: 'UploadRepositoryId | None' = None, fallback_repository: 'UploadRepositoryId | list[UploadRepositoryId] | None' = None, lifecycle: 'StorageSettings | None' = None) -> 'str' > ``` > > Upload the given data blob and return the access URL. The content type should be specified as the second argument. Use > `upload_file()` or `upload_image()` for convenience. Pass `lifecycle` to > control uploaded object expiration and initial ACL settings. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `data` | `str \| bytes` | - | - | > | `content_type` | `str` | - | - | > | `file_name` | `Optional[str]` | `None` | - | > | `repository` | `Optional[Literal[fal_v3, cdn, fal]]` | `None` | - | > | `fallback_repository` | `Literal[fal_v3, cdn, fal] \| list[Literal[fal_v3, cdn, fal]] \| NoneType` | `None` | - | > | `lifecycle` | `Optional[StorageSettings]` | `None` | - | > > **Returns:** `str` > > #### upload\_file > > ```python theme={null} > async def upload_file(self, path: 'os.PathLike', *, repository: 'UploadRepositoryId | None' = None, fallback_repository: 'UploadRepositoryId | list[UploadRepositoryId] | None' = None, lifecycle: 'StorageSettings | None' = None) -> 'str' > ``` > > Upload a local file and return the access URL. Pass `lifecycle` to control uploaded object expiration and initial ACL > settings. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `path` | `PathLike` | - | - | > | `repository` | `Optional[Literal[fal_v3, cdn, fal]]` | `None` | - | > | `fallback_repository` | `Literal[fal_v3, cdn, fal] \| list[Literal[fal_v3, cdn, fal]] \| NoneType` | `None` | - | > | `lifecycle` | `Optional[StorageSettings]` | `None` | - | > > **Returns:** `str` > > #### upload\_image > > ```python theme={null} > async def upload_image(self, image: 'Image.Image', format: 'str' = 'jpeg', *, repository: 'UploadRepositoryId | None' = None, fallback_repository: 'UploadRepositoryId | list[UploadRepositoryId] | None' = None, lifecycle: 'StorageSettings | None' = None) -> 'str' > ``` > > Upload a Pillow image object and return the access URL. Pass `lifecycle` to control uploaded object expiration and initial ACL > settings. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `image` | `Image.Image` | - | - | > | `format` | `str` | `'jpeg'` | - | > | `repository` | `UploadRepositoryId \| None` | `None` | - | > | `fallback_repository` | `UploadRepositoryId \| list[UploadRepositoryId] \| None` | `None` | - | > | `lifecycle` | `StorageSettings \| None` | `None` | - | > > #### ws\_connect > > ```python theme={null} > def ws_connect(self, application: 'str', *, use_jwt: 'bool' = True, path: 'str' = '', max_buffering: 'int | None' = None, token_expiration: 'int' = 120) -> "AsyncIterator['WebSocketClientProtocol']" > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `application` | `str` | - | - | > | `use_jwt` | `bool` | `True` | - | > | `path` | `str` | `''` | - | > | `max_buffering` | `int \| None` | `None` | - | > | `token_expiration` | `int` | `120` | - | ### RealtimeConnection ```python theme={null} class fal_client.RealtimeConnection ``` Synchronous realtime connection wrapper. > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `_ws` | `'Connection'` | - | - | > | `_encode_message` | `Callable[[Any], bytes] \| None` | `None` | - | > | `_decode_message` | `Callable[[bytes], Any] \| None` | `None` | - | > [accordion] Methods > > #### close > > ```python theme={null} > def close(self) -> 'None' > ``` > > **Returns:** `NoneType` > > #### recv > > ```python theme={null} > def recv(self) -> 'dict[str, Any] | None' > ``` > > **Returns:** `Optional[dict[str, Any]]` > > #### send > > ```python theme={null} > def send(self, arguments: 'dict[str, Any]') -> 'None' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `arguments` | `dict[str, Any]` | - | - | > > **Returns:** `NoneType` ### AsyncRealtimeConnection ```python theme={null} class fal_client.AsyncRealtimeConnection ``` Asynchronous realtime connection wrapper. > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `_ws` | `'WebSocketClientProtocol'` | - | - | > | `_encode_message` | `Callable[[Any], bytes] \| None` | `None` | - | > | `_decode_message` | `Callable[[bytes], Any] \| None` | `None` | - | > [accordion] Methods > > #### close > > ```python theme={null} > async def close(self) -> 'None' > ``` > > **Returns:** `NoneType` > > #### recv > > ```python theme={null} > async def recv(self) -> 'dict[str, Any] | None' > ``` > > **Returns:** `Optional[dict[str, Any]]` > > #### send > > ```python theme={null} > async def send(self, arguments: 'dict[str, Any]') -> 'None' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `arguments` | `dict[str, Any]` | - | - | > > **Returns:** `NoneType` ### Status ```python theme={null} class fal_client.Status ``` ### Queued ```python theme={null} class fal_client.Queued ``` Indicates the request is enqueued and waiting to be processed. The position field indicates the relative position in the queue (0-indexed). > **Inherits from:** `Status` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `position` | `int` | - | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `position` | `int` | - | - | ### InProgress ```python theme={null} class fal_client.InProgress ``` Indicates the request is currently being processed. If the status operation called with the `with_logs` parameter set to True, the logs field will be a list of log objects. > **Inherits from:** `Status` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `logs` | `Optional[list[dict[str, Any]]]` | - | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `logs` | `list[dict[str, Any]] \| None` | - | - | ### Completed ```python theme={null} class fal_client.Completed ``` Indicates the request has been completed and the result can be gathered. The logs field will contain the logs if the status operation was called with the `with_logs` parameter set to True. Metrics might contain the inference time, and other internal metadata (number of tokens processed, etc.). > **Inherits from:** `Status` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `logs` | `Optional[list[dict[str, Any]]]` | - | - | > | `metrics` | `dict[str, Any]` | - | - | > | `error` | `Optional[str]` | `None` | - | > | `error_type` | `Optional[str]` | `None` | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `logs` | `list[dict[str, Any]] \| None` | - | - | > | `metrics` | `dict[str, Any]` | - | - | > | `error` | `str \| None` | `None` | - | > | `error_type` | `str \| None` | `None` | - | ### FalClientError ```python theme={null} class fal_client.FalClientError ``` Common base class for all non-exit exceptions. > **Inherits from:** `Exception` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `args` | - | - | - | > | `kwargs` | - | - | - | ### FalClientHTTPError ```python theme={null} class fal_client.FalClientHTTPError ``` > **Inherits from:** `FalClientError` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `message` | `str` | - | - | > | `status_code` | `int` | - | - | > | `response_headers` | `dict[str, str]` | - | - | > | `response` | `Response` | - | - | > | `error_type` | `Optional[str]` | `None` | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `message` | `str` | - | - | > | `status_code` | `int` | - | - | > | `response_headers` | `dict[str, str]` | - | - | > | `response` | `httpx.Response` | - | - | > | `error_type` | `str \| None` | `None` | - | ### FalClientTimeoutError ```python theme={null} class fal_client.FalClientTimeoutError ``` > **Inherits from:** `FalClientError`, `TimeoutError` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `timeout` | `float` | - | - | > | `request_id` | `Optional[str]` | `None` | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `timeout` | `float` | - | - | > | `request_id` | `Optional[str]` | `None` | - | ### StorageACL ```python theme={null} class fal_client.StorageACL ``` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `default` | `Optional[Literal[hide, forbid, allow]]` | `None` | - | > | `rules` | `Optional[list[StorageACLRule]]` | `None` | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `default` | `StorageACLDecision \| None` | `None` | - | > | `rules` | `list[StorageACLRule] \| None` | `None` | - | ### StorageACLRule ```python theme={null} class fal_client.StorageACLRule ``` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `user` | `str` | - | - | > | `decision` | `Literal[hide, forbid, allow]` | - | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `user` | `str` | - | - | > | `decision` | `StorageACLDecision` | - | - | ### StorageSettings ```python theme={null} class fal_client.StorageSettings ``` Lifecycle configuration for uploaded files. Use `expires_in="never"` (or omit `expires_in`) to keep the backend's default retention policy. `expires_in="immediate"` maps to approximately 60 seconds because the backend treats `0` as no expiration. > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `expires_in` | `Literal[never, immediate, 1h, 1d, 7d, 30d, 1y] \| int \| NoneType` | `None` | - | > | `initial_acl` | `Optional[StorageACL]` | `None` | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `expires_in` | `ObjectExpiration \| None` | `None` | - | > | `initial_acl` | `StorageACL \| None` | `None` | - | ### SyncRequestHandle ```python theme={null} class fal_client.SyncRequestHandle ``` > **Inherits from:** `_BaseRequestHandle` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `request_id` | `str` | - | - | > | `response_url` | `str` | - | - | > | `status_url` | `str` | - | - | > | `cancel_url` | `str` | - | - | > | `client` | `Client` | - | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `client` | `httpx.Client` | - | - | > [accordion] Methods > > #### cancel > > ```python theme={null} > def cancel(self) -> 'None' > ``` > > Cancel the request. > > **Returns:** `NoneType` > > #### from\_request\_id > > ```python theme={null} > def from_request_id(cls, client: 'httpx.Client', application: 'str', request_id: 'str') -> 'SyncRequestHandle' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `client` | `Client` | - | - | > | `application` | `str` | - | - | > | `request_id` | `str` | - | - | > > **Returns:** `SyncRequestHandle` > > #### get > > ```python theme={null} > def get(self, *, interval: 'float' = 0.1) -> 'AnyJSON' > ``` > > Wait till the request is completed and return the result of the inference call. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `interval` | `float` | `0.1` | - | > > **Returns:** `dict[str, Any]` > > #### iter\_events > > ```python theme={null} > def iter_events(self, *, with_logs: 'bool' = False, interval: 'float' = 0.1) -> 'Iterator[Status]' > ``` > > Continuously poll for the status of the request and yield it at each interval till the request is completed. If `with_logs` is True, logs will be included in the response. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `with_logs` | `bool` | `False` | - | > | `interval` | `float` | `0.1` | - | > > **Returns:** `Iterator[Status]` > > #### status > > ```python theme={null} > def status(self, *, with_logs: 'bool' = False) -> 'Status' > ``` > > Returns the status of the request (which can be one of the following: Queued, InProgress, Completed). If `with_logs` is True, logs will be included > for InProgress and Completed statuses. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `with_logs` | `bool` | `False` | - | > > **Returns:** `Status` ### AsyncRequestHandle ```python theme={null} class fal_client.AsyncRequestHandle ``` > **Inherits from:** `_BaseRequestHandle` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `request_id` | `str` | - | - | > | `response_url` | `str` | - | - | > | `status_url` | `str` | - | - | > | `cancel_url` | `str` | - | - | > | `client` | `AsyncClient` | - | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `client` | `httpx.AsyncClient` | - | - | > [accordion] Methods > > #### cancel > > ```python theme={null} > async def cancel(self) -> 'None' > ``` > > Cancel the request. > > **Returns:** `NoneType` > > #### from\_request\_id > > ```python theme={null} > def from_request_id(cls, client: 'httpx.AsyncClient', application: 'str', request_id: 'str') -> 'AsyncRequestHandle' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `client` | `AsyncClient` | - | - | > | `application` | `str` | - | - | > | `request_id` | `str` | - | - | > > **Returns:** `AsyncRequestHandle` > > #### get > > ```python theme={null} > async def get(self, *, interval: 'float' = 0.1) -> 'AnyJSON' > ``` > > Wait till the request is completed and return the result. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `interval` | `float` | `0.1` | - | > > **Returns:** `dict[str, Any]` > > #### iter\_events > > ```python theme={null} > def iter_events(self, *, with_logs: 'bool' = False, interval: 'float' = 0.1) -> 'AsyncIterator[Status]' > ``` > > Continuously poll for the status of the request and yield it at each interval till the request is completed. If `with_logs` is True, logs will be included in the response. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `with_logs` | `bool` | `False` | - | > | `interval` | `float` | `0.1` | - | > > **Returns:** `AsyncIterator[Status]` > > #### status > > ```python theme={null} > async def status(self, *, with_logs: 'bool' = False) -> 'Status' > ``` > > Returns the status of the request (which can be one of the following: Queued, InProgress, Completed). If `with_logs` is True, logs will be included > for InProgress and Completed statuses. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `with_logs` | `bool` | `False` | - | > > **Returns:** `Status` *** ## Functions ### run ```python theme={null} def run(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', timeout: 'Optional[Union[int, float]]' = None, start_timeout: 'Optional[Union[int, float]]' = None, hint: 'str | None' = None, headers: 'dict[str, str]' = {}) -> 'AnyJSON' ``` Run an application with the given arguments (which will be JSON serialized). | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `''` | - | | `timeout` | `int \| float \| NoneType` | `None` | Client-side HTTP timeout in seconds. Controls how long the HTTP client waits for a response. Defaults to the client's default\_timeout. | | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts. Does not apply once the application begins processing. | | `hint` | `Optional[str]` | `None` | - | | `headers` | `dict[str, str]` | `\{\}` | - | **Returns:** `dict[str, Any]` ### subscribe\_async ```python theme={null} async def subscribe_async(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', hint: 'str | None' = None, with_logs: 'bool' = False, interval: 'float' = 0.1, on_enqueue: 'Optional[Callable[[str], None | Awaitable[None]]]' = None, on_queue_update: 'Optional[Callable[[Status], None | Awaitable[None]]]' = None, priority: 'Optional[Priority]' = None, headers: 'dict[str, str]' = {}, start_timeout: 'Optional[Union[int, float]]' = None, client_timeout: 'Optional[Union[int, float]]' = None) -> 'AnyJSON' ``` Subscribe to an application and wait for the result. | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `''` | - | | `hint` | `Optional[str]` | `None` | - | | `with_logs` | `bool` | `False` | - | | `interval` | `float` | `0.1` | Polling interval in seconds while waiting for request updates. | | `on_enqueue` | `Optional[Callable[str, Optional[Awaitable[NoneType]]]]` | `None` | - | | `on_queue_update` | `Optional[Callable[Status, Optional[Awaitable[NoneType]]]]` | `None` | - | | `priority` | `Optional[Literal[normal, low]]` | `None` | - | | `headers` | `dict[str, str]` | `\{\}` | - | | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts (includes queue wait, retries, and routing). Does not apply once the application begins processing. | | `client_timeout` | `int \| float \| NoneType` | `None` | Client-side total timeout in seconds. Limits the total time spent waiting for the entire request to complete (including queue wait and processing). If not set, waits indefinitely. | **Returns:** `dict[str, Any]` ### subscribe ```python theme={null} def subscribe(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', hint: 'str | None' = None, with_logs: 'bool' = False, interval: 'float' = 0.1, on_enqueue: 'Optional[Callable[[str], None]]' = None, on_queue_update: 'Optional[Callable[[Status], None]]' = None, priority: 'Optional[Priority]' = None, headers: 'dict[str, str]' = {}, start_timeout: 'Optional[Union[int, float]]' = None, client_timeout: 'Optional[Union[int, float]]' = None) -> 'AnyJSON' ``` Subscribe to an application and wait for the result. | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `''` | - | | `hint` | `Optional[str]` | `None` | - | | `with_logs` | `bool` | `False` | - | | `interval` | `float` | `0.1` | Polling interval in seconds while waiting for request updates. | | `on_enqueue` | `Optional[Callable[str, NoneType]]` | `None` | - | | `on_queue_update` | `Optional[Callable[Status, NoneType]]` | `None` | - | | `priority` | `Optional[Literal[normal, low]]` | `None` | - | | `headers` | `dict[str, str]` | `\{\}` | - | | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts (includes queue wait, retries, and routing). Does not apply once the application begins processing. | | `client_timeout` | `int \| float \| NoneType` | `None` | Client-side total timeout in seconds. Limits the total time spent waiting for the entire request to complete (including queue wait and processing). If not set, waits indefinitely. | **Returns:** `dict[str, Any]` ### submit ```python theme={null} def submit(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', hint: 'str | None' = None, webhook_url: 'str | None' = None, priority: 'Optional[Priority]' = None, headers: 'dict[str, str]' = {}, start_timeout: 'Optional[Union[int, float]]' = None) -> 'SyncRequestHandle' ``` Submit an application with the given arguments (which will be JSON serialized). | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `''` | - | | `hint` | `Optional[str]` | `None` | - | | `webhook_url` | `Optional[str]` | `None` | - | | `priority` | `Optional[Literal[normal, low]]` | `None` | - | | `headers` | `dict[str, str]` | `\{\}` | - | | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts (includes queue wait, retries, and routing). Does not apply once the application begins processing. | **Returns:** `SyncRequestHandle` ### stream ```python theme={null} def stream(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '/stream', timeout: 'float | None' = None, headers: 'dict[str, str]' = {}) -> 'Iterator[dict[str, Any]]' ``` Stream the output of an application with the given arguments (which will be JSON serialized). This is only supported at a few select applications at the moment, so be sure to first consult with the documentation of individual applications to see if this is supported. The function will iterate over each event that is streamed from the server. | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `'/stream'` | - | | `timeout` | `Optional[float]` | `None` | - | | `headers` | `dict[str, str]` | `\{\}` | - | **Returns:** `Iterator[dict[str, Any]]` ### run\_async ```python theme={null} async def run_async(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', timeout: 'Optional[Union[int, float]]' = None, start_timeout: 'Optional[Union[int, float]]' = None, hint: 'str | None' = None, headers: 'dict[str, str]' = {}) -> 'AnyJSON' ``` Run an application with the given arguments (which will be JSON serialized). The path parameter can be used to specify a subpath when applicable. This method will return the result of the inference call directly. | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `''` | - | | `timeout` | `int \| float \| NoneType` | `None` | Client-side HTTP timeout in seconds. Controls how long the HTTP client waits for a response. Defaults to the client's default\_timeout. | | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts. Does not apply once the application begins processing. | | `hint` | `Optional[str]` | `None` | - | | `headers` | `dict[str, str]` | `\{\}` | - | **Returns:** `dict[str, Any]` ### submit\_async ```python theme={null} async def submit_async(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '', hint: 'str | None' = None, webhook_url: 'str | None' = None, priority: 'Optional[Priority]' = None, headers: 'dict[str, str]' = {}, start_timeout: 'Optional[Union[int, float]]' = None) -> 'AsyncRequestHandle' ``` Submit an application with the given arguments (which will be JSON serialized). The path parameter can be used to specify a subpath when applicable. This method will return a handle to the request that can be used to check the status and retrieve the result of the inference call when it is done. | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `''` | - | | `hint` | `Optional[str]` | `None` | - | | `webhook_url` | `Optional[str]` | `None` | - | | `priority` | `Optional[Literal[normal, low]]` | `None` | - | | `headers` | `dict[str, str]` | `\{\}` | - | | `start_timeout` | `int \| float \| NoneType` | `None` | Server-side request timeout in seconds. Limits total time spent waiting before processing starts (includes queue wait, retries, and routing). Does not apply once the application begins processing. | **Returns:** `AsyncRequestHandle` ### stream\_async ```python theme={null} def stream_async(self, application: 'str', arguments: 'AnyJSON', *, path: 'str' = '/stream', timeout: 'float | None' = None, headers: 'dict[str, str]' = {}) -> 'AsyncIterator[dict[str, Any]]' ``` Stream the output of an application with the given arguments (which will be JSON serialized). This is only supported at a few select applications at the moment, so be sure to first consult with the documentation of individual applications to see if this is supported. The function will iterate over each event that is streamed from the server. | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `application` | `str` | - | - | | `arguments` | `dict[str, Any]` | - | - | | `path` | `str` | `'/stream'` | - | | `timeout` | `Optional[float]` | `None` | - | | `headers` | `dict[str, str]` | `\{\}` | - | **Returns:** `AsyncIterator[dict[str, Any]]` ### realtime ```python theme={null} def realtime(self, application: 'str', *, use_jwt: 'bool' = True, path: 'str' = '/realtime', max_buffering: 'int | None' = None, token_expiration: 'int' = 120, encode_message: 'Callable[[Any], bytes] | None' = None, decode_message: 'Callable[[bytes], Any] | None' = None) -> 'Iterator[RealtimeConnection]' ``` | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `application` | `str` | - | - | | `use_jwt` | `bool` | `True` | - | | `path` | `str` | `'/realtime'` | - | | `max_buffering` | `Optional[int]` | `None` | - | | `token_expiration` | `int` | `120` | - | | `encode_message` | `Optional[Callable[Any, bytes]]` | `None` | - | | `decode_message` | `Optional[Callable[bytes, Any]]` | `None` | - | **Returns:** `Iterator[RealtimeConnection]` ### realtime\_async ```python theme={null} def realtime_async(self, application: 'str', *, use_jwt: 'bool' = True, path: 'str' = '/realtime', max_buffering: 'int | None' = None, token_expiration: 'int' = 120, encode_message: 'Callable[[Any], bytes] | None' = None, decode_message: 'Callable[[bytes], Any] | None' = None) -> 'AsyncIterator[AsyncRealtimeConnection]' ``` | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `application` | `str` | - | - | | `use_jwt` | `bool` | `True` | - | | `path` | `str` | `'/realtime'` | - | | `max_buffering` | `Optional[int]` | `None` | - | | `token_expiration` | `int` | `120` | - | | `encode_message` | `Optional[Callable[Any, bytes]]` | `None` | - | | `decode_message` | `Optional[Callable[bytes, Any]]` | `None` | - | **Returns:** `AsyncIterator[AsyncRealtimeConnection]` ### cancel ```python theme={null} def cancel(self, application: 'str', request_id: 'str') -> 'None' ``` | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `application` | `str` | - | - | | `request_id` | `str` | - | - | **Returns:** `NoneType` ### cancel\_async ```python theme={null} async def cancel_async(self, application: 'str', request_id: 'str') -> 'None' ``` | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `application` | `str` | - | - | | `request_id` | `str` | - | - | **Returns:** `NoneType` ### status ```python theme={null} def status(self, application: 'str', request_id: 'str', *, with_logs: 'bool' = False) -> 'Status' ``` | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `application` | `str` | - | - | | `request_id` | `str` | - | - | | `with_logs` | `bool` | `False` | - | **Returns:** `Status` ### status\_async ```python theme={null} async def status_async(self, application: 'str', request_id: 'str', *, with_logs: 'bool' = False) -> 'Status' ``` | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `application` | `str` | - | - | | `request_id` | `str` | - | - | | `with_logs` | `bool` | `False` | - | **Returns:** `Status` ### result ```python theme={null} def result(self, application: 'str', request_id: 'str') -> 'AnyJSON' ``` | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `application` | `str` | - | - | | `request_id` | `str` | - | - | **Returns:** `dict[str, Any]` ### result\_async ```python theme={null} async def result_async(self, application: 'str', request_id: 'str') -> 'AnyJSON' ``` | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `application` | `str` | - | - | | `request_id` | `str` | - | - | **Returns:** `dict[str, Any]` ### encode ```python theme={null} def encode(data: 'str | bytes', content_type: 'str') -> 'str' ``` Encode the given data blob to a data URL with the specified content type. | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `data` | `str \| bytes` | - | - | | `content_type` | `str` | - | - | **Returns:** `str` ### encode\_file ```python theme={null} def encode_file(path: 'os.PathLike') -> 'str' ``` Encode a file from the local filesystem to a data URL with the inferred content type. | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `path` | `PathLike` | - | - | **Returns:** `str` ### encode\_image ```python theme={null} def encode_image(image: 'Image.Image', format: 'str' = 'jpeg') -> 'str' ``` Encode a pillow image object to a data URL with the specified format. | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `image` | `Image.Image` | - | - | | `format` | `str` | `'jpeg'` | - | ### set\_get\_current\_app ```python theme={null} def set_get_current_app(func: 'Callable[[], Any]') ``` | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `func` | `Callable[Any]` | - | - | # Python Client Source: https://fal.ai/docs/api-reference/client-libraries/python/index API reference for fal-client Python package The `fal-client` package provides a Python interface for calling fal AI models. ## Installation ```bash theme={null} pip install fal-client ``` ## Quick Start ```python theme={null} import fal_client result = fal_client.subscribe( "fal-ai/flux/dev", arguments={ "prompt": "a cat wearing a hat", "image_size": "landscape_4_3" }, with_logs=True, on_queue_update=lambda status: print(f"Status: {status}") ) print(result["images"][0]["url"]) ``` ## API Reference The following pages contain the auto-generated API reference for all public classes and functions in the `fal-client` package. # Swift Client Source: https://fal.ai/docs/api-reference/client-libraries/swift/index fal client library for iOS, macOS, tvOS, and watchOS The `fal-swift` package provides a native Swift interface for calling fal AI models on Apple platforms. ## Installation Add the package via Swift Package Manager: ```swift theme={null} .package(url: "https://github.com/fal-ai/fal-swift.git", from: "0.5.6") ``` ## Quick Start ```swift theme={null} import FalClient let result = try await fal.subscribe( to: "fal-ai/flux/dev", input: [ "prompt": "a cat", "seed": 6252023, "image_size": "landscape_4_3", "num_images": 4 ], includeLogs: true ) { update in if case let .inProgress(logs) = update { print(logs) } } ``` ## Supported Platforms * iOS 16+ * macOS 13+ * tvOS 16+ * watchOS 9+ ## API Reference > [card] [Swift API Reference](https://swiftpackageindex.com/fal-ai/fal-swift/documentation/falclient) > > Full API documentation on Swift Package Index > [card] [GitHub Repository](https://github.com/fal-ai/fal-swift) > > Source code and examples # Reference Source: https://fal.ai/docs/api-reference/index Complete API and SDK reference documentation for fal Complete reference documentation for all fal SDKs and tools. > [card] [Client Libraries](/docs/api-reference/client-libraries) > > Libraries for calling fal AI models from your applications > [card] [CLI Reference](/docs/api-reference/cli) > > Command-line interface for deploying and managing fal applications > [card] [Python SDK](/docs/api-reference/python-sdk/fal-app-reference) > > Tools for building and deploying serverless AI applications ## Overview | Section | What it's for | When to use | | :- | :- | :- | | **Client Libraries** | Call fal AI models and get results | You want to use fal's AI models in your app | | **CLI Reference** | Deploy, manage, and monitor fal applications | You're working with fal from the command line | | **Python SDK** | Build and deploy custom AI applications | You're deploying your own models on fal | # Inference API Source: https://fal.ai/docs/api-reference/inference-api/index Call fal models over HTTP with the queue API or the synchronous API, without an SDK. The Inference API is the HTTP interface that the fal SDKs use. Use it from any language or HTTP client. This page gives the rules that apply to all operations. The operation pages give the request and response schemas. For model pricing, usage, and request history, see the [Platform API](/docs/api-reference/platform-apis). ## Choose an API | API | Host | Use it when | | - | - | - | | [Queue API](/docs/api-reference/inference-api/queue/submit) | `https://queue.fal.run` | The request can take more than a few seconds, or you need retries, status, cancellation, or webhooks. | | [Synchronous API](/docs/api-reference/inference-api/sync/run) | `https://fal.run` | The request is short and you want the result in the same HTTP connection. | Use the queue for production traffic. The queue keeps the request until a runner is available, and it retries the request after a temporary runner error. The synchronous API does not retry, and it returns an error when it cannot get a runner. ## Authentication Send your API key in the `Authorization` header with the `Key` prefix: ```bash theme={null} curl -X POST https://queue.fal.run/blackforestlabs/flux-3-max/text-to-video \ -H "Authorization: Key $FAL_KEY" \ -H "Content-Type: application/json" \ -d '{"prompt": "a red fox in the snow"}' ``` The key must have the permission for the operation: | Operation | Permission | | - | - | | Submit a queue request, or run a model | `models:requests:submit` | | Get the status or result of a request | `models:requests:read` | | Cancel a request | `models:requests:cancel` | The `API` preset has all three permissions. See [Key-based authentication](/docs/documentation/model-apis/authentication/key-based). ## Model IDs and paths A model ID has an owner, an app, and an optional endpoint path. For the model ID `blackforestlabs/flux-3-max/text-to-video`, the owner is `blackforestlabs`, the app is `flux-3-max`, and the path is `text-to-video`. Put the full model ID in the submit or run URL. The status, result, and cancel URLs use only the owner and the app. Do not build these URLs yourself. Use the `status_url`, `response_url`, and `cancel_url` fields from the submit response. ## Queue request lifecycle **1. Submit the request** [Submit a request](/docs/api-reference/inference-api/queue/submit). The response has the status `IN_QUEUE` and a `request_id`. **2. Wait for completion** [Get the status](/docs/api-reference/inference-api/queue/status) until `status` is `COMPLETED`. The API returns `202` while the request is in the queue or in progress, and `200` when it is complete. To receive updates without polling, [stream the status](/docs/api-reference/inference-api/queue/status-stream) or send a webhook URL with the submit request. **3. Get the result** [Get the result](/docs/api-reference/inference-api/queue/result). If the request failed, this operation returns the error. A failed or cancelled request also has the status `COMPLETED`. Get the result to find out if the request succeeded. ## Retries The queue retries a request when the runner fails with a temporary error. Temporary errors are connection errors, `503`, and `504`. The queue makes up to 10 attempts. When your account has the maximum number of concurrent requests, the queue waits for capacity and does not count an attempt. Send `X-Fal-No-Retry: 1` to turn off retries for one request. The synchronous API does not retry. When an error is temporary, the response has the header `X-Fal-Needs-Retry: 1`. Your client can retry these errors. See [Reliability](/docs/documentation/model-apis/inference/reliability). ## Timeouts The `X-Fal-Request-Start-Timeout` header sets the maximum time in seconds for the request to start on a runner. The time includes queue time and retries. If the request does not start in this time, the API returns `504` with the header `X-Fal-Request-Timeout-Type: user` and the error type `startup_timeout`. This header does not limit the run time on the runner. The model app sets the maximum run time. If the runner does not respond in that time, the API returns `504` with the error type `request_timeout`. ## Result retention The queue keeps the result for 1 hour after the request completes. If the result is 10 KB or larger, the queue keeps it for 6 minutes. If payload storage is on, the result stays available for the storage period. Payload storage is on by default. Use the `X-Fal-Store-IO` header to change it for one request. After the result expires, the result operation returns `404`. Get the result before it expires, or use a webhook. ## Errors The error body has one of these shapes: | Shape | Returned for | | - | - | | `{"detail": "...", "error_type": "..."}` | Errors from the request pipeline, for example timeouts and runner errors. The `X-Fal-Error-Type` header has the same value as `error_type`. See [Request Error Types](/docs/documentation/model-apis/request-errors). | | `{"detail": [{"loc": [...], "msg": "...", "type": "..."}]}` | Input errors from the model, with status `422`. See [Model Errors](/docs/documentation/model-apis/errors). | | `{"detail": "...", "type": "concurrent_requests_limit", "data": {...}}` | The synchronous API, with status `429`, when your account has the maximum number of concurrent requests. See [Concurrency limit errors](/docs/documentation/model-apis/request-errors#concurrency-limit-errors). | | `{"detail": "..."}` | Authentication, permission, and lookup errors. | | `{"status": "NOT_FOUND"}` | Queue status and cancel operations for a request that does not exist. | The queue API returns `404` for a request that belongs to a different account. It does not return `403`, so that the response does not show that the request exists. ## Response headers | Header | Description | | - | - | | `x-fal-request-id` | The request ID. Include it when you contact support. | | `X-Fal-Error-Type` | The error category of a failed request. | | `X-Fal-Request-Timeout-Type` | `user` when the `X-Fal-Request-Start-Timeout` deadline passed. | | `X-Fal-Needs-Retry` | `1` when a retry can succeed. `0` when a retry cannot succeed. | | `X-Fal-Served-From` | The ID of the runner that processed the request. | | `X-Fal-Billable-Units` | The billable units of the request, when the model reports them. | For the request headers, see [Platform Headers](/docs/documentation/model-apis/common-parameters). ## Backup hosts Each host has a backup host. The backup host accepts the same API key, path, query parameters, and body. | Host | Backup host | | - | - | | `queue.fal.run` | `queue.falrun.com` | | `fal.run` | `falrun.com` | When you use a backup host, replace the host in the `status_url`, `response_url`, and `cancel_url` values. See [Reliability](/docs/documentation/model-apis/inference/reliability#backup-domains). ## Operations > [card] [Submit request](/docs/api-reference/inference-api/queue/submit) > > Add a model request to the queue. > [card] [Get request status](/docs/api-reference/inference-api/queue/status) > > Get the state of a queue request. > [card] [Stream request status](/docs/api-reference/inference-api/queue/status-stream) > > Receive status updates as server-sent events. > [card] [Get request result](/docs/api-reference/inference-api/queue/result) > > Get the output of a completed request. > [card] [Cancel request](/docs/api-reference/inference-api/queue/cancel) > > Remove a request from the queue or stop it. > [card] [Run model](/docs/api-reference/inference-api/sync/run) > > Run a model and wait for the result. # Cancel a request Source: https://fal.ai/docs/api-reference/inference-api/queue/cancel /api-reference/inference-api/openapi/queue.json put /{owner}/{app}/requests/{request_id}/cancel Cancel a queue request. If the request is in the queue, fal removes it. If the request is in progress, fal sends a cancellation signal to the runner. The model app decides how to stop the work. See [Handle cancellations](https://fal.ai/docs/documentation/development/handle-cancellations). # Get request result Source: https://fal.ai/docs/api-reference/inference-api/queue/result /api-reference/inference-api/openapi/queue.json get /{owner}/{app}/requests/{request_id} Get the result of a completed request. The response has the status code, headers, and body that the model returned. If the model returned an error, this operation returns the same error. fal keeps the result for 1 hour after the request completes. If the result is 10 KB or larger, fal keeps it for 6 minutes. If payload storage is on, the result stays available for the storage period. See `X-Fal-Store-IO`. # Get request status Source: https://fal.ai/docs/api-reference/inference-api/queue/status /api-reference/inference-api/openapi/queue.json get /{owner}/{app}/requests/{request_id}/status Get the state of a queue request. Poll this operation until `status` is `COMPLETED`, then get the result. To receive updates without polling, use the status stream. # Stream request status Source: https://fal.ai/docs/api-reference/inference-api/queue/status-stream /api-reference/inference-api/openapi/queue.json get /{owner}/{app}/requests/{request_id}/status/stream Receive status updates as server-sent events. Each event has a `data:` line with a status object. The status object has the same fields as the response of Get request status. The server closes the stream after it sends the `COMPLETED` event. The server sends a comment line every 15 seconds to keep the connection open. # Submit a request Source: https://fal.ai/docs/api-reference/inference-api/queue/submit /api-reference/inference-api/openapi/queue.json post /{owner}/{app} Add a model request to the queue. The response contains the request ID and the URLs for status, result, and cancellation. The queue keeps the request until a runner is available. The queue has no size limit unless you send `fal_max_queue_length`. # Submit a request to an endpoint path Source: https://fal.ai/docs/api-reference/inference-api/queue/submit-path /api-reference/inference-api/openapi/queue.json post /{owner}/{app}/{path} Add a request for a model endpoint path to the queue. Use this operation when the model ID has more than two segments, for example `blackforestlabs/flux-3-max/text-to-video`. The response contains the request ID and the URLs for status, result, and cancellation. The queue keeps the request until a runner is available. The queue has no size limit unless you send `fal_max_queue_length`. # Run a model Source: https://fal.ai/docs/api-reference/inference-api/sync/run /api-reference/inference-api/openapi/sync.json post /{owner}/{app} Run a model and wait for the result. fal does not retry synchronous requests. If a request fails because of a temporary error, the response has `X-Fal-Needs-Retry: 1`. For long requests, use the [Queue API](https://fal.ai/docs/api-reference/inference-api/queue/submit). # Run an endpoint path Source: https://fal.ai/docs/api-reference/inference-api/sync/run-path /api-reference/inference-api/openapi/sync.json post /{owner}/{app}/{path} Run a model endpoint path and wait for the result. Use this operation when the model ID has more than two segments, for example `blackforestlabs/flux-3-max/text-to-video`. For models with a streaming endpoint, use the path `stream` to receive server-sent events. fal does not retry synchronous requests. If a request fails because of a temporary error, the response has `X-Fal-Needs-Retry: 1`. For long requests, use the [Queue API](https://fal.ai/docs/api-reference/inference-api/queue/submit). # Authentication Source: https://fal.ai/docs/api-reference/platform-apis/authentication Platform APIs require API keys for secure access to your user or team's data. ## Generating API Keys Navigate to the dashboard keys page and generate a key from the UI: [fal.ai/dashboard/keys](https://fal.ai/dashboard/keys) ## Permissions Platform APIs require different key permissions. [Learn more about key-based authentication and permissions](/docs/documentation/model-apis/authentication/key-based#permissions). > [card] API preset > > Most Platform APIs accept a key with the **`API`** preset. This preset > covers model discovery, model analytics, and the requests you submit. > [card] Other presets > > Some Platform APIs read sensitive data and need more permissions. Billing > endpoints need the **`BILLING`** preset, compute endpoints need the > **`COMPUTE`** preset, and a key with the **`FULL`** preset reaches every > endpoint. > [!NOTE] > > Match the preset to the surface you call. If you are not sure, start with a key on the `API` preset. You can create a key with more permissions later. > [!WARNING] > > API keys should be kept secure and never exposed in client-side code or public repositories. ## Authentication Format Include your API key in the `Authorization` header with the `Key` prefix: ```bash theme={null} Authorization: Key YOUR_API_KEY ``` The header is the same for every preset. Only the permissions of the key change. ## Usage Examples ### cURL Using a key on the `API` preset for model listing: ```bash theme={null} curl -X GET "https://api.fal.ai/v1/models?limit=10" \ -H "Authorization: Key YOUR_API_KEY" ``` Using a key on the `BILLING` preset for usage data: ```bash theme={null} curl -X GET "https://api.fal.ai/v1/models/usage" \ -H "Authorization: Key YOUR_BILLING_API_KEY" ``` ### Python Using a key on the `API` preset: ```python theme={null} import requests headers = { "Authorization": "Key YOUR_API_KEY" } response = requests.get( "https://api.fal.ai/v1/models", headers=headers, params={"limit": 10} ) print(response.json()) ``` ### JavaScript Using a key on the `API` preset: ```javascript theme={null} const response = await fetch('https://api.fal.ai/v1/models?limit=10', { headers: { 'Authorization': 'Key YOUR_API_KEY' } }); const data = await response.json(); console.log(data); ``` ## Best Practices * Store API keys in environment variables * Use the preset with the fewest permissions for your use case * Rotate keys regularly * Keep `FULL` preset keys secure and never expose them client-side ## Troubleshooting ### 401 Unauthorized * Verify your API key is correct * Ensure the `Authorization` header includes the `Key` prefix * Check that your API key hasn't been revoked ### 403 Forbidden The key does not carry the permission the endpoint requires. Create a key on the preset that covers the surface you call, such as `BILLING` for billing endpoints or `COMPUTE` for compute endpoints. # Platform APIs for Accounts Source: https://fal.ai/docs/api-reference/platform-apis/for-accounts Programmatic access to account billing information, FOCUS-compliant cost reports, and model access controls The **fal Platform APIs** provide programmatic access to account-level billing, cost reporting, and governance, including: * **Billing information** - Retrieve account billing details and credit balances * **FOCUS reports** - Download FinOps FOCUS-compliant billing reports for cost analysis and interoperability * **Model access controls** - Export the resolved UI and API access state for each model in your organization ## Available Operations The Platform APIs provide the following endpoints for account billing, reporting, and governance: > [card] [Account Billing](/docs/platform-apis/v1/account/billing) > > Retrieve billing information and credit balances for your account > [card] [FOCUS Report](/docs/platform-apis/v1/account/focus) > > Download FOCUS-compliant billing reports from invoice or usage estimate data > [card] [Model Access Controls](/docs/platform-apis/v1/account/model-access-controls) > > Export the resolved UI and API access state for each model in your organization > [!NOTE] > > FOCUS reports and model access controls are available to enterprise customers with the corresponding features enabled. Contact your account team or [support@fal.ai](mailto:support@fal.ai) to request access. # Platform APIs for Assets Source: https://fal.ai/docs/api-reference/platform-apis/for-assets Programmatic access to fal Assets for browsing, searching, uploading, and organizing generated media The **fal Platform APIs** provide programmatic access to fal Assets, including: * **Browse and search** - List assets, filter by media type or source, and search with text or fal-hosted media * **Uploads** - Add media to your Assets library from API or CLI-driven workflows * **Collections** - Create manual collections and add or remove assets * **Characters** - Create reusable character collections with reference images * **Tags and favorites** - Organize assets with tags and favorite state Use these APIs when you want generated outputs, uploaded references, and reusable creative assets to be available outside the dashboard. For generating new media, use the [Model APIs](/docs/documentation/model-apis/overview), then use Assets to browse, search, and organize the media that belongs in your library. For an end-to-end example, see [Using the Assets API](/docs/documentation/assets/api). For browser workflows, see the [fal Assets guide](/docs/documentation/assets). ## Available Operations The Platform APIs provide the following endpoints for fal Assets: > [card] [Browse Assets](/docs/platform-apis/v1/assets) > > Browse and semantically search assets across media, uploads, favorites, collections, tags, and character references > [card] [Upload Asset](/docs/platform-apis/v1/assets/uploads) > > Upload fal-hosted media into your Assets library > [card] [Get Asset](/docs/platform-apis/v1/assets/get) > > Retrieve details for an asset in your library > [card] [Favorite Asset](/docs/platform-apis/v1/assets/favorite) > > Favorite an asset by vector ID or request ID ## Collections > [card] [List Collections](/docs/platform-apis/v1/assets/collections) > > List asset collections in your library > [card] [Create Collection](/docs/platform-apis/v1/assets/collections/create) > > Create a collection for organizing related assets > [card] [Browse Collection Assets](/docs/platform-apis/v1/assets/collections/assets) > > Browse assets inside a collection > [card] [Add Asset to Collection](/docs/platform-apis/v1/assets/collections/assets/add) > > Add an asset to a collection by vector ID or request ID ## Characters > [card] [List Characters](/docs/platform-apis/v1/assets/characters) > > List character collections in your library > [card] [Create Character](/docs/platform-apis/v1/assets/characters/create) > > Create a reusable character from descriptions and reference images > [card] [Get Character](/docs/platform-apis/v1/assets/characters/get) > > Retrieve a character collection > [card] [Favorite Character](/docs/platform-apis/v1/assets/characters/favorite) > > Mark a character collection as a favorite ## Tags > [card] [List Tags](/docs/platform-apis/v1/assets/tags) > > List tags in your Assets library > [card] [Create Tag](/docs/platform-apis/v1/assets/tags/create) > > Create a tag for organizing assets > [card] [Set Tags for Asset](/docs/platform-apis/v1/assets/tags/set-for-asset) > > Replace the full tag set for an asset > [card] [Assign Tag](/docs/platform-apis/v1/assets/tags/assign) > > Assign a tag to an asset by vector ID or request ID ## Authentication Assets endpoints require an API key in the `Authorization` header: ```bash theme={null} Authorization: Key YOUR_API_KEY ``` > [!NOTE] > > Assets must be enabled for the account associated with your API key. If generated media is missing, check the selected account and which request sources its configuration includes. See [Access and availability](/docs/documentation/assets/access). # Platform APIs for Compute Source: https://fal.ai/docs/api-reference/platform-apis/for-compute Programmatic access to compute instance management, lifecycle control, and monitoring The **fal Platform APIs** provide programmatic access to platform management features for Compute, including: * **Instance management** - List and delete compute instances * **Instance details** - Retrieve detailed information about specific instances ## Available Operations The Platform APIs provide the following endpoints for managing Compute instances: > [card] [List Instances](/docs/platform-apis/v1/compute/instances/list) > > List all compute instances with their current status and configuration > [card] [Get Instance Details](/docs/platform-apis/v1/compute/instances/get) > > Retrieve detailed information about a specific compute instance > [card] [Delete Instance](/docs/platform-apis/v1/compute/instances/delete) > > Terminate and remove a compute instance > [!NOTE] > > These APIs are for **platform management** of Compute instances. For getting started with Compute, see the [Compute documentation](/docs/compute). # Platform APIs for Keys Source: https://fal.ai/docs/api-reference/platform-apis/for-keys Programmatic access to API key management, creation, and revocation The **fal Platform APIs** provide programmatic access to API key management, including: * **List keys** - Retrieve the API keys in your account, with the permissions of each key * **Create keys** - Generate new keys on a preset or with a custom permission list * **Revoke keys** - Permanently disable existing API keys ## Available Operations The Platform APIs provide the following endpoints for managing API keys: > [card] [List API Keys](/docs/platform-apis/v1/keys/list) > > Retrieve all keys, with the mode, preset, and permissions of each key > [card] [Create API Key](/docs/platform-apis/v1/keys/create) > > Generate a new key on a preset or with a custom permission list > [card] [Revoke API Key](/docs/platform-apis/v1/keys/revoke) > > Permanently revoke a key and keep its audit record To create a key, send a `preset` or a `permissions` list. If you send neither, the key gets the `API` preset. A new key cannot have permissions that the calling key does not have. To limit a key to specific models, use the [dashboard](https://fal.ai/dashboard/keys). > [!NOTE] > > To list keys, use a key on the `BILLING` or `FULL` preset. To create or revoke a key, use a key on the `FULL` preset. A custom policy key with the same permissions also works. For more information, see [Key permissions](/docs/documentation/model-apis/authentication/key-based#permissions). # Platform APIs for Models Source: https://fal.ai/docs/api-reference/platform-apis/for-models Programmatic access to model metadata, pricing, usage tracking, and analytics The **fal Platform APIs** provide programmatic access to platform management features for Model APIs, including: * **Model metadata** - Search and discover available model endpoints with detailed information * **Pricing information** - Retrieve real-time pricing and estimate costs * **Usage tracking** - Access detailed usage line items with unit quantities and prices * **Analytics** - Query time-bucketed metrics for request counts, success/error rates, error-type breakdown, latency percentiles, cold boot metrics, and billable duration ## Available Operations The Platform APIs provide the following endpoints for managing Model APIs: > [card] [Model Search](/docs/platform-apis/v1/models) > > Search and discover available model endpoints with metadata, categories, and capabilities > [card] [Model Pricing](/docs/platform-apis/v1/models/pricing) > > Retrieve real-time pricing information for models > [card] [Estimate Cost](/docs/platform-apis/v1/models/pricing/estimate) > > Estimate costs for planned operations > [card] [Usage](/docs/platform-apis/v1/models/usage) > > Access detailed usage line items with unit quantities and prices > [card] [Analytics](/docs/platform-apis/v1/models/analytics) > > Query time-bucketed metrics for requests, success rates, error-type breakdown, latency percentiles, cold boot metrics, and billable duration > [card] [List Requests by Endpoint](/docs/platform-apis/v1/models/requests/by-endpoint) > > List recent requests for a specific model endpoint with filters and pagination > [card] [Delete Request Payloads](/docs/platform-apis/v1/models/requests/payloads) > > Delete IO payloads and CDN output files for a specific request > [!NOTE] > > These APIs are for **platform management** of Model APIs. For executing models and generating content, see the [Inference Methods](/docs/documentation/model-apis/inference) documentation. # Platform APIs for Organizations Source: https://fal.ai/docs/api-reference/platform-apis/for-organization Programmatic access to organization-wide team listings, cross-team usage records, FOCUS billing reports, and billing events The **fal Platform APIs** provide programmatic access to organization-level data spanning every team and product line, including: * **Team listings** - List all teams in your organization and identify the root team * **Usage records** - Browse cross-team, cross-product usage attributed to each team and product line * **FOCUS reports** - Download a FinOps FOCUS-compliant billing report as CSV, spanning every team in your organization * **Billing events** - Browse paginated per-request billing event records across all teams, with cost breakdowns in USD ## Available Operations The Platform APIs provide the following endpoints for organization administration: > [card] [Organization Teams](/docs/platform-apis/v1/organization/teams) > > List the teams in your organization with their details, including the root team > [card] [Organization Usage](/docs/platform-apis/v1/organization/usage) > > Browse paginated usage records across all teams and product lines, with per-team and per-product attribution > [card] [Organization FOCUS Report](/docs/platform-apis/v1/organization/focus) > > Download a FOCUS-compliant billing report as CSV spanning every team, with per-team sub-account attribution under pooled billing > [card] [Organization Billing Events](/docs/platform-apis/v1/organization/billing-events) > > Browse paginated per-request billing events across all teams, with per-team attribution and USD cost breakdowns > [!NOTE] > > These endpoints are available to enterprise customers with organizations enabled. Call them with a key on the `BILLING` preset that belongs to the root team of the organization. The Organization FOCUS Report also requires FOCUS reports to be enabled. Contact your account team or [support@fal.ai](mailto:support@fal.ai) to request access. # Platform APIs for Serverless Source: https://fal.ai/docs/api-reference/platform-apis/for-serverless Programmatic access to serverless apps metadata, analytics, and billing ## Available Operations The Platform APIs provide the following endpoints for Serverless Apps: ## Files > [card] [List Root Directory Contents](/docs/platform-apis/v1/serverless/files/list) > > List the contents of the root directory of your Serverless storage. > [card] [List Directory Contents](/docs/platform-apis/v1/serverless/files/list/directory) > > List the contents of any nested directory by providing its path. > [card] [Download File](/docs/platform-apis/v1/serverless/files/file/download) > > Download any file from Serverless storage. > [card] [Upload from URL](/docs/platform-apis/v1/serverless/files/file/upload-from-url) > > Upload a file from a URL into Serverless storage. > [card] [Upload Local File](/docs/platform-apis/v1/serverless/files/file/upload-local) > > Upload a local file into Serverless storage. ## Requests > [card] [List Requests by Endpoint](/docs/platform-apis/v1/serverless/requests/by-endpoint) > > List recent requests for your serverless endpoints with filtering, sorting, and pagination. Pass `expand=billing` to include `billable_units` per request — the per-request building block for cost reporting on your deployed apps. ## Billing Per-request billing data for your serverless apps is available through the `expand=billing` parameter on [List Requests by Endpoint](/docs/platform-apis/v1/serverless/requests/by-endpoint). Each request in the response includes a `billable_units` field representing the units fal billed for that invocation. > [!NOTE] > > `billable_units` is the raw unit count for each request. To compute total cost, multiply by your effective per-unit price for the app. For account-level credit balance, see [Account Billing](/docs/platform-apis/v1/account/billing). ```bash Example theme={null} curl -G "https://api.fal.ai/v1/serverless/requests/by-endpoint" \ -H "Authorization: Key $FAL_KEY" \ --data-urlencode "endpoint_id=your-username/your-app" \ --data-urlencode "expand=billing" ``` Sample response shape (truncated): ```json theme={null} { "items": [ { "request_id": "a1b2c3d4-...", "endpoint_id": "your-username/your-app", "ended_at": "2025-01-01T00:00:08Z", "status_code": 200, "duration": 7.8, "billable_units": 1.5 } ], "next_cursor": "Mg==", "has_more": true } ``` `billable_units` will be `null` if a billing event hasn't been recorded yet for the request (e.g., the request just completed and the billing pipeline hasn't caught up). ## Usage > [card] [Usage](/docs/platform-apis/v1/serverless/usage) > > Time-bucketed, aggregated compute usage for the serverless apps **you own** — the machine-seconds your deployed apps consumed, priced with your machine rates and net of discounts. The aggregated counterpart to the per-request `billable_units` above. Where [List Requests by Endpoint](/docs/platform-apis/v1/serverless/requests/by-endpoint) gives you per-request billing, **Usage** gives you the rolled-up view: how many machine-seconds each of your apps consumed and what it cost, grouped by app, environment, and machine type. It reports your *own* compute spend, scoped to the apps you own. > [!NOTE] > > This endpoint returns billing and usage data, so it requires a key on the **`BILLING`**, **`READONLY`**, or **`FULL`** preset. A key on the `API` preset receives a `403`. ### Filtering by app The `app` field in the response is your deployed app's name (e.g. `my-app-prod`). Two ways to narrow results: * **`app`** — exact match on one or more app names. Comma-separated or repeated, up to 50: `app=my-app-dev,my-app-prod`. Use the value exactly as it appears in the response. * **`search`** — case-insensitive substring match on the app name, for when you know the name but not the exact environment/version suffix: `search=my-app` returns every `my-app*` variant. Provide both to combine them (AND). Omit both to return every app you own — useful for discovering the exact names to filter on. ```bash Summary across all your apps (last 30 days) theme={null} curl -G "https://api.fal.ai/v1/serverless/usage" \ -H "Authorization: Key $FAL_KEY" \ --data-urlencode "start=2025-01-01" \ --data-urlencode "end=2025-01-31" \ --data-urlencode "expand=summary" ``` ```bash One app, daily time series theme={null} curl -G "https://api.fal.ai/v1/serverless/usage" \ -H "Authorization: Key $FAL_KEY" \ --data-urlencode "app=my-app-prod" \ --data-urlencode "start=2025-01-01" \ --data-urlencode "end=2025-01-31" \ --data-urlencode "timeframe=day" ``` ```bash All variants of an app by name theme={null} curl -G "https://api.fal.ai/v1/serverless/usage" \ -H "Authorization: Key $FAL_KEY" \ --data-urlencode "search=my-app" \ --data-urlencode "expand=summary" ``` Sample response shape (`expand=summary`): ```json theme={null} { "summary": [ { "app": "my-app-prod", "environment": null, "machine_type": "GPU-H100", "unit": "second", "quantity": 9702.47, "unit_price": 0.00125, "cost": 12.13, "currency": "USD", "is_surge": false } ], "next_cursor": null, "has_more": false } ``` > [!NOTE] > > Each row is machine-seconds (`unit` is always `"second"`). Surge and non-surge usage of the same app and machine type are returned as **separate rows** (`is_surge`), so sum across them for a per-app total. Time-series `bucket` timestamps are returned in the `timezone` you request (ISO 8601 with offset, e.g. `2025-01-15T00:00:00-05:00`), which also controls how usage is grouped. `cost` is already net of your discounts. ## Logs > [card] [Logs History](/docs/platform-apis/v1/serverless/logs/history) > > Query paginated logs with powerful label filters, time ranges, and search keywords. > [card] [Logs Stream](/docs/platform-apis/v1/serverless/logs/stream) > > Stream live logs that match the provided filters using Server-Sent Events. ## Analytics > [card] [Analytics](/docs/platform-apis/v1/serverless/analytics) > > Query time-bucketed metrics across all inbound traffic to your apps — request counts, error-type breakdown (startup, connection, timeout, runtime), latency percentiles (p25 through p99), cold boot metrics, and total billable duration. Ideal for exporting to your own observability tools. ## Metrics > [card] [Queue Size](/docs/platform-apis/v1/serverless/apps/queue) > > Read the current queue backlog for your serverless applications. > [card] [Metrics](/docs/platform-apis/v1/serverless/metrics) > > Export app metrics (runners, queue size, concurrent requests, throughput, and latency) in Prometheus format for custom dashboards and monitoring. # Platform APIs for Storage Source: https://fal.ai/docs/api-reference/platform-apis/for-storage Manage access control, signed URLs, and lifecycle settings for fal CDN files The **fal Platform APIs** for Storage provide programmatic control over files stored on the fal CDN, including: * **File ACLs** - Read and replace the Access Control List of a CDN file to make it public, restrict it, or grant access to specific users * **Signed URLs** - Mint time-limited URLs that grant temporary access to access-restricted files (valid up to 7 days) * **Account storage settings** - Configure account-wide defaults for newly uploaded files, including auto-expiration and the initial ACL ## Available Operations The Platform APIs provide the following endpoints for Storage: > [card] [Get File ACL](/docs/platform-apis/v1/storage/files/acl/get) > > Retrieve the Access Control List currently applied to a fal CDN file > [card] [Set File ACL](/docs/platform-apis/v1/storage/files/acl/set) > > Replace the Access Control List of a fal CDN file with a default decision and > optional per-user rules > [card] [Sign File URL](/docs/platform-apis/v1/storage/files/sign) > > Create a signed URL that grants temporary access to a file regardless of its > ACL > [card] [Get Storage Settings](/docs/platform-apis/v1/storage/settings/get) > > Read the account-level lifecycle settings applied to newly uploaded files > [card] [Update Storage Settings](/docs/platform-apis/v1/storage/settings/update) > > Replace the account-level defaults for auto-expiration and the initial ACL of > new uploads ## Access Control Lists A file ACL is composed of a **default decision** plus optional **per-user rules** that override the default: * `allow` - access is granted * `forbid` - access is denied (the file returns an error) * `hide` - access is denied and the file is treated as if it does not exist Setting `default` to `allow` with no rules makes a file public. Using `forbid` or `hide` restricts the file to only the users named in the rules. > [!NOTE] > > Rules that reference users who do not exist are dropped. The response always > reflects the ACL actually applied, so verify it contains the rules you sent. ## Authentication All Storage endpoints require authentication. Include your API key in the `Authorization` header: ``` Authorization: Key YOUR_API_KEY ``` Permissions are split by capability: | Operation | Required permission | | - | - | | Get file ACL / Sign file URL | `assets:read` | | Set file ACL | `assets:write` | | Get storage settings | `account:settings:read` | | Update storage settings | `account:settings:write` | # Platform APIs for Workflows Source: https://fal.ai/docs/api-reference/platform-apis/for-workflows Programmatic access to workflow creation, metadata, listing, and details The **fal Platform APIs** provide programmatic access to workflow management for the authenticated user, including: * **List workflows** - Paginated list of your workflows with optional search and filtering * **Get workflow details** - Retrieve a specific workflow by owner and name, including its full definition * **Create workflow** - Create a new workflow owned by the authenticated user ## Available Operations The Platform APIs provide the following endpoints for Workflows: > [card] [List Workflows](/docs/platform-apis/v1/workflows) > > List workflows for the authenticated user with optional search and filtering > by endpoint > [card] [Get Workflow Details](/docs/platform-apis/v1/workflows/get) > > Get detailed information about a specific workflow, including its full > definition > [card] [Create Workflow](/docs/platform-apis/v1/workflows/create) > > Create a new workflow owned by the authenticated user ## Authentication All Workflows endpoints require authentication. Include your API key in the `Authorization` header: ``` Authorization: Key YOUR_API_KEY ``` List workflows returns only workflows owned by the authenticated user. Get workflow details requires access to the workflow (e.g., it is yours or public). Creating a workflow adds it to the authenticated user's namespace. > [!NOTE] > > These APIs are for **platform management** of Workflows (creating, listing, > and reading). To run workflows, use the [Model APIs](/docs/model-apis) or workflow > execution endpoints. # Introduction to Platform APIs Source: https://fal.ai/docs/api-reference/platform-apis/index Platform APIs provide programmatic access to platform resources including model metadata, usage tracking, analytics, and fal Assets. > [card] [Platform APIs for Models](/docs/api-reference/platform-apis/for-models) > > Access model metadata, pricing information, usage tracking, and analytics for Model APIs > [card] [Platform APIs for Assets](/docs/api-reference/platform-apis/for-assets) > > Browse, search, upload, and organize generated or uploaded media in fal Assets > [card] [Platform APIs for Storage](/docs/api-reference/platform-apis/for-storage) > > Control access, sign URLs, and manage lifecycle settings for fal CDN files > [card] [Platform APIs for Serverless](/docs/api-reference/platform-apis/for-serverless) > > APIs to manage and monitor your serverless applications > [card] [Platform APIs for Compute](/docs/api-reference/platform-apis/for-compute) > > Manage compute instances with lifecycle control and monitoring capabilities > [card] [Platform APIs for Workflows](/docs/api-reference/platform-apis/for-workflows) > > List and retrieve workflow metadata and definitions > [card] [Platform APIs for Accounts](/docs/api-reference/platform-apis/for-accounts) > > Access account billing information and FOCUS-compliant cost reports > [!NOTE] > > For executing models and generating content, see [Model APIs](/docs/documentation/model-apis/overview). To call models over HTTP, see the [Inference API](/docs/api-reference/inference-api). # Platform Metadata Source: https://fal.ai/docs/api-reference/platform-apis/meta GET /meta Returns platform metadata including webhook IP ranges for allowlisting. If your infrastructure requires allowlisting IP addresses for incoming webhook requests, this endpoint provides the current list of IP ranges used by fal.ai webhooks in CIDR notation. **Authentication:** not required. # OpenAPI Schema Source: https://fal.ai/docs/api-reference/platform-apis/openapi-schema The fal Platform API is documented using the OpenAPI 3.1 specification format. ## Download Download the complete OpenAPI schema to integrate with your tools and workflows: > [card] [OpenAPI Specification](https://api.fal.ai/v1/openapi.json) > > Download the OpenAPI 3.1 JSON schema ## Use Cases The OpenAPI schema enables you to: * **Generate Client SDKs**: Use tools like OpenAPI Generator to create client libraries in your preferred language * **API Testing**: Import into testing tools like Postman or Insomnia * **Code Generation**: Generate type definitions and API interfaces * **Documentation**: Use with documentation generators and API explorers * **Validation**: Validate API requests and responses against the schema ## Schema URL ``` https://api.fal.ai/v1/openapi.json ``` ## Integration Examples ### Postman 1. Open Postman 2. Click **Import** 3. Select **Link** and paste the schema URL 4. Postman will generate a collection from the OpenAPI spec ### OpenAPI Generator Generate a client library using the OpenAPI Generator: ```bash theme={null} openapi-generator-cli generate \ -i https://api.fal.ai/v1/openapi.json \ -g python \ -o ./fal-api-client ``` ### Swagger UI View the API documentation in Swagger UI: ```bash theme={null} docker run -p 8080:8080 \ -e SWAGGER_JSON_URL=https://api.fal.ai/v1/openapi.json \ swaggerapi/swagger-ui ``` ## Specification Details * **Version**: OpenAPI 3.1.0 * **Format**: JSON * **Authentication**: API key. The required preset depends on the endpoint. See [Key permissions](/docs/documentation/model-apis/authentication/key-based#permissions). * **Base URL**: `https://api.fal.ai/v1` # fal.api Source: https://fal.ai/docs/api-reference/python-sdk/api-reference API reference for fal.api ```python theme={null} from fal.api import ( SyncServerlessClient, AppsNamespace, RunnersNamespace, KeysNamespace, SecretsNamespace, ) ``` ## Classes ### SyncServerlessClient ```python theme={null} class fal.api.SyncServerlessClient ``` Synchronous Python client for fal Serverless. Manage apps, runners, and deployments programmatically. The namespaces and methods mirror the CLI so you can automate the same workflows from Python. **Example:** ```python theme={null} from fal.api import SyncServerlessClient client = SyncServerlessClient() # List apps apps = client.apps.list() # Scale an app client.apps.scale("my-app", max_concurrency=10) # Deploy client.deploy("path/to/myfile.py::MyApp") ``` **Namespaces:** * client.apps.\* - corresponds to `fal apps ...` * client.runners.\* - corresponds to `fal runners ...` * client.keys.\* - corresponds to `fal keys ...` * client.secrets.\* - corresponds to `fal secrets ...` * client.deploy() - corresponds to `fal deploy ...` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `host` | `Optional[str]` | `None` | Optional. Override API host. | > | `api_key` | `Optional[str]` | `None` | Optional. If omitted, read from env/profile. | > | `profile` | `Optional[str]` | `None` | Optional. Named profile to use. | > | `team` | `Optional[str]` | `None` | Optional. Team context for runner operations. | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `host` | `Optional[str]` | `None` | - | > | `api_key` | `Optional[str]` | `None` | - | > | `profile` | `Optional[str]` | `None` | - | > | `team` | `Optional[str]` | `None` | - | > [accordion] Properties > > | Name | Type | Description | > | :- | :- | :- | > | `_credentials` | `Credentials` | - | > | `_grpc_host` | `str` | - | > | `_rest_url` | `str` | - | > [accordion] Methods > > #### deploy > > ```python theme={null} > def deploy(self, *args, **kwargs) > ``` > > Deploy an application. Corresponds to `fal deploy`. If app\_ref is omitted, discovery behavior matches the CLI > (e.g., uses pyproject.toml). > > **Example:** > > ```python theme={null} > # Auto-discover from pyproject.toml > client.deploy() > > # Deploy from a file path > client.deploy("path/to/myfile.py") > > # Deploy a specific class > client.deploy("path/to/myfile.py::MyApp") > > # With options > client.deploy( > app_ref="path/to/myfile.py::MyApp", > app_name="myapp", > auth="public", > strategy="rolling", > ) > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `args` | - | - | - | > | `kwargs` | - | - | - | ### AppsNamespace ```python theme={null} class fal.api.AppsNamespace ``` Namespace for app management operations. Corresponds to `fal apps ...` CLI commands. Accessed via `client.apps`. **Example:** ```python theme={null} from fal.api import SyncServerlessClient client = SyncServerlessClient() apps = client.apps.list() client.apps.scale("my-app", max_concurrency=10) ``` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `client` | `SyncServerlessClient` | - | - | > [accordion] Methods > > #### gpus > > ```python theme={null} > def gpus(self, app_name: 'str') -> 'dict' > ``` > > Get GPU usage for a single application. Corresponds to `fal apps gpus \`. Returns > `\{"gpus": \{\: \, ...\}, "total": \\}`. > > **Example:** > > ```python theme={null} > usage = client.apps.gpus("fal-ai/flux") > print(usage["total"]) # e.g. 21 > print(usage["gpus"]) # e.g. {"B200": 21} > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `app_name` | `str` | - | - | > > **Returns:** `dict` > > #### list > > ```python theme={null} > def list(self, *, filter: 'str | None' = None, environment_name: 'str | None' = None) -> 'List[AliasInfo]' > ``` > > List all applications. Corresponds to `fal apps list`. > > **Example:** > > ```python theme={null} > apps = client.apps.list() > filtered = client.apps.list(filter="stable") > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `filter` | `Optional[str]` | `None` | Optional app name filter string. | > | `environment_name` | `Optional[str]` | `None` | Optional environment name. | > > **Returns:** `list[AliasInfo]` > > #### rollout > > ```python theme={null} > def rollout(self, app_name: 'str', *, force: 'bool' = False, environment_name: 'str | None' = None) -> 'None' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `app_name` | `str` | - | - | > | `force` | `bool` | `False` | - | > | `environment_name` | `Optional[str]` | `None` | - | > > **Returns:** `NoneType` > > #### runners > > ```python theme={null} > def runners(self, app_name: 'str', *, since=None, state: 'List[str] | None' = None, environment_name: 'str | None' = None) -> 'List[RunnerInfo]' > ``` > > List runners for a specific app. Corresponds to `fal apps runners \`. > > **Example:** > > ```python theme={null} > from datetime import datetime, timedelta > > runners = client.apps.runners("my-app") > recent = client.apps.runners( > "my-app", since=datetime.now() - timedelta(hours=1) > ) > running = client.apps.runners("my-app", state=["running"]) > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `app_name` | `str` | - | Name of the application. | > | `since` | - | `None` | Only return runners started after this datetime. | > | `state` | `Optional[list[str]]` | `None` | Filter by runner state (e.g., \["running"]). | > | `environment_name` | `Optional[str]` | `None` | Optional environment name. | > > **Returns:** `list[RunnerInfo]` > > #### scale > > ```python theme={null} > def scale(self, app_name: 'str', *, keep_alive: 'int | None' = None, max_multiplexing: 'int | None' = None, max_concurrency: 'int | None' = None, min_concurrency: 'int | None' = None, concurrency_buffer: 'int | None' = None, concurrency_buffer_perc: 'int | None' = None, scaling_delay: 'int | None' = None, request_timeout: 'int | None' = None, startup_timeout: 'int | None' = None, machine_types: 'List[str] | None' = None, regions: 'List[str] | None' = None, environment_name: 'str | None' = None) -> 'apps_api.AliasInfo' > ``` > > Adjust scaling settings for an application. Corresponds to `fal apps scale`. Any omitted option keeps the current value. > > **Example:** > > ```python theme={null} > client.apps.scale( > "my-app", > keep_alive=300, > max_concurrency=10, > min_concurrency=1, > machine_types=["GPU-H100", "GPU-H200"], > ) > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `app_name` | `str` | - | Name of the application. | > | `keep_alive` | `Optional[int]` | `None` | Keep-alive time in seconds. | > | `max_multiplexing` | `Optional[int]` | `None` | Maximum request multiplexing. | > | `max_concurrency` | `Optional[int]` | `None` | Maximum concurrent runners. | > | `min_concurrency` | `Optional[int]` | `None` | Minimum concurrent runners. | > | `concurrency_buffer` | `Optional[int]` | `None` | - | > | `concurrency_buffer_perc` | `Optional[int]` | `None` | - | > | `scaling_delay` | `Optional[int]` | `None` | - | > | `request_timeout` | `Optional[int]` | `None` | Request timeout in seconds. | > | `startup_timeout` | `Optional[int]` | `None` | Startup timeout in seconds. | > | `machine_types` | `Optional[list[str]]` | `None` | List of allowed machine types (e.g., \["GPU-H100"]). | > | `regions` | `Optional[list[str]]` | `None` | List of allowed regions (e.g., \["us-east"]). | > | `environment_name` | `Optional[str]` | `None` | - | > > **Returns:** `AliasInfo` ### RunnersNamespace ```python theme={null} class fal.api.RunnersNamespace ``` Namespace for runner management operations. Corresponds to `fal runners ...` CLI commands. Accessed via `client.runners`. **Example:** ```python theme={null} from fal.api import SyncServerlessClient client = SyncServerlessClient() runners = client.runners.list() client.runners.stop("runner-id") ``` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `client` | `SyncServerlessClient` | - | - | > [accordion] Methods > > #### gpus > > ```python theme={null} > def gpus(self) -> 'dict' > ``` > > Get team-wide GPU usage summary. Corresponds to `fal runners gpus`. Returns > `\{"gpus": \{\: \, ...\}, "total": \\}`. > > **Example:** > > ```python theme={null} > usage = client.runners.gpus() > print(usage["total"]) # e.g. 1120 > print(usage["gpus"]) # e.g. {"H100": 394, "B200": 353, ...} > ``` > > **Returns:** `dict` > > #### kill > > ```python theme={null} > def kill(self, runner_id: 'str') -> 'None' > ``` > > Forcefully kill a runner. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `runner_id` | `str` | - | The ID of the runner to kill. | > > **Returns:** `NoneType` > > #### list > > ```python theme={null} > def list(self, *, since=None) -> 'List[RunnerInfo]' > ``` > > List all runners. Corresponds to `fal runners list`. > > **Example:** > > ```python theme={null} > from datetime import datetime, timedelta > > all_runners = client.runners.list() > recent = client.runners.list(since=datetime.now() - timedelta(minutes=10)) > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `since` | - | `None` | Only return runners started after this datetime. | > > **Returns:** `list[RunnerInfo]` > > #### stop > > ```python theme={null} > def stop(self, runner_id: 'str', replace_first: 'bool' = False) -> 'None' > ``` > > Gracefully stop a runner. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `runner_id` | `str` | - | The ID of the runner to stop. | > | `replace_first` | `bool` | `False` | Whether to replace the runner before stopping it. | > > **Returns:** `NoneType` ### KeysNamespace ```python theme={null} class fal.api.KeysNamespace ``` Namespace for API key management. Corresponds to `fal keys ...` CLI commands. Accessed via `client.keys`. **Example:** ```python theme={null} from fal.api import SyncServerlessClient client = SyncServerlessClient() keys = client.keys.list() key_id, key_secret = client.keys.create(scope="admin") ``` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `client` | `SyncServerlessClient` | - | - | > [accordion] Methods > > #### create > > ```python theme={null} > def create(self, *, scope: 'KeyScope', description: 'str | None' = None) -> 'tuple[str, str]' > ``` > > Create a new API key. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `scope` | `KeyScope` | - | Key scope (e.g., "admin"). | > | `description` | `Optional[str]` | `None` | Optional description for the key. | > > **Returns:** `tuple[str, str]` > > #### list > > ```python theme={null} > def list(self) -> 'List[UserKeyInfo]' > ``` > > List all API keys. > > **Returns:** `list[UserKeyInfo]` > > #### revoke > > ```python theme={null} > def revoke(self, key_id: 'str') -> 'None' > ``` > > Revoke an API key. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `key_id` | `str` | - | The ID of the key to revoke. | > > **Returns:** `NoneType` ### SecretsNamespace ```python theme={null} class fal.api.SecretsNamespace ``` Namespace for secrets management. Corresponds to `fal secrets ...` CLI commands. Accessed via `client.secrets`. **Example:** ```python theme={null} from fal.api import SyncServerlessClient client = SyncServerlessClient() client.secrets.set("API_KEY", "my-secret-value") secrets = client.secrets.list() ``` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `client` | `SyncServerlessClient` | - | - | > [accordion] Methods > > #### list > > ```python theme={null} > def list(self, environment_name: 'str | None' = None) -> 'List[ServerlessSecret]' > ``` > > List all secrets (names only, not values). > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `environment_name` | `Optional[str]` | `None` | - | > > **Returns:** `list[ServerlessSecret]` > > #### set > > ```python theme={null} > def set(self, name: 'str', value: 'str', environment_name: 'str | None' = None, default_exposed: 'bool | None' = None) -> 'None' > ``` > > Set a secret value. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `name` | `str` | - | Name of the secret. | > | `value` | `str` | - | Value to store. | > | `environment_name` | `Optional[str]` | `None` | Optional environment name. | > | `default_exposed` | `Optional[bool]` | `None` | Whether the secret is exposed to apps that do not explicitly list their secrets. None keeps the account-level default (and preserves the current setting on updates). | > > **Returns:** `NoneType` > > #### unset > > ```python theme={null} > def unset(self, name: 'str', environment_name: 'str | None' = None) -> 'None' > ``` > > Delete a secret. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `name` | `str` | - | Name of the secret to delete. | > | `environment_name` | `Optional[str]` | `None` | Optional environment name. | > > **Returns:** `NoneType` # SyncServerlessClient Source: https://fal.ai/docs/api-reference/python-sdk/client Synchronous Python client for fal Serverless. Manage apps, runners, and deployments programmatically. The `SyncServerlessClient` is the synchronous Python client for interacting with fal Serverless. Its namespaces and methods mirror the CLI so you can automate the same workflows from Python. ## Import and Initialize ```python theme={null} from fal.api import SyncServerlessClient client = SyncServerlessClient( host=None, # Optional. Override API host api_key=None, # Optional. If omitted, read from env/profile profile=None, # Optional. Named profile to use team=None, # Optional. Team context for runner ops ) ``` ## Overview of Namespaces * `client.apps.*` — corresponds to `fal apps ...` * `client.runners.*` — corresponds to `fal runners ...` * `client.secrets.*` — corresponds to `fal secrets ...` * `client.keys.*` — corresponds to `fal keys ...` * `client.environments.*` — corresponds to `fal environments ...` * `client.deploy(...)` — corresponds to `fal deploy ...` ## Apps Namespace Manage your applications: list them, view runners for a specific app, and adjust scaling. ### List Applications (fal apps list) ```python theme={null} apps = client.apps.list() # Optional app name filter filtered = client.apps.list(filter="stable") # List apps in a specific environment staging_apps = client.apps.list(environment_name="staging") ``` ### List App Runners (fal apps runners my-app) ```python theme={null} app_runners = client.apps.runners("my-app") # Optional filters recent = client.apps.runners("my-app", since=datetime.now() - timedelta(hours=1)) # last hour running_only = client.apps.runners("my-app", state=["running"]) # by state # List runners for an app in a specific environment staging_runners = client.apps.runners("my-app", environment_name="staging") ``` ### Scale Application (fal apps scale) Maps to CLI flags in `fal apps scale`. Any omitted option keeps the current value. ```python theme={null} client.apps.scale( "my-app", keep_alive=300, # seconds max_multiplexing=1, max_concurrency=10, min_concurrency=1, request_timeout=600, # seconds startup_timeout=900, # seconds machine_types=["GPU-H100", "GPU-H200"], regions=["us-east-1", "us-west-2"], concurrency_buffer=1, concurrency_buffer_perc=10, environment_name="staging", # target environment ) ``` ### Rollout Application (fal apps rollout) ```python theme={null} client.apps.rollout("my-app") # Force rollout client.apps.rollout("my-app", force=True) # Rollout in a specific environment client.apps.rollout("my-app", environment_name="staging") ``` ## Runners Namespace List and manage runners. ### List Runners (fal runners list) ```python theme={null} all_runners = client.runners.list() # Recent runners only last_10_min = client.runners.list(since=datetime.now() - timedelta(minutes=10)) ``` ## Keys Namespace Create and manage API keys that the service uses to authenticate requests. The Python surface mirrors `fal keys ...`. ### Create Key (fal keys create) ```python theme={null} from fal.sdk import KeyScope # ADMIN keys can manage resources; API keys are limited to app invocation. key_id, key_secret = client.keys.create( scope=KeyScope.ADMIN, # or KeyScope.API description="CI deploy key", ) print(f"Store securely: {key_id}:{key_secret}") # secret shown only once ``` ### List Keys (fal keys list) ```python theme={null} keys = client.keys.list() for key in keys: print(key.key_id, key.scope.value, key.alias) # alias holds the description ``` ### Revoke Key (fal keys revoke) ```python theme={null} client.keys.revoke("key-id-to-revoke") ``` ## Secrets Namespace Store configuration values for builds and runtime without hardcoding them. Values are never returned when you list secrets. ### Set Secret (fal secrets set) ```python theme={null} client.secrets.set("MY_API_TOKEN", "s3cr3t-value") # Set secret in a specific environment client.secrets.set("MY_API_TOKEN", "staging-value", environment_name="staging") ``` ### List Secrets (fal secrets list) ```python theme={null} secrets = client.secrets.list() for secret in secrets: print(secret.name, secret.created_at, secret.environment_name) # List secrets for a specific environment staging_secrets = client.secrets.list(environment_name="staging") ``` ### Unset Secret (fal secrets unset) ```python theme={null} client.secrets.unset("MY_API_TOKEN") # Unset secret in a specific environment client.secrets.unset("MY_API_TOKEN", environment_name="staging") ``` ## Environments Namespace Create and manage environments to organize your applications and secrets across different stages (development, staging, production). ### Create Environment (fal environments create) ```python theme={null} env = client.environments.create("staging", description="Staging environment") print(f"Created: {env.name}") ``` ### List Environments (fal environments list) ```python theme={null} environments = client.environments.list() for env in environments: print(env.name, env.description, env.is_default) ``` ### Delete Environment (fal environments delete) ```python theme={null} client.environments.delete("staging") ``` > [!WARNING] > > Deleting an environment removes all apps and secrets in that environment. ## Deploy (fal deploy) Programmatic equivalent of `fal deploy`. If `app_ref` is omitted, discovery behavior matches the CLI (e.g., `pyproject.toml`). ```python theme={null} # Auto-discover client.deploy() # Deploy from a file path client.deploy("path/to/myfile.py") # Deploy a specific class in a file client.deploy("path/to/myfile.py::MyApp") # Deploy by existing app name client.deploy("my-app") # With options mirroring CLI flags client.deploy( app_ref="path/to/myfile.py::MyApp", app_name="myapp", auth="public", # "private" | "public" strategy="rolling", # "recreate" | "rolling" reset_scale=True, # use previous scaling if False environment_name="staging", # target environment message="a1b2c3d fix cold-start", # freeform message for this revision annotations={"GIT_SHA": "a1b2c3d4"}, # custom key/value pairs for this revision ) ``` The `message` and `annotations` are attached to the revision and can be used to identify it later in the dashboard or via the [revisions API](/docs/platform-apis/v1/serverless/apps/revisions). Annotation keys and values must be strings. ## Reference > [card] [CLI Overview](/docs/serverless/python/cli) > > CLI commands that mirror these methods > [card] [API Reference](/docs/reference/serverless-sdk/fal.api) > > Full method signatures and types # fal Source: https://fal.ai/docs/api-reference/python-sdk/fal API reference for fal ```python theme={null} from fal import ( App, HealthCheck, FalServerlessKeyCredentials, ContainerImage, function, cached, endpoint, realtime, sync_dir, ) ``` ## Classes ### App ```python theme={null} class fal.App ``` Create a fal serverless application. Subclass this to define your application with custom setup, endpoints, and configuration. The App class handles model loading, request routing, and lifecycle management. **Example:** ```python theme={null} >>> class TextToImage(fal.App, machine_type="GPU"): ... requirements = ["diffusers", "torch"] ... ... def setup(self): ... self.pipe = StableDiffusionPipeline.from_pretrained( ... "runwayml/stable-diffusion-v1-5" ... ) ... ... @fal.endpoint("/") ... def generate(self, prompt: str) -> dict: ... image = self.pipe(prompt).images[0] ... return {"url": fal.toolkit.upload_image(image)} ``` > **Inherits from:** `BaseServable` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `_allow_init` | `bool` | `False` | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `requirements` | `ClassVar[list[str] \| list[list[str]]]` | `[]` | Pip packages to install in the environment. Supports standard pip syntax including version specifiers. Use a list of strings for a single install step, or a list of lists to install in multiple steps. Example: `["numpy==1.24.0", "torch\>=2.0.0"]` or `[["setuptools", "wheel"], ["numpy==1.24.0"]]` | > | `requirements_context_dir` | `ClassVar[Optional[str]]` | `None` | Base directory for resolving local-path requirements such as `.[extra]` or `../shared[extra]`. Defaults to the directory containing the app file. | > | `local_python_modules` | `ClassVar[list[str]]` | `[]` | List of local Python module names to include in the deployment. Use for custom code not available on PyPI. Example: `["my_utils", "models"]` | > | `machine_type` | `ClassVar[str \| list[str]]` | `'S'` | Compute instance type for your application. CPU options: 'XS', 'S' (default), 'M', 'L'. GPU options: 'GPU-A6000', 'GPU-A100', 'GPU-H100', 'GPU-H200', 'GPU-B200'. Use a string for a single type, or a list to define fallback types (tried in order until one is available). Example: `"GPU-A100"` or `["GPU-H100", "GPU-A100"]` | > | `num_gpus` | `ClassVar[int \| None]` | `None` | Number of GPUs to allocate. Only applies to GPU machine types. | > | `regions` | `ClassVar[Optional[list[str]]]` | `None` | Allowed regions for deployment. None means any region. Example: `["us-east", "eu-west"]` | > | `host_kwargs` | `ClassVar[dict[str, Any]]` | `\{'_scheduler': 'nomad', '_scheduler_options': \{'storage_region': 'us-east'\}, 'resolver': 'uv', 'keep_alive': 60\}` | Advanced configuration dictionary passed to the host. For internal use. Prefer using class attributes instead. | > | `app_name` | `ClassVar[Optional[str]]` | `None` | Custom name for the application. Defaults to class name. | > | `app_auth` | `ClassVar[Optional[AuthModeLiteral]]` | `None` | Authentication mode. Options: 'private' (API key required), 'public' (no auth), 'shared' (shareable link). | > | `app_files` | `ClassVar[list[str]]` | `[]` | List of files/directories to include in deployment. Example: `["./models", "./config.yaml"]` | > | `app_files_ignore` | `ClassVar[list[str]]` | `['\\.pyc$', '__pycache__/', '\\.git/', '\\.DS_Store$']` | Regex patterns to exclude from deployment. Default excludes `.pyc`, `__pycache__`, `.git`, `.DS_Store`. | > | `app_files_context_dir` | `ClassVar[Optional[str]]` | `None` | Base directory for resolving app\_files paths. Defaults to the directory containing the app file. | > | `request_timeout` | `ClassVar[Optional[int]]` | `None` | Maximum seconds for a single request. None for default. | > | `startup_timeout` | `ClassVar[Optional[int]]` | `None` | Maximum seconds for app startup/setup. None for default. | > | `metrics_port` | `ClassVar[Optional[int]]` | `None` | Internal metrics server port for platform scrapes. When omitted, served/exposed deployments default to 9090. | > | `min_concurrency` | `ClassVar[Optional[int]]` | `None` | Minimum warm instances to keep running. Set to 1+ to avoid cold starts. Default is 0 (scale to zero). | > | `max_concurrency` | `ClassVar[Optional[int]]` | `None` | Maximum instances to scale up to. | > | `concurrency_buffer` | `ClassVar[Optional[int]]` | `None` | Additional instances to keep warm above current load. | > | `concurrency_buffer_perc` | `ClassVar[Optional[int]]` | `None` | Percentage buffer of instances above current load. | > | `scaling_delay` | `ClassVar[Optional[int]]` | `None` | Seconds to wait for a request to be picked up by a runner before triggering a scale up. Useful for apps with slow startup times. | > | `max_multiplexing` | `ClassVar[Optional[int]]` | `None` | Maximum concurrent requests per instance. | > | `kind` | `ClassVar[Optional[str]]` | `None` | Deployment kind. For internal use. | > | `image` | `ClassVar[Optional[ContainerImage]]` | `None` | Custom container image for the application. Use ContainerImage to specify a Dockerfile. | > | `local_file_path` | `ClassVar[Optional[str]]` | `None` | - | > | `skip_retry_conditions` | `ClassVar[Optional[list[RetryConditionLiteral]]]` | `None` | - | > | `retry_config` | `ClassVar[Optional[RetryConfig \| RetryConfigDict]]` | `None` | - | > | `termination_grace_period_seconds` | `ClassVar[Optional[int]]` | `None` | - | > | `secrets` | `ClassVar[Optional[list[str]]]` | `None` | Names of user secrets to expose to the app as environment variables. When omitted, the server applies the default behavior (follows the user's preferences). Pass an explicit list to opt in to only the secrets listed. Example: `["OPENAI_API_KEY", "HF_TOKEN"]` | > | `data_mounts` | `ClassVar[Optional[list[str]]]` | `None` | Persistent data mount paths to expose to the application. Use `["/data"]` for full access, or specific subdirectories like `["/data/.cache"]`. When omitted (None), the server applies a default based on the user model. | > | `isolate_channel` | `async_grpc.Channel \| None` | `None` | - | > [accordion] Properties > > | Name | Type | Description | > | :- | :- | :- | > | `current_request` | `Optional[RequestContext]` | - | > [accordion] Methods > > #### build\_metadata > > ```python theme={null} > def build_metadata(cls) -> 'dict[str, Any]' > ``` > > **Returns:** `dict[str, Any]` > > #### collect\_routes > > ```python theme={null} > def collect_routes(self) -> 'dict[RouteSignature, Callable[..., Any]]' > ``` > > **Returns:** `dict[RouteSignature, Callable[Ellipsis, Any]]` > > #### get\_endpoints > > ```python theme={null} > def get_endpoints(cls) -> 'list[str]' > ``` > > **Returns:** `list[str]` > > #### get\_health\_check\_config > > ```python theme={null} > def get_health_check_config(cls) -> 'Optional[ApplicationHealthCheckConfig]' > ``` > > **Returns:** `Optional[ApplicationHealthCheckConfig]` > > #### handle\_exit > > ```python theme={null} > def handle_exit(self) > ``` > > Handle exit signal. > > #### health > > ```python theme={null} > def health(self) > ``` > > #### lifespan > > ```python theme={null} > def lifespan(self, app: 'fastapi.FastAPI') > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `app` | `FastAPI` | - | - | > > #### provide\_hints > > ```python theme={null} > def provide_hints(self) -> 'list[str]' > ``` > > Provide hints for routing the application. > > **Returns:** `list[str]` > > #### run\_local > > ```python theme={null} > def run_local(cls, *args, exposed_port: 'int | None' = None, exposed_metrics_port: 'int | None' = None, **kwargs) > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `args` | - | - | - | > | `exposed_port` | `Optional[int]` | `None` | - | > | `exposed_metrics_port` | `Optional[int]` | `None` | - | > | `kwargs` | - | - | - | > > #### setup > > ```python theme={null} > def setup(self) > ``` > > Setup the application before serving. > > #### spawn > > ```python theme={null} > def spawn(cls) -> 'AppSpawnInfo' > ``` > > **Returns:** `AppSpawnInfo` > > #### teardown > > ```python theme={null} > def teardown(self) > ``` > > Teardown the application after serving. ### HealthCheck ```python theme={null} class fal.HealthCheck ``` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `start_period_seconds` | `Optional[int]` | `None` | Minimum time the runner has been running before considering the runner unhealthy when health check fails. To prevent the health check from failing too early, this will be replaced by startup\_timeout of the application if it's less than it. Defaults to 30. | > | `timeout_seconds` | `Optional[int]` | `None` | Timeout in seconds for the health check request. Defaults to 5 seconds. | > | `failure_threshold` | `Optional[int]` | `None` | Number of consecutive failures before considering the runner as unhealthy. Defaults to 3. | > | `call_regularly` | `Optional[bool]` | `None` | Perform health check every 15s. If false, only do it when the x-fal-runner-health-check header is present. Defaults to True. | > | `method` | `Optional[str]` | `None` | HTTP method to use for the health check request. | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `start_period_seconds` | `Optional[int]` | `None` | - | > | `timeout_seconds` | `Optional[int]` | `None` | - | > | `failure_threshold` | `Optional[int]` | `None` | - | > | `call_regularly` | `Optional[bool]` | `None` | - | > | `method` | `Optional[str]` | `None` | - | ### FalServerlessKeyCredentials ```python theme={null} class fal.FalServerlessKeyCredentials ``` > **Inherits from:** `Credentials` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `key_id` | `str` | - | - | > | `key_secret` | `str` | - | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `key_id` | `str` | - | - | > | `key_secret` | `str` | - | - | > [accordion] Methods > > #### to\_grpc > > ```python theme={null} > def to_grpc(self) -> 'grpc.ChannelCredentials' > ``` > > **Returns:** `ChannelCredentials` > > #### to\_headers > > ```python theme={null} > def to_headers(self) -> 'dict[str, str]' > ``` > > **Returns:** `dict[str, str]` ### ContainerImage ```python theme={null} class fal.ContainerImage ``` ContainerImage represents a Docker image that can be built from a Dockerfile. > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `dockerfile_str` | `str` | - | - | > | `build_args` | `dict[str, str]` | `\` | - | > | `registries` | `dict[str, dict[str, str]]` | `\` | - | > | `builder` | `Optional[Literal[depot, service, worker]]` | `None` | - | > | `compression` | `str` | `'gzip'` | - | > | `force_compression` | `bool` | `False` | - | > | `secrets` | `dict[str, str]` | `\` | - | > | `entrypoint` | `str \| list[str] \| NoneType` | `None` | - | > | `cmd` | `str \| list[str] \| NoneType` | `None` | - | > | `use_isolate` | `Optional[bool]` | `None` | - | > | `context_dir` | `PathLike` | `current directory` | - | > | `dockerignore` | `Optional[list[str]]` | `None` | - | > | `dockerignore_path` | `Optional[PathLike]` | `None` | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `dockerfile_str` | `str` | - | - | > | `build_args` | `dict[str, str]` | - | - | > | `registries` | `dict[str, dict[str, str]]` | - | - | > | `builder` | `Optional[Literal[depot, service, worker]]` | `None` | - | > | `compression` | `str` | `'gzip'` | - | > | `force_compression` | `bool` | `False` | - | > | `secrets` | `dict[str, str]` | - | - | > | `entrypoint` | `str \| list[str] \| NoneType` | `None` | - | > | `cmd` | `str \| list[str] \| NoneType` | `None` | - | > | `use_isolate` | `Optional[bool]` | `None` | - | > | `context_dir` | `PathLike` | `current directory` | - | > | `dockerignore` | `Optional[list[str]]` | `None` | - | > | `dockerignore_path` | `Optional[PathLike]` | `None` | - | > [accordion] Methods > > #### add\_dockerignore > > ```python theme={null} > def add_dockerignore(self, patterns: List[str] | None = None, path: os.PathLike | None = None) -> None > ``` > > Add or update dockerignore patterns. Sets the internal dockerignore patterns using gitignore-style matching. > You can provide either a list of patterns or a path to a .dockerignore file. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `patterns` | `Optional[list[str]]` | `None` | List of gitignore-style patterns | > | `path` | `Optional[PathLike]` | `None` | Path to a .dockerignore file | > > **Returns:** `NoneType` > > **Raises:** > > * `ValueError`: If both patterns and path are provided, or neither > > #### from\_dockerfile > > ```python theme={null} > def from_dockerfile(cls, path: str, **kwargs) -> 'ContainerImage' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `path` | `str` | - | - | > | `kwargs` | - | - | - | > > **Returns:** `ContainerImage` > > #### from\_dockerfile\_str > > ```python theme={null} > def from_dockerfile_str(cls, text: str, **kwargs) -> 'ContainerImage' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `text` | `str` | - | - | > | `kwargs` | - | - | - | > > **Returns:** `ContainerImage` > > #### get\_copy\_add\_sources > > ```python theme={null} > def get_copy_add_sources(self) -> List[str] > ``` > > Get list of src paths/patterns from COPY/ADD commands. This method only parses the Dockerfile - it doesn't access the filesystem. > > **Returns:** `list[str]` > > #### to\_dict > > ```python theme={null} > def to_dict(self) -> dict > ``` > > **Returns:** `dict` *** ## Functions ### function ```python theme={null} def function(kind: 'str' = 'virtualenv', *, host: 'Host | None' = None, local_python_modules: 'list[str] | None' = None, **config: 'Any') ``` | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `kind` | `str` | `'virtualenv'` | - | | `host` | `Optional[Host]` | `None` | - | | `local_python_modules` | `Optional[list[str]]` | `None` | - | | `config` | `Any` | - | - | ### cached ```python theme={null} def cached(func: 'Callable[ArgsT, ReturnT]') -> 'Callable[ArgsT, ReturnT]' ``` Cache the result of the given function in-memory. | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `func` | `Callable[ArgsT, ReturnT]` | - | - | **Returns:** `Callable[ArgsT, ReturnT]` ### endpoint ```python theme={null} def endpoint(path: 'str', *, is_websocket: 'bool' = False, health_check: 'HealthCheck | None' = None) -> 'Callable[[EndpointT], EndpointT]' ``` Designate the decorated function as an application endpoint. | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `path` | `str` | - | - | | `is_websocket` | `bool` | `False` | - | | `health_check` | `Optional[HealthCheck]` | `None` | - | **Returns:** `Callable[EndpointT, EndpointT]` ### realtime ```python theme={null} def realtime(path: 'str', *, buffering: 'int | None' = None, session_timeout: 'float | None' = None, input_modal: 'Any | None' = , output_modal: 'Any | None' = , max_batch_size: 'int' = 1, content_type: 'str' = 'application/msgpack', encode_message: 'Callable[[Any], bytes] | None' = None, decode_message: 'Callable[[bytes], Any] | None' = None) -> 'Callable[[EndpointT], EndpointT]' ``` Designate the decorated function as a realtime application endpoint. | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `path` | `str` | - | - | | `buffering` | `Optional[int]` | `None` | - | | `session_timeout` | `Optional[float]` | `None` | - | | `input_modal` | `Optional[Any]` | `\` | - | | `output_modal` | `Optional[Any]` | `\` | - | | `max_batch_size` | `int` | `1` | - | | `content_type` | `str` | `'application/msgpack'` | - | | `encode_message` | `Optional[Callable[Any, bytes]]` | `None` | - | | `decode_message` | `Optional[Callable[bytes, Any]]` | `None` | - | **Returns:** `Callable[EndpointT, EndpointT]` ### sync\_dir ```python theme={null} def sync_dir(local_dir: 'str | Path', remote_dir: 'str', force_upload=False) -> 'str' ``` | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `local_dir` | `str \| Path` | - | - | | `remote_dir` | `str` | - | - | | `force_upload` | - | `False` | - | **Returns:** `str` # Python SDK Source: https://fal.ai/docs/api-reference/python-sdk/fal-app-reference API reference for the fal Python package The `fal` package provides decorators and utilities for building serverless AI applications. ## Installation ```bash theme={null} pip install fal ``` ## Quick Start ```python theme={null} import fal class MyApp(fal.App): @fal.endpoint("/") def run(self) -> dict: return {"message": "Hello, World!"} ``` Deploy with: ```bash theme={null} fal deploy my_app.py ``` See the [Quick Start guide](/docs/serverless/getting-started/quick-start) for a complete walkthrough. ## API Reference > [card] [fal](/docs/reference/serverless-sdk/fal) > > `App` class, decorators (`endpoint`, `realtime`, `function`, `cached`), `HealthCheck`, `ContainerImage` > [card] [fal.api](/docs/reference/serverless-sdk/fal.api) > > `SyncServerlessClient`: manage apps, runners, keys, secrets, and deploy programmatically > [card] [fal.toolkit](/docs/reference/serverless-sdk/fal.toolkit) > > File types (`Image`, `Video`, `Audio`), `KVStore`, model downloads, GPU utilities > [card] [fal.exceptions](/docs/reference/serverless-sdk/fal.exceptions) > > Exception classes for error handling > [card] [CLI](/docs/reference/cli/installation) > > `fal deploy`, `fal apps`, `fal runners`, `fal keys`, `fal secrets`, and more ## Key Decorators | Decorator | Description | | :- | :- | | `@fal.endpoint(path)` | Define an HTTP endpoint on an App | | `@fal.realtime(path)` | WebSocket endpoint for realtime applications | | `@fal.function(...)` | Create a standalone serverless function | | `@fal.cached` | Cache function results in-memory | See the [fal module reference](/docs/reference/serverless-sdk/fal) for full details. ## App Configuration Configure your app using class variables. See the [full App reference](/docs/reference/serverless-sdk/fal#app) for all options. | Property | Description | | :- | :- | | `machine_type` | GPU type: `"GPU-A100"`, `"GPU-H100"`, or list for fallback (see [Machine Types](/docs/documentation/deployment/machine-types)) | | `requirements` | Pip packages to install (e.g., `["torch>=2.0"]`) | | `requirements_context_dir` | Base directory for resolving local-path requirements such as `.[extra]` or `projects/foo[extra]` | | `num_gpus` | Number of GPUs to allocate | | `min_concurrency` | Minimum warm instances (1+ to avoid cold starts) | | `max_concurrency` | Maximum instances to scale to | | `request_timeout` | Maximum seconds per request | | `startup_timeout` | Maximum seconds for setup | | `app_auth` | Auth mode: `"private"`, `"public"`, or `"shared"` | | `app_files` | Files/directories to include in deployment | | `image` | Custom `ContainerImage` for the application | ## Toolkit Highlights The [fal.toolkit](/docs/reference/serverless-sdk/fal.toolkit) module provides utilities for common tasks: | Utility | Description | | :- | :- | | `Image`, `Video`, `Audio` | File types with automatic CDN upload | | `KVStore` | Persistent key-value storage | | `download_model_weights()` | Download and cache model weights | | `clone_repository()` | Clone git repositories | | `sync_dir()` | Sync local directories to remote storage | | `get_gpu_type()` | Detect current GPU type | ## SyncServerlessClient The [SyncServerlessClient](/docs/reference/serverless-sdk/fal.api#syncserverlessclient) provides programmatic access to fal operations (mirrors the CLI): ```python theme={null} from fal.api import SyncServerlessClient client = SyncServerlessClient() # Manage apps apps = client.apps.list() client.apps.scale("my-app", max_concurrency=10) # Manage runners runners = client.runners.list() client.runners.stop("runner-id") # Manage keys and secrets client.keys.create(scope="admin") client.secrets.set("API_KEY", "value") # Deploy client.deploy("path/to/app.py::MyApp") ``` For detailed guides on building applications, see the [Serverless documentation](/docs/serverless). # fal.distributed Source: https://fal.ai/docs/api-reference/python-sdk/fal-distributed API reference for fal.distributed ```python theme={null} from fal.distributed import DistributedRunner, DistributedWorker ``` ## Classes ### DistributedRunner ```python theme={null} class fal.distributed.DistributedRunner ``` A class to launch and manage distributed workers. > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `worker_cls` | `type[DistributedWorker]` | `\` | - | > | `world_size` | `int` | `1` | - | > | `master_addr` | `str` | `'127.0.0.1'` | - | > | `master_port` | `int` | `29500` | - | > | `worker_addr` | `str` | `'127.0.0.1'` | - | > | `worker_port` | `int` | `54923` | - | > | `timeout` | `int` | `86400` | - | > | `keepalive_payload` | `dict[str, Any]` | `\{\}` | - | > | `keepalive_interval` | `int \| float \| NoneType` | `None` | - | > | `cwd` | `str \| Path \| NoneType` | `None` | - | > | `set_device` | `Optional[bool]` | `None` | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `zmq_socket` | `Optional[Socket[Any]]` | - | - | > | `context` | `Optional[mp.ProcessContext]` | - | - | > | `keepalive_timer` | `Optional[KeepAliveTimer]` | - | - | > [accordion] Methods > > #### close\_zmq\_socket > > ```python theme={null} > def close_zmq_socket(self) -> 'None' > ``` > > Closes the ZeroMQ socket. > > **Returns:** `NoneType` > > #### ensure\_alive > > ```python theme={null} > def ensure_alive(self) -> 'None' > ``` > > Ensures that the distributed worker processes are alive. If the processes are not alive, it raises an error. > > **Returns:** `NoneType` > > #### gather\_errors > > ```python theme={null} > def gather_errors(self) -> 'list[Exception]' > ``` > > Gathers errors from the distributed worker processes. This method should be called to collect any errors that occurred > during execution. > > **Returns:** `list[Exception]` > > #### get\_zmq\_socket > > ```python theme={null} > def get_zmq_socket(self) -> 'Socket[Any]' > ``` > > Returns a ZeroMQ socket of the specified type. > > **Returns:** `A ZeroMQ socket.` > > #### invoke > > ```python theme={null} > async def invoke(self, payload: 'dict[str, Any]' = {}, timeout: 'Optional[int]' = None) -> 'Any' > ``` > > Invokes the distributed worker with the given payload. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `payload` | `dict[str, Any]` | `\{\}` | The payload to send to the worker. | > | `timeout` | `Optional[int]` | `None` | The timeout for the overall operation. | > > **Returns:** `Any` > > #### is\_alive > > ```python theme={null} > def is_alive(self) -> 'bool' > ``` > > Check if the distributed worker processes are alive. > > **Returns:** `bool` > > #### keepalive > > ```python theme={null} > def keepalive(self, timeout: 'Optional[Union[int, float]]' = 60.0) -> 'None' > ``` > > Sends the keepalive payload to the worker. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `timeout` | `int \| float \| NoneType` | `60.0` | - | > > **Returns:** `NoneType` > > #### maybe\_cancel\_keepalive > > ```python theme={null} > def maybe_cancel_keepalive(self) -> 'None' > ``` > > Cancels the keepalive timer if it is set. > > **Returns:** `NoneType` > > #### maybe\_reset\_keepalive > > ```python theme={null} > def maybe_reset_keepalive(self) -> 'None' > ``` > > Resets the keepalive timer if it is set. > > **Returns:** `NoneType` > > #### maybe\_start\_keepalive > > ```python theme={null} > def maybe_start_keepalive(self) -> 'None' > ``` > > Starts the keepalive timer if it is set. > > **Returns:** `NoneType` > > #### run > > ```python theme={null} > def run(self, **kwargs: 'Any') -> 'None' > ``` > > The main function to run the distributed worker. This function is called by each worker process spawned by > `torch.multiprocessing.spawn`. This method must be synchronous. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `kwargs` | `Any` | - | The arguments to pass to the worker. | > > **Returns:** `NoneType` > > #### start > > ```python theme={null} > async def start(self, timeout: 'int' = 1800, **kwargs: 'Any') -> 'None' > ``` > > Starts the distributed worker processes. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `timeout` | `int` | `1800` | The timeout for the distributed processes. | > | `kwargs` | `Any` | - | - | > > **Returns:** `NoneType` > > #### stop > > ```python theme={null} > async def stop(self, timeout: 'int' = 10) -> 'None' > ``` > > Stops the distributed worker processes. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `timeout` | `int` | `10` | The timeout for the distributed processes to stop. | > > **Returns:** `NoneType` > > #### stream > > ```python theme={null} > def stream(self, payload: 'dict[str, Any]' = {}, timeout: 'Optional[int]' = None, streaming_timeout: 'Optional[int]' = None, as_text_events: 'bool' = False) -> 'AsyncIterator[Any]' > ``` > > Streams the result from the distributed worker. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `payload` | `dict[str, Any]` | `\{\}` | The payload to send to the worker. | > | `timeout` | `Optional[int]` | `None` | The timeout for the overall operation. | > | `streaming_timeout` | `Optional[int]` | `None` | The timeout in-between streamed results. | > | `as_text_events` | `bool` | `False` | Whether to yield results as text events. | > > **Returns:** `AsyncIterator[Any]` > > #### terminate > > ```python theme={null} > def terminate(self, timeout: 'Union[int, float]' = 10) -> 'None' > ``` > > Terminates the distributed worker processes. This method should be called to clean up the worker processes. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `timeout` | `int \| float` | `10` | - | > > **Returns:** `NoneType` ### DistributedWorker ```python theme={null} class fal.distributed.DistributedWorker ``` A base class for distributed workers. > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `rank` | `int` | `0` | - | > | `world_size` | `int` | `1` | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `queue` | `queue.Queue[bytes]` | - | - | > | `loop` | `asyncio.AbstractEventLoop` | - | - | > | `thread` | `threading.Thread` | - | - | > [accordion] Properties > > | Name | Type | Description | > | :- | :- | :- | > | `device` | - | The device for the current worker | > | `running` | `bool` | Whether the event loop is running | > [accordion] Methods > > #### add\_streaming\_error > > ```python theme={null} > def add_streaming_error(self, error: 'Exception') -> 'None' > ``` > > Add an error to the queue. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `error` | `Exception` | - | The error to add to the queue. | > > **Returns:** `NoneType` > > #### add\_streaming\_result > > ```python theme={null} > def add_streaming_result(self, result: 'Any', image_format: 'str' = 'jpeg', as_text_event: 'bool' = False) -> 'None' > ``` > > Add a streaming result to the queue. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `result` | `Any` | - | The result to add to the queue. | > | `image_format` | `str` | `'jpeg'` | - | > | `as_text_event` | `bool` | `False` | - | > > **Returns:** `NoneType` > > #### initialize > > ```python theme={null} > def initialize(self, **kwargs: 'Any') -> 'None' > ``` > > Initialize the worker. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `kwargs` | `Any` | - | - | > > **Returns:** `NoneType` > > #### rank\_print > > ```python theme={null} > def rank_print(self, message: 'str', debug: 'bool' = False) -> 'None' > ``` > > Print a message with the rank of the current worker. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `message` | `str` | - | The message to print. | > | `debug` | `bool` | `False` | Whether to print the message as a debug message. | > > **Returns:** `NoneType` > > #### run\_in\_worker > > ```python theme={null} > def run_in_worker(self, func: 'Callable[..., Any]', *args: 'Any', **kwargs: 'Any') -> 'Future[Any]' > ``` > > Run a function in the worker. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `func` | `Callable[Ellipsis, Any]` | - | - | > | `args` | `Any` | - | - | > | `kwargs` | `Any` | - | - | > > **Returns:** `Future[Any]` > > #### setup > > ```python theme={null} > def setup(self, **kwargs: 'Any') -> 'None' > ``` > > Override this method to set up the worker. This method is called once per worker. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `kwargs` | `Any` | - | - | > > **Returns:** `NoneType` > > #### shutdown > > ```python theme={null} > def shutdown(self, timeout: 'Optional[Union[int, float]]' = None) -> 'None' > ``` > > Shutdown the event loop. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `timeout` | `int \| float \| NoneType` | `None` | The timeout for the shutdown. | > > **Returns:** `NoneType` > > #### submit > > ```python theme={null} > def submit(self, coro: 'Coroutine[Any, Any, Any]') -> 'Future[Any]' > ``` > > Submit a coroutine to the event loop. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `coro` | `Coroutine[Any, Any, Any]` | - | The coroutine to submit to the event loop. | > > **Returns:** `Future[Any]` > > #### teardown > > ```python theme={null} > def teardown(self) -> 'None' > ``` > > Override this method to tear down the worker. This method is called once per worker. > > **Returns:** `NoneType` # fal.exceptions Source: https://fal.ai/docs/api-reference/python-sdk/fal-exceptions API reference for fal.exceptions ```python theme={null} from fal.exceptions import ( FalServerlessException, AppException, FieldException, RequestCancelledException, FileTooLargeError, AppFileUploadException, GPUException, GPUOutOfMemoryException, CUDAOutOfMemoryException, UnauthenticatedException, catch_gpu_exceptions, ) ``` ## Classes ### FalServerlessException ```python theme={null} class fal.exceptions.FalServerlessException ``` Base exception type for fal Serverless related flows and APIs. > **Inherits from:** `Exception` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `args` | - | - | - | > | `kwargs` | - | - | - | ### AppException ```python theme={null} class fal.exceptions.AppException ``` Base exception class for application-specific errors. > **Inherits from:** `FalServerlessException` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `message` | `str` | - | A descriptive message explaining the error. | > | `status_code` | `int` | - | The HTTP status code associated with the error. | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `message` | `str` | - | A descriptive message explaining the error. | > | `status_code` | `int` | - | The HTTP status code associated with the error. | ### FieldException ```python theme={null} class fal.exceptions.FieldException ``` Exception raised for errors related to specific fields. > **Inherits from:** `FalServerlessException` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `field` | `str` | - | The field that caused the error. | > | `message` | `str` | - | A descriptive message explaining the error. | > | `status_code` | `int` | `422` | The HTTP status code associated with the error. Defaults to 422 | > | `type` | `str` | `'value_error'` | The type of error. Defaults to "value\_error" | > | `billable_units` | `int \| float \| str \| NoneType` | `0` | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `field` | `str` | - | The field that caused the error. | > | `message` | `str` | - | A descriptive message explaining the error. | > | `status_code` | `int` | `422` | The HTTP status code associated with the error. Defaults to 422 | > | `type` | `str` | `'value_error'` | The type of error. Defaults to "value\_error" | > | `billable_units` | `int \| float \| str \| None` | `0` | - | > [accordion] Methods > > #### to\_pydantic\_format > > ```python theme={null} > def to_pydantic_format(self) -> 'dict[str, list[dict]]' > ``` > > **Returns:** `dict[str, list[dict]]` ### RequestCancelledException ```python theme={null} class fal.exceptions.RequestCancelledException ``` Exception raised when the request is cancelled by the client. > **Inherits from:** `FalServerlessException` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `message` | `str` | `'Request cancelled by the client.'` | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `message` | `str` | `'Request cancelled by the client.'` | - | ### FileTooLargeError ```python theme={null} class fal.exceptions.FileTooLargeError ``` Exception raised when the file is too large. > **Inherits from:** `FalServerlessException` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `message` | `str` | `'File is too large.'` | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `message` | `str` | `'File is too large.'` | - | ### AppFileUploadException ```python theme={null} class fal.exceptions.AppFileUploadException ``` Raised when file upload fails > **Inherits from:** `FalServerlessException` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `message` | `str` | - | - | > | `relative_path` | `str` | - | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `message` | `str` | - | - | > | `relative_path` | `str` | - | - | ### GPUException ```python theme={null} class fal.exceptions.GPUException ``` Base exception for GPU-related errors. > **Inherits from:** `AppException` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `message` | `str` | `'GPU error'` | - | > | `status_code` | `int` | `503` | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `message` | `str` | `'GPU error'` | - | > | `status_code` | `int` | `503` | - | ### GPUOutOfMemoryException ```python theme={null} class fal.exceptions.GPUOutOfMemoryException ``` Exception raised when a GPU operation runs out of memory. > **Inherits from:** `GPUException` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `message` | `str` | `'GPU error'` | - | > | `status_code` | `int` | `503` | - | ### CUDAOutOfMemoryException ```python theme={null} class fal.exceptions.CUDAOutOfMemoryException ``` Exception raised when a CUDA operation runs out of memory. > **Inherits from:** `GPUOutOfMemoryException` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `message` | `str` | `'CUDA error: out of memory'` | - | > | `status_code` | `int` | `503` | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `message` | `str` | `'CUDA error: out of memory'` | - | ### UnauthenticatedException ```python theme={null} class fal.exceptions.UnauthenticatedException ``` Base exception type for fal Serverless related flows and APIs. > **Inherits from:** `FalServerlessException` ### catch\_gpu\_exceptions ```python theme={null} class fal.exceptions.catch_gpu_exceptions ``` Catch GPU/CUDA exceptions and convert them to HTTP 503 responses. Works as both a context manager and a decorator. Any caught GPU exception (CUDA OOM, cuDNN errors, NVML failures, etc.) is re-raised as a GPU exception with HTTP status 503. **Example:** ```python theme={null} from fal.exceptions import catch_gpu_exceptions with catch_gpu_exceptions(): run_inference() @catch_gpu_exceptions() def run_inference(): ... ``` > **Inherits from:** `ContextDecorator` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `args` | - | - | - | > | `kwargs` | - | - | - | # fal.toolkit Source: https://fal.ai/docs/api-reference/python-sdk/fal-toolkit API reference for fal.toolkit ```python theme={null} from fal.toolkit import ( Audio, CompressedFile, FalBaseModel, File, Image, ImageSizeConstraints, ImageValidationConfig, ImageValidationOptions, KVStore, Video, FalTookitException, FileUploadException, KVStoreException, DownloadError, to_xfal, Hidden, get_image_size, clone_repository, download_file, download_model_weights, get_gpu_type, load_inductor_cache, sync_inductor_cache, synchronized_inductor_cache, ) ``` ## Classes ### Audio ```python theme={null} class fal.toolkit.Audio ``` !!! abstract "Usage Documentation" [Models](../concepts/models.md) A base class for creating Pydantic models. > **Inherits from:** `File` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `data` | `Any` | - | - | ### CompressedFile ```python theme={null} class fal.toolkit.CompressedFile ``` !!! abstract "Usage Documentation" [Models](../concepts/models.md) A base class for creating Pydantic models. > **Inherits from:** `File` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `data` | `Any` | - | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `extract_dir` | `Optional[str]` | - | - | > [accordion] Methods > > #### glob > > ```python theme={null} > def glob(self, pattern: 'str') > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `pattern` | `str` | - | - | ### FalBaseModel ```python theme={null} class fal.toolkit.FalBaseModel ``` Base model for fal applications with field ordering, visibility control, and context binding for error reporting. Features: * FIELD\_ORDERS: Control field order in JSON schema, useful for nested models. * Hidden(Field(...)): Mark fields as hidden from OpenAPI schema, useful for hidden params. **Example:** ```python theme={null} from fal.toolkit.pydantic import FalBaseModel, Field, Hidden class Input(FalBaseModel): FIELD_ORDERS = ["prompt", "image_url"] prompt: str = Field(description="Text prompt") image_url: str = Field(description="Image URL") debug_mode: bool = Hidden(Field(default=False)) ``` > **Inherits from:** `BaseModel` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `data` | `Any` | - | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `SCHEMA_IGNORES` | `ClassVar[Set[str]]` | `set()` | - | > | `FIELD_ORDERS` | `ClassVar[List[str]]` | `[]` | - | ### File ```python theme={null} class fal.toolkit.File ``` !!! abstract "Usage Documentation" [Models](../concepts/models.md) A base class for creating Pydantic models. > **Inherits from:** `BaseModel` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `data` | `Any` | - | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `url` | `str` | - | - | > | `content_type` | `Optional[str]` | - | - | > | `file_name` | `Optional[str]` | - | - | > | `file_size` | `Optional[int]` | - | - | > | `file_data` | `Optional[bytes]` | - | - | > [accordion] Methods > > #### as\_bytes > > ```python theme={null} > def as_bytes(self) -> 'bytes' > ``` > > **Returns:** `bytes` > > #### from\_bytes > > ```python theme={null} > def from_bytes(cls, data: 'bytes', content_type: 'Optional[str]' = None, file_name: 'Optional[str]' = None, repository: 'FileRepository | RepositoryId' = 'fal_v3', fallback_repository: 'Optional[FileRepository | RepositoryId | list[FileRepository | RepositoryId]]' = ['fal'], request: 'Optional[Request]' = None, save_kwargs: 'Optional[dict]' = None, fallback_save_kwargs: 'Optional[dict]' = None) -> 'File' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `data` | `bytes` | - | - | > | `content_type` | `Optional[str]` | `None` | - | > | `file_name` | `Optional[str]` | `None` | - | > | `repository` | `FileRepository \| Literal[fal, fal_v2, fal_v3, in_memory, gcp_storage, r2, cdn]` | `'fal_v3'` | - | > | `fallback_repository` | `FileRepository \| Literal[fal, fal_v2, fal_v3, in_memory, gcp_storage, r2, cdn] \| list[FileRepository \| Literal[fal, fal_v2, fal_v3, in_memory, gcp_storage, r2, cdn]] \| NoneType` | `['fal']` | - | > | `request` | `Optional[Request]` | `None` | - | > | `save_kwargs` | `Optional[dict]` | `None` | - | > | `fallback_save_kwargs` | `Optional[dict]` | `None` | - | > > **Returns:** `File` > > #### from\_bytes\_async > > ```python theme={null} > async def from_bytes_async(cls, data: 'bytes', content_type: 'Optional[str]' = None, file_name: 'Optional[str]' = None, repository: 'FileRepository | RepositoryId' = 'fal_v3', fallback_repository: 'Optional[FileRepository | RepositoryId | list[FileRepository | RepositoryId]]' = ['fal'], request: 'Optional[Request]' = None, save_kwargs: 'Optional[dict]' = None, fallback_save_kwargs: 'Optional[dict]' = None) -> 'File' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `data` | `bytes` | - | - | > | `content_type` | `Optional[str]` | `None` | - | > | `file_name` | `Optional[str]` | `None` | - | > | `repository` | `FileRepository \| Literal[fal, fal_v2, fal_v3, in_memory, gcp_storage, r2, cdn]` | `'fal_v3'` | - | > | `fallback_repository` | `FileRepository \| Literal[fal, fal_v2, fal_v3, in_memory, gcp_storage, r2, cdn] \| list[FileRepository \| Literal[fal, fal_v2, fal_v3, in_memory, gcp_storage, r2, cdn]] \| NoneType` | `['fal']` | - | > | `request` | `Optional[Request]` | `None` | - | > | `save_kwargs` | `Optional[dict]` | `None` | - | > | `fallback_save_kwargs` | `Optional[dict]` | `None` | - | > > **Returns:** `File` > > #### from\_path > > ```python theme={null} > def from_path(cls, path: 'str | Path', content_type: 'Optional[str]' = None, repository: 'FileRepository | RepositoryId' = 'fal_v3', multipart: 'bool | None' = None, fallback_repository: 'Optional[FileRepository | RepositoryId | list[FileRepository | RepositoryId]]' = ['fal'], request: 'Optional[Request]' = None, save_kwargs: 'Optional[dict]' = None, fallback_save_kwargs: 'Optional[dict]' = None) -> 'File' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `path` | `str \| Path` | - | - | > | `content_type` | `Optional[str]` | `None` | - | > | `repository` | `FileRepository \| Literal[fal, fal_v2, fal_v3, in_memory, gcp_storage, r2, cdn]` | `'fal_v3'` | - | > | `multipart` | `Optional[bool]` | `None` | - | > | `fallback_repository` | `FileRepository \| Literal[fal, fal_v2, fal_v3, in_memory, gcp_storage, r2, cdn] \| list[FileRepository \| Literal[fal, fal_v2, fal_v3, in_memory, gcp_storage, r2, cdn]] \| NoneType` | `['fal']` | - | > | `request` | `Optional[Request]` | `None` | - | > | `save_kwargs` | `Optional[dict]` | `None` | - | > | `fallback_save_kwargs` | `Optional[dict]` | `None` | - | > > **Returns:** `File` > > #### from\_path\_async > > ```python theme={null} > async def from_path_async(cls, path: 'str | Path', content_type: 'Optional[str]' = None, repository: 'FileRepository | RepositoryId' = 'fal_v3', multipart: 'bool | None' = None, fallback_repository: 'Optional[FileRepository | RepositoryId | list[FileRepository | RepositoryId]]' = ['fal'], request: 'Optional[Request]' = None, save_kwargs: 'Optional[dict]' = None, fallback_save_kwargs: 'Optional[dict]' = None) -> 'File' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `path` | `str \| Path` | - | - | > | `content_type` | `Optional[str]` | `None` | - | > | `repository` | `FileRepository \| Literal[fal, fal_v2, fal_v3, in_memory, gcp_storage, r2, cdn]` | `'fal_v3'` | - | > | `multipart` | `Optional[bool]` | `None` | - | > | `fallback_repository` | `FileRepository \| Literal[fal, fal_v2, fal_v3, in_memory, gcp_storage, r2, cdn] \| list[FileRepository \| Literal[fal, fal_v2, fal_v3, in_memory, gcp_storage, r2, cdn]] \| NoneType` | `['fal']` | - | > | `request` | `Optional[Request]` | `None` | - | > | `save_kwargs` | `Optional[dict]` | `None` | - | > | `fallback_save_kwargs` | `Optional[dict]` | `None` | - | > > **Returns:** `File` > > #### save > > ```python theme={null} > def save(self, path: 'str | Path', overwrite: 'bool' = False) -> 'Path' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `path` | `str \| Path` | - | - | > | `overwrite` | `bool` | `False` | - | > > **Returns:** `Path` > > #### save\_async > > ```python theme={null} > async def save_async(self, path: 'str | Path', overwrite: 'bool' = False) -> 'Path' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `path` | `str \| Path` | - | - | > | `overwrite` | `bool` | `False` | - | > > **Returns:** `Path` ### Image ```python theme={null} class fal.toolkit.Image ``` Represents an image file. > **Inherits from:** `File` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `data` | `Any` | - | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `width` | `Optional[int]` | - | - | > | `height` | `Optional[int]` | - | - | > [accordion] Methods > > #### from\_bytes > > ```python theme={null} > def from_bytes(cls, data: 'bytes', format: 'ImageFormat', size: 'ImageSize | None' = None, file_name: 'str | None' = None, repository: 'FileRepository | RepositoryId' = 'fal_v3', fallback_repository: 'Optional[FileRepository | RepositoryId | list[FileRepository | RepositoryId]]' = ['fal'], request: 'Optional[Request]' = None, save_kwargs: 'Optional[dict]' = None, fallback_save_kwargs: 'Optional[dict]' = None) -> 'Image' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `data` | `bytes` | - | - | > | `format` | `Literal[png, jpeg, jpg, webp, gif]` | - | - | > | `size` | `Optional[ImageSize]` | `None` | - | > | `file_name` | `Optional[str]` | `None` | - | > | `repository` | `FileRepository \| Literal[fal, fal_v2, fal_v3, in_memory, gcp_storage, r2, cdn]` | `'fal_v3'` | - | > | `fallback_repository` | `FileRepository \| Literal[fal, fal_v2, fal_v3, in_memory, gcp_storage, r2, cdn] \| list[FileRepository \| Literal[fal, fal_v2, fal_v3, in_memory, gcp_storage, r2, cdn]] \| NoneType` | `['fal']` | - | > | `request` | `Optional[Request]` | `None` | - | > | `save_kwargs` | `Optional[dict]` | `None` | - | > | `fallback_save_kwargs` | `Optional[dict]` | `None` | - | > > **Returns:** `Image` > > #### from\_pil > > ```python theme={null} > def from_pil(cls, pil_image: 'PILImage.Image', format: 'ImageFormat | None' = None, file_name: 'str | None' = None, repository: 'FileRepository | RepositoryId' = 'fal_v3', fallback_repository: 'Optional[FileRepository | RepositoryId | list[FileRepository | RepositoryId]]' = ['fal'], request: 'Optional[Request]' = None, save_kwargs: 'Optional[dict]' = None, fallback_save_kwargs: 'Optional[dict]' = None) -> 'Image' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `pil_image` | `PILImage.Image` | - | - | > | `format` | `ImageFormat \| None` | `None` | - | > | `file_name` | `str \| None` | `None` | - | > | `repository` | `FileRepository \| RepositoryId` | `'fal_v3'` | - | > | `fallback_repository` | `Optional[FileRepository \| RepositoryId \| list[FileRepository \| RepositoryId]]` | `['fal']` | - | > | `request` | `Optional[Request]` | `None` | - | > | `save_kwargs` | `Optional[dict]` | `None` | - | > | `fallback_save_kwargs` | `Optional[dict]` | `None` | - | > > #### to\_pil > > ```python theme={null} > def to_pil(self, mode: 'str' = 'RGB') -> 'PILImage.Image' > ``` > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `mode` | `str` | `'RGB'` | - | ### ImageSizeConstraints ```python theme={null} class fal.toolkit.ImageSizeConstraints ``` Advisory limits on the image size a model can generate. Attach to an `image_size` field via :func:`fal.toolkit.ImageSizeField` to surface the model's size envelope in the OpenAPI schema (under the `x-fal` extension), so clients and UIs can validate sizes before a request. These are documentation hints and are not enforced by the SDK. > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `min_width` | `Optional[int]` | `None` | - | > | `min_height` | `Optional[int]` | `None` | - | > | `max_width` | `Optional[int]` | `None` | - | > | `max_height` | `Optional[int]` | `None` | - | > | `min_area` | `Optional[int]` | `None` | - | > | `max_area` | `Optional[int]` | `None` | - | > | `multiple_of` | `Optional[int]` | `None` | - | > | `min_aspect_ratio` | `Optional[float]` | `None` | - | > | `max_aspect_ratio` | `Optional[float]` | `None` | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `min_width` | `Optional[int]` | `None` | - | > | `min_height` | `Optional[int]` | `None` | - | > | `max_width` | `Optional[int]` | `None` | - | > | `max_height` | `Optional[int]` | `None` | - | > | `min_area` | `Optional[int]` | `None` | - | > | `max_area` | `Optional[int]` | `None` | - | > | `multiple_of` | `Optional[int]` | `None` | - | > | `min_aspect_ratio` | `Optional[float]` | `None` | - | > | `max_aspect_ratio` | `Optional[float]` | `None` | - | ### ImageValidationConfig ```python theme={null} class fal.toolkit.ImageValidationConfig ``` Limits applied to an input image. Surfaced in the schema (`x-fal`); the SDK does not enforce them. > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `max_file_size` | `Optional[int]` | `None` | - | > | `min_width` | `Optional[int]` | `None` | - | > | `min_height` | `Optional[int]` | `None` | - | > | `max_width` | `Optional[int]` | `None` | - | > | `max_height` | `Optional[int]` | `None` | - | > | `min_aspect_ratio` | `Optional[float]` | `None` | - | > | `max_aspect_ratio` | `Optional[float]` | `None` | - | > | `timeout` | `float` | `20.0` | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `max_file_size` | `Optional[int]` | `None` | - | > | `min_width` | `Optional[int]` | `None` | - | > | `min_height` | `Optional[int]` | `None` | - | > | `max_width` | `Optional[int]` | `None` | - | > | `max_height` | `Optional[int]` | `None` | - | > | `min_aspect_ratio` | `Optional[float]` | `None` | - | > | `max_aspect_ratio` | `Optional[float]` | `None` | - | > | `timeout` | `float` | `20.0` | - | ### ImageValidationOptions ```python theme={null} class fal.toolkit.ImageValidationOptions ``` Validation options accepted by input-image helpers. > **Inherits from:** `dict` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `args` | - | - | - | > | `kwargs` | - | - | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `max_file_size` | `ForwardRef('Optional[int]', module='fal.toolkit.constraints', owner=fal.toolkit.constraints.ImageValidationOptions)` | - | - | > | `min_width` | `ForwardRef('Optional[int]', module='fal.toolkit.constraints', owner=fal.toolkit.constraints.ImageValidationOptions)` | - | - | > | `min_height` | `ForwardRef('Optional[int]', module='fal.toolkit.constraints', owner=fal.toolkit.constraints.ImageValidationOptions)` | - | - | > | `max_width` | `ForwardRef('Optional[int]', module='fal.toolkit.constraints', owner=fal.toolkit.constraints.ImageValidationOptions)` | - | - | > | `max_height` | `ForwardRef('Optional[int]', module='fal.toolkit.constraints', owner=fal.toolkit.constraints.ImageValidationOptions)` | - | - | > | `min_aspect_ratio` | `ForwardRef('Optional[float]', module='fal.toolkit.constraints', owner=fal.toolkit.constraints.ImageValidationOptions)` | - | - | > | `max_aspect_ratio` | `ForwardRef('Optional[float]', module='fal.toolkit.constraints', owner=fal.toolkit.constraints.ImageValidationOptions)` | - | - | > | `timeout` | `ForwardRef('Optional[float]', module='fal.toolkit.constraints', owner=fal.toolkit.constraints.ImageValidationOptions)` | - | - | ### KVStore ```python theme={null} class fal.toolkit.KVStore ``` A key-value store client for interacting with the FAL KV service. > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `db_name` | `str` | - | The name of the database/namespace to use for this KV store. | > [accordion] Properties > > | Name | Type | Description | > | :- | :- | :- | > | `auth_headers` | `dict[str, str]` | - | > [accordion] Methods > > #### delete > > ```python theme={null} > def delete(self, key: str) -> None > ``` > > Delete a value from the key-value store. The operation is idempotent and succeeds whether or not the key > existed. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `key` | `str` | - | The key to delete. | > > **Returns:** `NoneType` > > #### get > > ```python theme={null} > def get(self, key: str) -> str | None > ``` > > Retrieve a value from the key-value store. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `key` | `str` | - | The key to retrieve the value for. | > > **Returns:** `Optional[str]` > > #### set > > ```python theme={null} > def set(self, key: str, value: str, ttl: int | None = None) -> None > ``` > > Store a value in the key-value store. > > | Parameter | Type | Default | Description | > | :- | :- | :- | :- | > | `key` | `str` | - | The key to store the value under. | > | `value` | `str` | - | The value to store. | > | `ttl` | `Optional[int]` | `None` | Optional time-to-live in seconds. Must be between 60 and 2592000 (30 days). Defaults to 30 days when omitted. | > > **Returns:** `NoneType` ### Video ```python theme={null} class fal.toolkit.Video ``` !!! abstract "Usage Documentation" [Models](../concepts/models.md) A base class for creating Pydantic models. > **Inherits from:** `File` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `data` | `Any` | - | - | ### FalTookitException ```python theme={null} class fal.toolkit.FalTookitException ``` Base exception for all toolkit exceptions > **Inherits from:** `Exception` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `args` | - | - | - | > | `kwargs` | - | - | - | ### FileUploadException ```python theme={null} class fal.toolkit.FileUploadException ``` Raised when file upload fails > **Inherits from:** `FalTookitException` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `args` | - | - | - | > | `kwargs` | - | - | - | ### KVStoreException ```python theme={null} class fal.toolkit.KVStoreException ``` Raised when KV store operation fails > **Inherits from:** `FalTookitException` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `args` | - | - | - | > | `kwargs` | - | - | - | ### DownloadError ```python theme={null} class fal.toolkit.DownloadError ``` Common base class for all non-exit exceptions. > **Inherits from:** `Exception` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `args` | - | - | - | > | `kwargs` | - | - | - | *** ## Functions ### to\_xfal ```python theme={null} def to_xfal(config: 'ImageSizeConstraints | ImageValidationConfig') -> 'dict[str, Any]' ``` Return a config's set (non-None) limits as the `x-fal` schema payload. | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `config` | `ImageSizeConstraints \| ImageValidationConfig` | - | - | **Returns:** `dict[str, Any]` ### Hidden ```python theme={null} def Hidden(field: '_T') -> '_T' ``` Wrapper that marks a Field as hidden in the UI. The field MUST have a default or default\_factory set since hidden fields cannot be required inputs in the UI. Usage: class Input(FalBaseModel): prompt: str = Field(...) hidden\_flag: bool = Hidden(Field(default=False)) | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `field` | `_T` | - | A pydantic FieldInfo instance (result of Field(...)) | **Returns:** `_T` **Raises:** * `ValueError`: If field has no default or default\_factory ### get\_image\_size ```python theme={null} def get_image_size(source: 'ImageSizeInput') -> 'ImageSize' ``` | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `source` | `ImageSize \| Literal[square_hd, square, portrait_4_3, portrait_16_9, landscape_4_3, landscape_16_9]` | - | - | **Returns:** `ImageSize` ### clone\_repository ```python theme={null} def clone_repository(https_url: 'str', *, commit_hash: 'str | None' = None, target_dir: 'str | Path | None' = None, repo_name: 'str | None' = None, force: 'bool' = False, include_to_path: 'bool' = False) -> 'Path' ``` Clones a Git repository from the specified HTTPS URL into a local directory. This function clones a Git repository from the specified HTTPS URL into a local directory. It can also checkout a specific commit if the `commit_hash` is provided. If a custom `target_dir` or `repo_name` is not specified, a predefined directory is used for the target directory, and the repository name is determined from the URL. | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `https_url` | `str` | - | The HTTPS URL of the Git repository to be cloned. | | `commit_hash` | `Optional[str]` | `None` | The commit hash to checkout after cloning. | | `target_dir` | `str \| Path \| NoneType` | `None` | The directory where the repository will be saved. If not provided, a predefined directory is used. | | `repo_name` | `Optional[str]` | `None` | The name to be used for the cloned repository directory. If not provided, the repository's name from the URL is used. | | `force` | `bool` | `False` | If `True`, the repository is cloned even if it already exists locally and its commit hash matches the provided commit hash. Defaults to `False`. | | `include_to_path` | `bool` | `False` | If `True`, the cloned repository is added to the `sys.path`. Defaults to `False`. | **Returns:** `Path` ### download\_file ```python theme={null} def download_file(url: 'str', target_dir: 'str | Path', *, force: 'bool' = False, request_headers: 'dict[str, str] | None' = None, filesize_limit: 'int | None' = None) -> 'Path' ``` Downloads a file from the specified URL to the target directory. The function downloads the file from the given URL and saves it in the specified target directory, provided it is below the given filesize limit. If the downloaded response resolves to an existing local file whose content length matches the downloaded file, the existing file is kept. If the file needs to be downloaded or if an existing file's content length does not match the expected length, the function proceeds to download and save the file. It ensures that the target directory exists and handles any errors that may occur during the download process, raising a `DownloadError` if necessary. | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `url` | `str` | - | The URL of the file to be downloaded. | | `target_dir` | `str \| Path` | - | The directory where the downloaded file will be saved. If it's not an absolute path, it's treated as a relative directory to "/data". | | `force` | `bool` | `False` | If `True`, the file is downloaded even if it already exists locally and its content length matches the downloaded response. Defaults to `False`. | | `request_headers` | `Optional[dict[str, str]]` | `None` | A dictionary containing additional headers to be included in the HTTP request. Defaults to `None`. | | `filesize_limit` | `Optional[int]` | `None` | An integer specifying the maximum downloadable size, in megabytes. Defaults to `None`. | **Returns:** `Path` **Raises:** * `DownloadError`: If an error occurs during the download process. ### download\_model\_weights ```python theme={null} def download_model_weights(url: 'str', force: 'bool' = False, request_headers: 'dict[str, str] | None' = None) -> 'Path' ``` Downloads model weights from the specified URL and saves them to a predefined directory. This function is specifically designed for downloading model weights and stores them in a predefined directory. It calls the `download_file` function with the provided URL and the target directory set to a pre-defined location for model weights. The downloaded model weights are saved in this directory, and the function returns the full path to the downloaded weights file. | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `url` | `str` | - | The URL from which the model weights will be downloaded. | | `force` | `bool` | `False` | If `True`, the model weights are downloaded even if they already exist locally and their content length matches the expected content length from the remote file. Defaults to `False`. | | `request_headers` | `Optional[dict[str, str]]` | `None` | A dictionary containing additional headers to be included in the HTTP request. Defaults to `None`. | **Returns:** `Path` ### get\_gpu\_type ```python theme={null} def get_gpu_type() -> 'str' ``` Detect the GPU type using nvidia-smi. **Example:** ```python theme={null} >>> gpu_type = get_gpu_type() >>> print(f"Running on: {gpu_type}") Running on: H100 ``` **Returns:** `str` ### load\_inductor\_cache ```python theme={null} def load_inductor_cache(cache_key: 'str') -> 'str' ``` Load PyTorch Inductor compilation cache from global storage. This function: 1. Sets TORCHINDUCTOR\_CACHE\_DIR environment variable 2. Looks for cached compiled kernels in GPU-specific global storage 3. Unpacks the cache to local temporary directory 4. Returns a hash of the unpacked directory for change detection **Example:** ```python theme={null} >>> dir_hash = load_inductor_cache("flux/2") Found compilation cache at /data/inductor-caches/H100/flux/2.zip, unpacking... Cache unpacked successfully. ``` | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `cache_key` | `str` | - | Unique identifier for this cache (e.g., "flux/2", "mymodel/v1") | **Returns:** `str` ### sync\_inductor\_cache ```python theme={null} def sync_inductor_cache(cache_key: 'str', unpacked_dir_hash: 'str') -> 'None' ``` Sync updated PyTorch Inductor cache back to global storage. This function: 1. Checks if the local cache has changed (by comparing hashes) 2. If changed, creates a zip archive of the new cache 3. Saves it to GPU-specific global storage **Example:** ```python theme={null} >>> sync_inductor_cache("flux/2", dir_hash) No changes in the cache dir, skipping sync. # or Changes detected in the cache dir, syncing... ``` | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `cache_key` | `str` | - | Unique identifier for this cache (same as used in load\_inductor\_cache) | | `unpacked_dir_hash` | `str` | - | Hash returned from load\_inductor\_cache (for change detection) | **Returns:** `NoneType` ### synchronized\_inductor\_cache ```python theme={null} def synchronized_inductor_cache(cache_key: 'str') -> 'Iterator[None]' ``` Context manager to automatically load and sync PyTorch Inductor cache. This wraps load\_inductor\_cache and sync\_inductor\_cache for convenience. The cache is loaded on entry and synced on exit (even if an exception occurs). **Example:** ```python theme={null} >>> with synchronized_inductor_cache("mymodel/v1"): ... self.model = torch.compile(self.model) ... self.warmup() # Compilation happens here # Cache is automatically synced after the with block ``` | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `cache_key` | `str` | - | Unique identifier for this cache (e.g., "flux/2", "mymodel/v1") | **Returns:** `Iterator[]` # fal.toolkit.image.nsfw_filter Source: https://fal.ai/docs/api-reference/python-sdk/fal-toolkit-image-nsfw-filter API reference for fal.toolkit.image.nsfw_filter ```python theme={null} from fal.toolkit.image.nsfw_filter import NSFWImageDetectionInput, NSFWImageDetectionOutput, run_nsfw_estimation ``` ## Classes ### NSFWImageDetectionInput ```python theme={null} class fal.toolkit.image.nsfw_filter.NSFWImageDetectionInput ``` !!! abstract "Usage Documentation" [Models](../concepts/models.md) A base class for creating Pydantic models. > **Inherits from:** `BaseModel` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `data` | `Any` | - | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `image_url` | `str` | - | - | ### NSFWImageDetectionOutput ```python theme={null} class fal.toolkit.image.nsfw_filter.NSFWImageDetectionOutput ``` !!! abstract "Usage Documentation" [Models](../concepts/models.md) A base class for creating Pydantic models. > **Inherits from:** `BaseModel` > [accordion] Constructor Parameters > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `data` | `Any` | - | - | > [accordion] Class Variables > > | Name | Type | Default | Description | > | :- | :- | :- | :- | > | `nsfw_probability` | `float` | - | - | *** ## Functions ### run\_nsfw\_estimation ```python theme={null} def run_nsfw_estimation(input: fal.toolkit.image.nsfw_filter.inference.NSFWImageDetectionInput) -> fal.toolkit.image.nsfw_filter.inference.NSFWImageDetectionOutput ``` | Parameter | Type | Default | Description | | :- | :- | :- | :- | | `input` | `NSFWImageDetectionInput` | - | - | **Returns:** `NSFWImageDetectionOutput` # pyproject.toml Reference Source: https://fal.ai/docs/api-reference/python-sdk/pyproject-toml Configure fal Serverless apps in pyproject.toml for reusable app names, package entry points, runtime settings, scaling, and containers. Use `pyproject.toml` to define one or more fal apps in a project. Each entry in `[tool.fal.apps]` gives an app a stable local name that you can pass to `fal run` or `fal deploy` instead of repeating a file path and class reference. ```toml theme={null} [tool.fal.apps] image-generator = { ref = "src/app.py::ImageGenerator", auth = "private", machine_type = "GPU-H100" } ``` ```bash theme={null} fal run image-generator fal deploy image-generator ``` App paths are resolved from the directory that contains `pyproject.toml`. > [!NOTE] > > `fal deploy` respects `auth` from `pyproject.toml`. `fal run` currently defaults to `public` auth and only changes auth mode when you pass `--auth`. ## Package Entry Points Use `python_entry_point` when your fal app is importable as a Python package and you want fal to load it by module path: ```toml theme={null} [project] name = "my-image-app" version = "0.1.0" dependencies = ["fal"] [tool.fal.apps] image-generator = { python_entry_point = "my_image_app.server:ImageGenerator", requirements = ["."], auth = "private", machine_type = "GPU-H100" } ``` `python_entry_point` must use `:` format. It is mutually exclusive with `ref`. Runtime and deployment settings for entry-point apps are read from `pyproject.toml`, not from class attributes or function decorator options in the imported package. For packaging requirements, monorepo examples, and custom-container usage, see [Package Entry Points](/docs/documentation/development/import-code#package-entry-points). ## Multiple Apps Define multiple apps in the same project by using app-specific tables: ```toml theme={null} [tool.fal.apps.image-generator] ref = "src/image_app.py::ImageGenerator" auth = "private" machine_type = "GPU-H100" [tool.fal.apps.captioner] python_entry_point = "my_package.captioner:Captioner" requirements = ["."] auth = "shared" machine_type = "GPU-A100" ``` Deploy each app by its key: ```bash theme={null} fal deploy image-generator fal deploy captioner ``` ## App Fields | Field | Type | Description | | :- | :- | :- | | `ref` | `string` | File reference to load, such as `src/app.py::MyApp`. Mutually exclusive with `python_entry_point`. Required unless `python_entry_point` or image-only container config is used. | | `python_entry_point` | `string` | Import path in `:` format. Use with `requirements = ["."]` or with a container image that already includes the package. Mutually exclusive with `ref`. | | `name` | `string` | Deployed app name. Defaults to the `[tool.fal.apps]` key. | | `auth` | `string` | Authentication mode: `private`, `public`, or `shared`. | | `team` | `string` | Team slug to use when running or deploying this app. A CLI `--team` value overrides it. | | `deployment_strategy` | `string` | Deploy strategy: `rolling` or `recreate`. | | `app_scale_settings` | `boolean` | When `true`, deploys with the scale settings from this config instead of inheriting runtime-tuned settings from the previous deployment. | | `requirements` | `list[string]` or `list[list[string]]` | Pip requirements. `.`, `.[extra]`, and `projects/foo[extra]` package a local project before installing it on the runner. | | `requirements_context_dir` | `string` | Base directory for resolving local-path `requirements`. Relative paths resolve from the `pyproject.toml` directory. | | `python_version` | `string` | Python version for the runtime, such as `"3.12"`. | | `machine_type` | `string` or `list[string]` | Machine type or fallback list, such as `"GPU-H100"` or `["GPU-H100", "GPU-A100"]`. | | `num_gpus` | `integer` | Number of GPUs to allocate for GPU machine types. | | `regions` | `list[string]` | Allowed regions. Supported values are `us-west`, `us-central`, `us-east`, `eu-north`, and `eu-west`. | | `min_concurrency` | `integer` | Minimum warm runners. | | `max_concurrency` | `integer` | Maximum runners to scale to. | | `max_multiplexing` | `integer` | Maximum concurrent requests per runner. | | `concurrency_buffer` | `integer` | Additional runners to keep warm above current load. | | `concurrency_buffer_perc` | `integer` | Percentage buffer of runners above current load. | | `scaling_delay` | `integer` | Seconds to wait before scaling up for pending requests. | | `keep_alive` | `integer` | Seconds to keep an idle runner alive. | | `request_timeout` | `integer` | Maximum seconds for a single request. | | `startup_timeout` | `integer` | Maximum seconds for runner startup and `setup()`. | | `private_logs` | `boolean` | Exclude app logs from request-log output, including for the owner. Runner logs remain accessible to the owner. Does not grant callers log access or control retention. See [Logging](/docs/documentation/development/logging#log-privacy-settings). | | `app_files` | `list[string]` | Local files or directories to include with the app. Not supported for container apps. | | `app_files_ignore` | `list[string]` | Regex patterns to exclude from `app_files`. | | `app_files_context_dir` | `string` | Base directory for resolving `app_files`. Only valid when `app_files` is set. Relative paths resolve from the `pyproject.toml` directory. | | `exposed_port` | `integer` | HTTP port exposed by a custom server app. | | `skip_retry_conditions` | `list[string]` | Retry conditions to skip. Supported values include `timeout`, `server_error`, and `connection_error`. | | `retry_config` | `table` | Default retry budget per retry condition, e.g. `{ server_error = { retries = 3 } }`. See [Retries and Error Handling](/docs/documentation/serverless/reliability/retries#app-level-retry_config). | | `termination_grace_period_seconds` | `integer` | Grace period for runner shutdown. | | `secrets` | `list[string]` | Runtime fal secrets to mount into the app environment. | | `health_check` | `table` | Health check configuration. See [Health Check](#health-check). | | `image` | `table` | Container image configuration. See [Container Image](#container-image). | > [!WARNING] > > `no_scale` is deprecated. Use `app_scale_settings` instead. ## Health Check ```toml theme={null} [tool.fal.apps.image-generator.health_check] path = "/health" start_period_seconds = 30 timeout_seconds = 5 failure_threshold = 3 call_regularly = true ``` | Field | Type | Description | | :- | :- | :- | | `path` | `string` | Required health check endpoint path. | | `start_period_seconds` | `integer` | Minimum runner age before failures count as unhealthy. | | `timeout_seconds` | `integer` | Timeout for each health check request. | | `failure_threshold` | `integer` | Consecutive failures before the runner is marked unhealthy. | | `call_regularly` | `boolean` | Whether fal should call the health check periodically. | ## Container Image Use the `[tool.fal.apps..image]` section to configure a container from `pyproject.toml`. Build from a Dockerfile: ```toml theme={null} [tool.fal.apps.container-app] python_entry_point = "my_package.app:MyApp" machine_type = "GPU-H100" [tool.fal.apps.container-app.image] dockerfile = "Dockerfile" build_args = { CUDA_VERSION = "12.4" } entrypoint = ["python", "-m", "my_package.app"] cmd = ["--host", "0.0.0.0", "--port", "8080"] secrets = { PIP_TOKEN = "$PIP_TOKEN" } ``` Or reference an existing image: ```toml theme={null} [tool.fal.apps.container-app] machine_type = "GPU-H100" exposed_port = 8000 [tool.fal.apps.container-app.image] image = "my-org/container-app:latest" cmd = ["your-server", "--host", "0.0.0.0", "--port", "8000"] [tool.fal.apps.container-app.image.registries."https://index.docker.io/v1/"] username = "myuser" password = "$DOCKERHUB_TOKEN" ``` | Field | Type | Description | | :- | :- | :- | | `dockerfile` | `string` | Path to the Dockerfile. Relative paths resolve from the `pyproject.toml` directory. Mutually exclusive with `image`. | | `image` | `string` | Existing container image reference, such as `my-org/container-app:latest`. Mutually exclusive with `dockerfile`. | | `build_args` | `table` | Docker build arguments. Only valid with `dockerfile`. | | `registries` | `table` | Private registry credentials for Dockerfile base images or referenced images. | | `secrets` | `table` | Build-time secrets. Values prefixed with `$` resolve from fal secrets. Only valid with `dockerfile`. | | `entrypoint` | `string` or `list[string]` | Docker ENTRYPOINT override. | | `cmd` | `string` or `list[string]` | Docker CMD override. | Set either `dockerfile` or `image` under `[tool.fal.apps..image]`. Use `registries` when the Dockerfile pulls a private base image or when `image` references a private image. Container apps can use `ref`, `python_entry_point`, or neither. If both `ref` and `python_entry_point` are omitted, fal treats the container as an image-only app and does not use the fal Python app loader. When a container app uses `python_entry_point`, make sure the Dockerfile or existing image installs the package that contains the referenced module. # Product Changelog Source: https://fal.ai/docs/changelog Latest features and updates to the fal platform What's New in Serverless Analytics, requests, runners, logs, notifications & environments From Alert to Root Cause June 2026 Scaling, observability, cold starts & multi-GPU January 2026 **October 29, 2026** ## Fallback Chains Send a primary model and up to two fallback models in one request to `POST https://fal.run/execute`. If the primary model fails with an error that you allow, fal runs the next model. The response contains the first successful result and a record of each attempt. Each model has its own input, start timeout, and list of errors that start the next model. [Learn more about fallback chains](/docs/documentation/model-apis/inference/fallback-chains) **October 13, 2026** ## Rate Limits for Runner and App Management fal now limits how often you can list, inspect, shell into, stop, and kill apps and runners. The limits apply to the CLI, the Python SDK, and the REST API. When you exceed a limit, the REST API returns `429 Too Many Requests`, and the CLI and SDK return the gRPC status `RESOURCE_EXHAUSTED`. [Learn more about the limits](/docs/documentation/serverless/reliability/rate-limits) **October 9, 2026** ## Key Presets and Custom Policies Keys now use permission presets instead of the `ADMIN` and `API` scopes. When you create a key, select one of seven presets: `API`, `SERVERLESS`, `DEPLOY`, `COMPUTE`, `BILLING`, `READONLY`, or `FULL`. If no preset matches your case, select the exact permissions the key needs. You can also limit a key to specific models and set it to expire. A preset key follows the live definition of its preset. A custom policy key, including a preset key with a model limit, keeps the permissions it had at creation. Existing `ADMIN` and `API` keys continue to work. The Platform API reference now lists the permissions each API requires and the presets that include them. [Learn more about key permissions](/docs/documentation/model-apis/authentication/key-based#permissions) **October 9, 2026** ## Creator and Viewer Team Roles Admins can now assign two new team roles. **Creator** can use the Playground, Sandbox, and Workflows, but cannot view request logs or manage API keys, billing, members, or roles. **Viewer** has read-only access to team resources. A Viewer can view request logs and the library, but cannot run models or change anything. Existing members keep their current roles. [Learn more about team roles](/docs/documentation/setting-up/teams#roles) **September 14, 2026** ## Billing Headers for WebSocket Endpoints Shared WebSocket endpoints can now declare billing on their `101` upgrade response. Set `x-fal-billable-units` when the unit count is known at connect time. Set `x-fal-billable-units-webhook` to `1` when the count is only known at the end of the session. Then report the total with `POST /requests/billable-units/{request_id}`. The platform still charges sessions without either header by duration. [Learn more about billable units](/docs/documentation/serverless/publishing-to-marketplace#define-billable-units) **September 9, 2026** ## Switch Between App Endpoints in the Dashboard Playground Deployed Serverless apps now include **Testing > Playground** in the app dashboard. Select an available endpoint, fill in its generated input form, and run a request without leaving the app. Multi-endpoint apps have one place to test their endpoints, using the existing Playground authentication and billing behavior. [Open the guide](/docs/documentation/model-apis/playground#your-own-apps) **August 17, 2026** ## Platform MCP Server fal's second MCP server — the **Platform API MCP** — is now available at `https://api.fal.ai/v1/mcp/platform`. Where the [Run MCP](/docs/documentation/setting-up/mcp) lets your AI assistant *build with models*, this one lets it *operate your fal account*: connect Claude Code, Cursor, or any MCP-compatible client with your API key and ask *"why did my last request to my-app fail?"* — your assistant walks the same debugging steps you would. **15 tools**: eleven first-class serverless debugging tools covering requests, logs, error analytics, deploy and revision history, runner and queue state, spend, and persistent storage — plus a four-tool discovery gateway that opens up the rest of the Platform API (compute, workflows, keys, account, organization, storage) without bloating your assistant's context. ```bash theme={null} claude mcp add --transport http fal-platform \ https://api.fal.ai/v1/mcp/platform \ --header "Authorization: Key YOUR_FAL_KEY" ``` * **Read-only** — it can observe your account but never change it; write operations are listed in the catalog but refuse to execute * **Stateless** — your key is sent per-request and never stored, and normal permission and ownership scoping applies * **Free** — tool calls are the same Platform API calls you could make directly with your key [Setup guide →](/docs/documentation/setting-up/platform-mcp) **August 17, 2026** ## New Serverless Observability APIs A batch of endpoints rounds out programmatic access to what the dashboard shows about your serverless apps: * **[`GET /v1/serverless/apps`](/docs/platform-apis/v1/serverless/apps/list)** — list your deployed apps with live state: active runners, queue size, machine types, and environment. Add `expand=endpoints` to include each app's route-level endpoint ids, in the exact form the requests and analytics APIs accept. * **[`GET /v1/serverless/apps/{owner}/{name}/events`](/docs/platform-apis/v1/serverless/apps/events)** — operational event history: deployments, configuration changes, and runner lifecycle transitions — the "what changed around this time?" API. Also surfaced in the dashboard's [events timeline](/docs/documentation/serverless/observability/app-events). * **[`GET /v1/serverless/apps/{owner}/{name}/revisions`](/docs/platform-apis/v1/serverless/apps/revisions)** — revision history with deployment status, who deployed, and [deploy messages and annotations](/docs/documentation/deployment/deploy-to-production#annotating-deployments) (the API behind the August 3 entry above) — line revision boundaries up against your error timeline to spot a bad deploy. * **[`GET /v1/serverless/apps/{owner}/{name}/runners/history`](/docs/platform-apis/v1/serverless/apps/runner-history)** — historical runner counts by state (running, idle, pending, draining) for capacity analysis and incident forensics. Together with the existing requests, logs, analytics, metrics, and usage APIs, these power the new [Platform MCP server](/docs/documentation/setting-up/platform-mcp) — and they're plain REST endpoints you can call directly with your API key. **August 4, 2026** ## Narrower BILLING Key Preset The `BILLING` key preset is now read-only for billing. A key on this preset can read usage, invoices, contracts, and billing settings. It can no longer change payment methods or billing settings. The preset now also grants read access to the list of keys and to the model catalog. The `READONLY` preset no longer grants request sharing. A key on a preset follows the live definition of that preset, so existing `BILLING` and `READONLY` keys picked up these changes at their next request. If the permissions of a key must stay the same for the life of the key, create the key with a custom policy. See [Key permissions](/docs/documentation/model-apis/authentication/key-based#permissions). **August 4, 2026** ## GPU Utilization in Runner Telemetry Runner telemetry now includes a dedicated **GPU Utilization** chart alongside the existing CPU, memory, and VRAM charts, so you can see how much compute your GPUs are actually doing -- not just how much memory they hold. * **GPU Utilization** reports the average compute utilization across a runner's GPUs over time, surfaced both as a current stat and a time-series chart in the runner side sheet. * Pair it with **VRAM Usage** to tell a memory-bound runner apart from a compute-bound one, making it easier to right-size machine types and spot under-utilized GPUs. Open any runner from the Runners page (**Dashboard → Apps → \[your-app] → Runners**) to view its telemetry. See [Runner Analytics](/docs/documentation/serverless/observability/runner-analytics) for details. **August 3, 2026** ## Deploy Messages and Annotations You can now attach a freeform message and custom annotations to each revision when deploying: ```bash theme={null} fal deploy my_app.py::MyApp --message "Deploying new version" --annotation GIT_SHA=a1b2c3d4 ``` * Messages and annotations are set at deploy time and stay with the revision. * View and search them on the app's **Versions** page in the dashboard, or fetch them via the [revisions API](/docs/platform-apis/v1/serverless/apps/revisions). * Also available in the Python SDK: `client.deploy(..., message=..., annotations={...})`. See [Annotating Deployments](/docs/documentation/deployment/deploy-to-production#annotating-deployments) for details. **July 8, 2026** ## App-Level Retry Configuration Apps can now register a default per-condition retry budget at deploy time with the new **`retry_config`** deployment option, using the same format as the `X-Fal-Retry-Config` request header. * Set it as a class attribute on `fal.App` or under the app's table in `pyproject.toml`. * Applies to all queue-based requests to the app; the app owner can still override it per-request with the `X-Fal-Retry-Config` header. * Each condition (`server_error`, `timeout`, `connection_error`) keeps an independent budget, bounded by the platform ceiling of 10 total attempts. See [Retries and Error Handling](/docs/documentation/serverless/reliability/retries#app-level-retry_config) for details. **June 17, 2026** ## New Serverless Usage Page The new **[Serverless Usage page](https://fal.ai/dashboard/serverless-usage)** (Serverless → Usage) provides attributable, dimensioned reporting of serverless compute spend in the dashboard. * **Compute reported in machine-seconds**, broken down per app, environment, and machine type. * **Spend is split by price category: Reserve, Burst, On-Demand, and List.** This distinguishes consumption covered by committed reserved capacity from burst overage and undiscounted list-rate usage, supporting reservation sizing and workload placement decisions. * **Group by app or by machine type**, including a dedicated **Usage by machine type** view, to identify the deployments and hardware classes driving cost. * Billing-cycle and custom time-range presets are supported. On-demand quotes are reported as a distinct price category, and organization-level reporting now spans both serverless and compute. This is the same dataset returned by the [`GET /v1/serverless/usage`](/docs/platform-apis/v1/serverless/usage) API, surfaced in the dashboard. **June 16, 2026** ## Redesigned Usage & Billing Page The **[Usage & Billing page](https://fal.ai/dashboard/usage-billing)** has been rebuilt to support usage attribution (the Settings "Overview" tab is now "Usage"). * **Filter by auth method, API key, and login username** to attribute consumption to a specific credential or user. * Normalized app names and revised charts improve readability and export. **June 16, 2026** ## Deploy Existing Docker Servers Without Code Changes Existing Docker-based servers (ComfyUI, custom APIs) can now be deployed without rewriting them as a `fal.App`, reducing migration effort from self-hosted infrastructure, Kubernetes, or RunPod. * **Direct Server Mode:** set `exposed_port` in `pyproject.toml` and fal routes traffic directly to the container port. Existing routes, middleware, and response formats are preserved. * **Prebuilt image references (no Dockerfile required):** reference an image already pushed to a registry (`image = "my-org/my-server:latest"`) and override `entrypoint`/`cmd` under `[tool.fal.apps..image]`. * **Private registry support:** pull from Docker Hub, Google Artifact Registry, or Amazon ECR by supplying registry credentials in the image configuration. * Migration guides are available for [external Docker servers](/docs/documentation/development/migrate-external-docker-server) and [RunPod](/docs/documentation/development/migrate-from-runpod), along with the [`pyproject.toml` reference](/docs/api-reference/python-sdk/pyproject-toml) and [Private Docker Registries](/docs/documentation/development/private-registries). **June 15, 2026** ## Serverless Usage API * New **[`GET /v1/serverless/usage`](/docs/platform-apis/v1/serverless/usage)** endpoint reports your own serverless compute usage — the machine-seconds each of your deployed apps consumed, priced with your machine rates and net of discounts * Break usage down per app, environment, and machine type, with `time_series` and `summary` views over any date range and timeframe * Filter by app name with `app` (exact, one or more) or `search` (case-insensitive substring) — match a deployed app by name without needing its exact version suffix * Ideal for per-app cost reporting and exporting to your own billing/observability tools * Complements the per-request `billable_units` on [`GET /v1/serverless/requests/by-endpoint`](/docs/platform-apis/v1/serverless/requests/by-endpoint) with an aggregated, time-bucketed view **June 7, 2026** ## New Capacity Page The new **[Capacity page](https://fal.ai/dashboard/capacity)** (Serverless → Capacity) reports GPU consumption against your account limit, providing visibility into available headroom before requests begin queuing. * **Account-wide GPU usage over time, plotted against your limit**, with baseline and burst reference lines indicating utilization relative to reserved capacity. * **Per-GPU-type breakdown** of capacity consumption by hardware class. * **Approaching-limit and at-limit indicators** on runner and app views, with GPU counts shown on runners. * **Request more capacity** action for requesting a higher limit. **June 5, 2026** ## Per-Condition Retry Configuration The new **`X-Fal-Retry-Config`** request header replaces all-or-nothing retry behavior with a separate retry budget per failure condition, allowing retry policy to be tuned independently for each failure mode. * Map each retry condition (`server_error`, `timeout`, `connection_error`) to its own `retries` count (for example, retry transient server errors while disabling retries on timeouts). * Each condition maintains an independent budget, bounded by the platform ceiling of 10 total attempts. * Applies to apps you own and takes precedence over status-code defaults. `x-fal-no-retry` takes precedence when both are set. * Complements app-level `skip_retry_conditions` and the per-response `X-Fal-Needs-Retry` and `x-fal-stop-runner` controls. See [Retries and Error Handling](/docs/documentation/serverless/reliability/retries) for the full reference. **June 2, 2026** ## Filter and Sort Apps Managing a large number of serverless apps is now easier with new filtering and sorting controls directly on the [apps page](https://fal.ai/dashboard/apps). * **Filter by machine type** to instantly isolate apps running on specific hardware (e.g., H100, A100, L40) and monitor targeted resource allocation. * **Sort by active runners, GPUs, or queue size** to instantly surface the apps consuming the most capacity or backing up with queued requests. ![New filter by machine type and sorting options for runners, GPUs, and queue size](https://mintcdn.com/fal-d8505a2e/ND7LYAPTZuIL9ZIB/images/changelog/apps-filters.png?fit=max\&auto=format\&n=ND7LYAPTZuIL9ZIB\&q=85\&s=d5db77ed01bd9fc1d93279d0bb95752d) Works in both card view and list view, and stacks with environment and tag filtering so you can find what needs your attention faster. **June 1, 2026** ## Expanded Analytics Metrics The [`GET /v1/models/analytics`](/docs/platform-apis/v1/models/analytics) and [`GET /v1/serverless/analytics`](/docs/platform-apis/v1/serverless/analytics) endpoints now support fourteen additional metrics via the `expand` parameter, matching the metric families the dashboard surfaces: * **Error type breakdown** — `startup_error_count`, `connection_error_count`, `timeout_error_count`, `runtime_error_count` for finer-grained failure attribution beyond the existing 4xx/5xx counts * **Cold boot metrics** — `cold_boot_count`, `p50_cold_boot_duration`, `p75_cold_boot_duration`, `p90_cold_boot_duration` for tracking startup latency * **Extended latency percentiles** — `p25_duration`, `p95_duration`, `p99_duration`, `p95_prepare_duration`, `p99_prepare_duration` for tail-latency analysis * **Total billable duration** — `total_billable_duration` for aggregate billable execution time (the sum of request execution durations) Existing metrics and response shape are unchanged; only new optional fields are added. **May 29, 2026** ## Configurable Termination Grace Period The runner termination grace period is now configurable, allowing long-running requests to drain and `teardown()` to complete before `SIGKILL`, which reduces the risk of dropped work or inconsistent state during scale-down. * **`termination_grace_period_seconds` is configurable up to 1 hour** (previously capped at 30 seconds, default 5 seconds). * The grace period is a shared budget for completing in-flight requests and running `teardown()`. Use `handle_exit()` to signal long requests to stop early so cleanup is not skipped. * `keep_alive` now applies to both idle-after-request and never-served runners. See [Scale Your Application](/docs/documentation/deployment/scale-your-application#termination_grace_period_seconds) for details. **April 29, 2026** ## Aggregate Analytics Components ![Serverless apps page aggregate analytics dashboard with GPU and CPU distribution, live capacity tiles, traffic and concurrency charts, top apps, and a per-app stacked requests breakdown](https://mintcdn.com/fal-d8505a2e/NH1xMgqfuYMzBqdq/images/changelog/apps.png?fit=max\&auto=format\&n=NH1xMgqfuYMzBqdq\&q=85\&s=39b65eb1b8d4b4f4d0376c0a11b57a05) The Serverless apps page now opens with an aggregate analytics dashboard that summarizes capacity, traffic, and per-app activity across every app you own in one place. * **GPU and CPU distribution** charts visualize how your active runners are split across machine types (H100, A100, L40, B200, CPU types, etc.) * **Live capacity tiles** show total **Active Runners, Queued Requests, GPUs, and CPUs**, each annotated with how many apps contribute to the number * **Status code, request traffic, and concurrent request** charts plot aggregate request health over your selected window * **Top Apps** lists your highest-volume apps over the window for quick drill-in * **Requests by app** is a new stacked chart that breaks aggregate traffic down per app, with a searchable legend you can click to isolate a single app or flip to an **Errors** view **April 28, 2026** ## Legacy CDN Cleanup — June 1st, 2026 On **June 1st, 2026**, any legacy CDN object not accessed in the past 6 months will be deleted. **How to identify legacy objects:** Legacy URLs look like `/files/[animal]/[filename]` (e.g. `/files/otter/AFsfdoliuhhvf.mp4`). Anything served from `/files/b/...` is on our current CDN and is unaffected. **If you've accessed it recently, it's already safe:** Any legacy object accessed in the last 6 months has already been automatically migrated to our current CDN — no action needed on your end. The URL is unchanged and the object will be preserved. **To keep a legacy object you haven't touched in a while:** Access it once before **June 1st, 2026**. That single access triggers the automatic migration and preserves the object. The URL stays the same. **What stays the same:** * Legacy URLs continue to work — no code changes needed * Anything new you create already uses the modern CDN (`/files/b/...`) **April 27, 2026** ## Deploy ComfyUI on fal — Visual Control Run ComfyUI workflows on fal serverless GPUs without writing a single line of code. Two pre-built zip packages, one double-click — your team is generating on H100s in minutes. * **User package** — a tiny launcher UI on `localhost:9998`. Paste your fal API key and the endpoint slug your team lead gave you, click **Start**, and the full ComfyUI canvas opens on `localhost:8188` running against the cloud GPU. * **Admin package** — a complete management UI on `localhost:9999`. Add models, custom nodes, and Python deps from a table, set HuggingFace / Civitai tokens for gated weights (auto-pushed to fal secrets at deploy), and ship with one click. Live runner observability, an outputs gallery, and an undeploy switch are built in. ![Admin web UI showing the Models tab — folders, filenames, download URLs in a table](https://mintcdn.com/fal-d8505a2e/Un5AMpXNKs4_TsjB/images/changelog/comfyui-visual-admin.png?fit=max\&auto=format\&n=Un5AMpXNKs4_TsjB\&q=85\&s=f0f6c87a56d04a741a6a535ea505cc84) The launcher auto-installs `uv` and Python 3.11 on first run — no Python knowledge required from end users. Works on macOS and Windows. [Read the guide →](/docs/examples/image-generation/run-comfyui-visual) **April 23, 2026** ## Runner Termination Reason Diagnose why a runner was terminated directly from the dashboard. The reason now appears across every runner surface. * **Runner detail page** — termination reason is shown inline next to the state. ![Runner detail page state section showing termination reason badge](https://mintcdn.com/fal-d8505a2e/GdCSIoK3y-dVum8C/images/changelog/runner-terminate-reason-detail.png?fit=max\&auto=format\&n=GdCSIoK3y-dVum8C\&q=85\&s=b855acfc34426bf63bdcc0877d1a2bb1) * **Runner list** — surfaces the same reason via a tooltip on the state badge, so you can scan failures without opening each runner ![Runner list with termination reason tooltip on the state badge](https://mintcdn.com/fal-d8505a2e/GdCSIoK3y-dVum8C/images/changelog/runner-terminate-reason-list.png?fit=max\&auto=format\&n=GdCSIoK3y-dVum8C\&q=85\&s=86dcc994543b9f7ad36e7ccd4d9a3d9a) * **Runner events timeline** — event rows display the termination reason as a highlighted badge alongside the status text ![Runner event row showing termination reason as a highlighted badge alongside the status text](https://mintcdn.com/fal-d8505a2e/GdCSIoK3y-dVum8C/images/changelog/runner-terminate-reason-events.png?fit=max\&auto=format\&n=GdCSIoK3y-dVum8C\&q=85\&s=d27c350bee87a53a7357c64e52a3dcd9) Please note that in some cases the termination reason may be unknown. When that happens, no reason badge or tooltip is shown. **April 23, 2026** ## fal Workflow * Improved the model search experience * Improved API documentation * Smoother workflow when adding models * Node IDs are visible in the UI * Nodes can be locked * Media-type icons on node handles * Performance improvements and bug fixes **April 14, 2026** ## Model API Reference We've launched a comprehensive **[Model API Reference](/docs/model-api-reference)** — auto-generated documentation for every top model on fal.ai, covering video generation, image generation, audio, vision, and 3D. Each model page includes: * **Full input/output schemas** with parameter descriptions, types, and defaults * **Quick Start code examples** in Python, JavaScript, and cURL * **Real prompt-and-output examples** pulled directly from the fal.ai playground * **Rich model descriptions** with feature breakdowns, comparisons, and technical specs * **Direct playground links** to try models interactively The reference is organized by model family (FLUX, Kling Video, Seedance, Nano Banana, Veo, and more) with a navigation structure that mirrors the endpoint hierarchy. Browse by category or jump straight to any endpoint. [Explore the Model API Reference →](/docs/model-api-reference) **April 10, 2026** ## Serverless Analytics API * New **[`GET /v1/serverless/analytics`](/docs/platform-apis/v1/serverless/analytics)** endpoint lets serverless app owners query time-bucketed analytics across all inbound traffic to their endpoints * Retrieve request counts, success/error rates, and latency percentiles (p50/p75/p90) for any date range and timeframe * Ideal for exporting analytics to your own tools like BigQuery, Grafana, or Datadog * Requires endpoint ownership — only the app owner can access these metrics * The existing [`GET /v1/models/analytics`](/docs/platform-apis/v1/models/analytics) continues to show your own request activity as a caller **April 1, 2026** ## Latency Percentile Chart ![Latency percentile chart showing p50, p90, p95, and p99 over time](https://mintcdn.com/fal-d8505a2e/_K0ozUKUZUyNXY0L/images/changelog/latency-percentile-chart.png?fit=max\&auto=format\&n=_K0ozUKUZUyNXY0L\&q=85\&s=b652d30a1d10d515e5c2adada4b7c364) * The [analytics page](/docs/documentation/serverless/observability/app-analytics) now includes a **latency percentile chart** showing p50, p90, p95, and p99 request latency over time * Quickly spot latency regressions or tail-latency spikes at a glance **March 31, 2026** ## Multi-Endpoint Aggregation in Analytics ![Analytics endpoint selector with All option for aggregated metrics](https://mintcdn.com/fal-d8505a2e/_K0ozUKUZUyNXY0L/images/changelog/multi-endpoint-aggregation.png?fit=max\&auto=format\&n=_K0ozUKUZUyNXY0L\&q=85\&s=612727e3c34f436fb147b05517d4bdd4) * Select **"All" endpoints** in [App Analytics](/docs/documentation/serverless/observability/app-analytics) to see metrics aggregated across every endpoint at once * Aggregation works across request counts, error rates, percentile charts, and gateway stats, so you can get a full picture of your app's performance without switching between endpoints **March 31, 2026** ## GPU and Runner Metrics on Apps Page ![Apps page with aggregate metrics bar showing runners, queue depth, and GPU distribution](https://mintcdn.com/fal-d8505a2e/_K0ozUKUZUyNXY0L/images/changelog/gpu-runner-metrics-apps.png?fit=max\&auto=format\&n=_K0ozUKUZUyNXY0L\&q=85\&s=4d30827b73e8c4dab8707307896f688d) * The [apps page](/docs/documentation/deployment/manage-deployments) now shows an **aggregate metrics bar** with total runners, queue depth, and GPU distribution, giving you a quick overview of your resource usage without clicking into each app * **Per-app GPU and queue columns** in both card view and list view make it easy to compare usage across apps at a glance **March 31, 2026** ## Logs Endpoint Filtering and Source Column ![Logs view with endpoint filter and source column](https://mintcdn.com/fal-d8505a2e/_K0ozUKUZUyNXY0L/images/changelog/logs-endpoint-source.png?fit=max\&auto=format\&n=_K0ozUKUZUyNXY0L\&q=85\&s=0637fb4efb04c9488924b69b2a91cff1) * **Filter [logs](/docs/serverless/development/logging) by endpoint** to focus on a specific route * A new **Source column** shows which endpoint or system action produced each log line **March 30, 2026** ## Notifications Overhaul ![Redesigned notifications dropdown with pagination and mark all read](https://mintcdn.com/fal-d8505a2e/_K0ozUKUZUyNXY0L/images/changelog/notifications-overhaul.png?fit=max\&auto=format\&n=_K0ozUKUZUyNXY0L\&q=85\&s=ead345f1f0c40abef26501511f790595) * **Redesigned notification dropdown** so you can stay on top of issues without leaving the page you're on * **Category filtering** lets you cut through noise and focus on the notification types that matter to you * **Pagination** so you can browse your full notification history without losing your place * **Mark all as read** to quickly clear your inbox when you've caught up * **OOM alerts** notify you when a runner runs out of memory, so you can resize before it impacts users * **Notification badge on app tabs** shows unread counts per app so you know exactly which apps need attention See [notification settings](/docs/documentation/serverless/observability/slack-notifications) to configure alerts. **March 28, 2026** ## Cold Start and Queue Percentiles ![Analytics page showing cold start ratio, cold start percentiles, and queue wait percentiles](https://mintcdn.com/fal-d8505a2e/_K0ozUKUZUyNXY0L/images/changelog/cold-start-queue-percentiles.png?fit=max\&auto=format\&n=_K0ozUKUZUyNXY0L\&q=85\&s=17f96717c19e1fa0ac28027d8a1d49d5) * **Cold start ratio** shows what percentage of requests hit a cold start, so you can measure the impact of your scaling configuration * **Cold start duration percentiles** (p50, p75, p90, p95) help you understand whether cold starts are a minor delay or a real bottleneck for your users * **Queue wait percentiles** (p50, p75, p90, p95) reveal how long requests wait before a runner picks them up, helping you decide if you need more concurrency * A new **startup breakdown card** shows exactly where startup time goes (image pull, setup, etc.) so you know what to optimize * The [analytics](/docs/documentation/serverless/observability/app-analytics) layout has been redesigned with expandable sections so you can focus on the metrics that matter most **March 28, 2026** ## Request Throughput Charts ![Charts showing processed requests per second, received requests per second, and concurrent requests](https://mintcdn.com/fal-d8505a2e/_K0ozUKUZUyNXY0L/images/changelog/request-throughput-charts.png?fit=max\&auto=format\&n=_K0ozUKUZUyNXY0L\&q=85\&s=63a293ed8a4ebec930f7f3a42eff8be3) New charts are available on the [App Analytics](/docs/documentation/serverless/observability/app-analytics) Requests tab: * **Processed requests per second** chart shows your inference throughput over time * **Received requests per second** chart shows the inbound request rate * **Concurrent requests** chart shows how many requests are in-flight simultaneously **March 28, 2026** ## API Key Tags and Editing ![Keys page with tags column and editable key descriptions](https://mintcdn.com/fal-d8505a2e/_K0ozUKUZUyNXY0L/images/changelog/api-key-tags-editing.png?fit=max\&auto=format\&n=_K0ozUKUZUyNXY0L\&q=85\&s=433861fbc2313a08b37a7b53c64a55d7) * **Tags on [API keys](/docs/documentation/setting-up/authentication/index)** let you organize keys with the same tagging system used for apps * **Editable key descriptions** can now be updated directly from the dashboard without recreating the key **March 27, 2026** ## Request Timing Breakdown ![Request list showing duration broken into startup time and execution time](https://mintcdn.com/fal-d8505a2e/_K0ozUKUZUyNXY0L/images/changelog/request-timing-breakdown.png?fit=max\&auto=format\&n=_K0ozUKUZUyNXY0L\&q=85\&s=905043093a77cbf45aa840451a649378) * Request duration in the [requests list](/docs/serverless/deployment-operations/monitor-performance) now shows a **breakdown into startup time and execution time** * Hover over the duration to see the full timing detail **March 27, 2026** ## Environment Manager ![Environment manager dialog for creating and deleting environments](https://mintcdn.com/fal-d8505a2e/_K0ozUKUZUyNXY0L/images/changelog/environment-manager.png?fit=max\&auto=format\&n=_K0ozUKUZUyNXY0L\&q=85\&s=f2ddcafc9f772e06c0aff90ec68643aa) * A new **[environment manager](/docs/serverless/deployment-operations/manage-environments) dialog** lets you create and delete environments in one place * The environment selector is now **searchable**, replacing the old dropdown **March 25, 2026** ## Requests Page Overhaul ![Requests page with status code charts, p90 latency, and sortable request list](https://mintcdn.com/fal-d8505a2e/o8eW4dsVeOWMw5el/images/changelog/requests-page-overhaul.png?fit=max\&auto=format\&n=o8eW4dsVeOWMw5el\&q=85\&s=6f0dec1c687f0a72c19529ae9502d6bc) * **Status code and latency charts** — the requests page now shows interactive charts for request status code distribution and p90 latency over time, giving you an instant picture of your app's health * **Click and drag to filter** — select a time range on any chart to filter the request list below to just that window, making it easy to isolate a spike or incident * **Sort by cold start, execution time, and latency** — sort the request list by longest cold start duration, execution time, total latency, and more to quickly surface the slowest or most problematic requests * **Jump to Analytics** — a direct link takes you from the requests page to App Analytics with your current filters pre-applied **March 23, 2026** ## Runner Summary on App Overview ![Runner summary card showing active runner counts, state breakdowns, and concurrency trend](https://mintcdn.com/fal-d8505a2e/o8eW4dsVeOWMw5el/images/changelog/runner-summary-card.png?fit=max\&auto=format\&n=o8eW4dsVeOWMw5el\&q=85\&s=659748d93f5c17e43f616c0c86d99973) * The app overview page now includes a **runner summary card** showing active runner counts, state breakdowns, and a concurrency trend chart at a glance * Quickly see how many runners are in each state (running, idle, pending, setup) without navigating to the Runners page **March 20, 2026** ## Search Runners by ID ![Runner ID search on the Runners page](https://mintcdn.com/fal-d8505a2e/o8eW4dsVeOWMw5el/images/changelog/runner-id-search.png?fit=max\&auto=format\&n=o8eW4dsVeOWMw5el\&q=85\&s=f1b14ce93d0862ff6364bcd8e5806cb7) * Search for a specific runner by its ID on the Runners page — useful when you have a runner ID from logs, alerts, or incident reports * Results display instantly with full runner details, and the Refresh button re-fetches the searched runner **March 20, 2026** ## Error Types in App Requests and Errors pages ![Error type badges on request logs showing specific failure reasons](https://mintcdn.com/fal-d8505a2e/o8eW4dsVeOWMw5el/images/changelog/error-types-ui.png?fit=max\&auto=format\&n=o8eW4dsVeOWMw5el\&q=85\&s=28a9aeb6cfea6071d12d5858af5c9ae7) * Failed requests in the dashboard now show the **specific reason** for the failure — not just a status code, but whether it was a `request_timeout`, `runner_disconnected`, `startup_timeout`, `runner_scheduling_failure`, and more * Instantly understand if a 500 was caused by your code crashing, the runner running out of memory, or a scheduling issue — without digging through logs * Error types are shown as badges on request rows and in the request detail view, matching the `error_type` field in [API responses](/docs/model-apis/errors#request-error-types) **March 20, 2026** ## Granularity Picker on App Overview Chart ![Granularity picker on the app overview chart](https://mintcdn.com/fal-d8505a2e/o8eW4dsVeOWMw5el/images/changelog/granularity-picker.png?fit=max\&auto=format\&n=o8eW4dsVeOWMw5el\&q=85\&s=4caf1dec51215ceb44a02a7d5bfd48cb) * The app overview chart now includes a **granularity picker** to control the time bucket size — defaults to 10-minute intervals * Choose finer or coarser intervals to zoom into specific traffic patterns or view broader trends **March 16, 2026** ## Enhanced App Cards * App cards on the listing page now show **separate client and server error rates** for clearer error attribution * Updated **machine type icons** for better visual identification of GPU types * Improved card layout with more readable stat values **March 20, 2026** ## REST API `/metrics` Improvements Runner-level resource metrics are now available through the REST API: * **Runner resource metrics** — CPU, memory, GPU, and VRAM usage are now included in `/metrics`, summed across all runners per app * **Per-runner metrics endpoint** — `GET /metrics/runners/{runner_id}` returns resource metrics for an individual runner **March 18, 2026** ## fal MCP Server The fal MCP server is now available at `mcp.fal.ai`. Connect any AI assistant that supports the [Model Context Protocol](https://modelcontextprotocol.io) — Claude Code, Claude Desktop, Cursor, Windsurf, and more — to the full fal platform. **9 tools** let your assistant search 1,000+ models, check schemas and pricing, run inference, upload files, and browse documentation — all from a single conversation. ```bash theme={null} claude mcp add --transport http --scope user fal https://mcp.fal.ai/mcp-relay ``` Then run `/mcp` in Claude Code, select `fal`, and sign in through your browser. No API key or authorization header is needed. The server is fully stateless and free to use. You only pay for the model runs you trigger. * [Setup guide](/docs/documentation/setting-up/mcp) **March 17, 2026** ## `x-fal-stop-runner` Response Header You can now control whether a runner is terminated after a response using the `x-fal-stop-runner` response header, independent of the HTTP status code. * Set `x-fal-stop-runner: true` to force runner termination with any status code (same effect as a 503 on the runner, without requiring a 503 response) * Set `x-fal-stop-runner: false` to keep the runner alive even when returning a 503 (useful when you want the retry behavior of a 503 without killing the runner) * The header is stripped from the response before it reaches the caller * Combine with `X-Fal-Needs-Retry` to fully decouple retry behavior from runner lifecycle — for example, retry on a fresh runner (`X-Fal-Needs-Retry: 1` + `x-fal-stop-runner: true`) or retry while keeping the current runner alive (`X-Fal-Needs-Retry: 1` + `x-fal-stop-runner: false`) See [Retries and Error Handling](/docs/documentation/serverless/reliability/retries#per-response-x-fal-stop-runner) for full details. **March 12, 2026** ## Delete App Versions * You can now **delete individual app versions** directly from the dashboard * Useful for cleaning up old or failed deployments without needing the CLI * A confirmation dialog prevents accidental deletions **March 12, 2026** ## Shareable Runner Details * Runner slideout panels are now **shareable via URL** — click on a runner and copy the link to share the exact runner view with a teammate * Helpful for debugging runner issues collaboratively or linking from incident reports **March 12, 2026** ## Endpoint Filter in Request Logs * Filter your request logs by **specific endpoint** to focus on traffic to a particular route (e.g. `/predict` vs `/health`) * Works alongside existing filters for status codes, date ranges, and apps **March 11, 2026** ## Interval Selection and Chart Zoom in Analytics * The analytics pages now include an **Interval** picker that lets you control how metrics are bucketed — choose from **30 seconds**, **1 minute**, **5 minutes**, **10 minutes**, **1 hour**, **1 day**, **1 week**, or **1 month** depending on your selected date range * Use finer intervals (30 sec, 1 min) to pinpoint exact moments when latency spiked or error rates changed, and wider intervals (1 day, 1 week) for high-level trends over longer periods * **Click and drag on any chart** in [App Analytics](/docs/documentation/serverless/observability/app-analytics) to select a time range and instantly zoom into that window — the date range updates automatically so you can isolate an incident, compare before-and-after a deployment, or drill into a traffic spike without manually adjusting date pickers * The Interval picker is available on both the **Requests** and **Runners** tabs in App Analytics, as well as in [Error Analytics](/docs/documentation/serverless/observability/error-analytics) **March 11, 2026** ## App List View * Toggle between **card view** and a new compact **list view** on the app listing page using the view switcher in the toolbar * List view displays your apps as rows with columns for **type**, **runners**, **requests/min**, **latency**, **errors**, **machine type**, and **last updated** — making it easy to scan and compare performance across many apps at once * Your view preference is saved automatically, so you'll see the same layout next time you visit * Especially useful for teams managing dozens of serverless apps who need to quickly spot which apps need attention **March 11, 2026** ## Error Types in API Responses * Error responses now include a machine-readable **`error_type`** field identifying the specific failure category — such as `request_timeout`, `runner_disconnected`, `runner_scheduling_failure`, or `runner_server_error` * Use `error_type` to build smarter retry logic: runner and timeout errors (e.g. `runner_connection_timeout`, `startup_timeout`) are typically transient and worth retrying, while client errors like `bad_request` should not be * Track `error_type` values in your monitoring to spot trends — for example, frequent `runner_scheduling_failure` errors may indicate you need to increase `max_concurrency` See [Error Reference — Request Error Types](/docs/model-apis/errors#request-error-types) for the full list of error types, status codes, and handling guidance. **March 11, 2026** ## Termination Grace Period * New `termination_grace_period_seconds` parameter lets you control how long a runner has to finish in-flight requests and run `teardown()` before being forcefully killed * Defaults to **5 seconds**, configurable up to a maximum of **30 seconds** ```python theme={null} class MyApp(fal.App): termination_grace_period_seconds = 20 ``` See [Scale Your Application — Termination Grace Period](/docs/serverless/deployment-operations/scale-your-application#termination-grace-period) for the full shutdown lifecycle and best practices. **February 25, 2026** ## App Tagging * You can now create and assign **custom tags** to your serverless apps directly from the dashboard * Organize your app listing by tagging apps by team, project, model type, or any label that makes sense for your workflow * **Filter by tag** in the app list to quickly find the apps you need * Create, assign, and remove tags right from the app listing page — no CLI or API needed Tags are visual labels for organizing your dashboard — they don't affect app behavior, routing, or secrets. For isolated deployment stages (dev, staging, production), use [Environments](/docs/serverless/deployment-operations/manage-environments) instead. **February 23, 2026** ## Machine Type in Runner Output * `fal runners list` and `fal app runners ` now display the **machine type** for each runner (e.g. `GPU-A100`, `GPU-H100`) * JSON output (`--output json`) also includes the `machine_type` field for each runner **February 17, 2026** ## Runner `CRASH_BACKOFF` Status * Runners that fail during `setup()` now show a `CRASH_BACKOFF` status, making it easier to identify runners that are in a cooldown period before retrying initialization * You can filter runners by this state using `fal runners list --state crash_backoff` * See [Understanding Runners](/docs/serverless/deployment-operations/understand-runners#runner-states) for details **February 16, 2026** ## Interactive Log Histogram * The logs page now features an interactive histogram that visualizes log volume over time, broken down by severity level * **Click and drag** to select a time range on the histogram to zoom into that window and filter your logs instantly * **Zoom in and out** to explore log patterns at different time granularities * Color-coded bars show the distribution of stderr, error, warning, info, and trace logs at a glance ## Jump to Context * When viewing a specific log entry, use the new **Jump to Context** button to instantly scroll to surrounding log lines * Quickly see what happened before and after any log entry without manually searching through timestamps * Especially useful when navigating to a log from a shared link or alert ## Switch Log Timezones Between UTC and Local * You can now toggle between **UTC** and your **local timezone** directly from the datepicker in the logs page * All log timestamps, filters, and the histogram update instantly when switching timezones **February 12, 2026** ## Serverless App Cards with Error Rates and Graphs * The app listing page now displays rich cards for each serverless app with at-a-glance performance metrics * **Error rate indicators** show the health of each app directly on the card * **Inline sparkline graphs** visualize request volume and error trends over time * Quickly identify apps that need attention without clicking into each one individually **February 11, 2026** ## Share Logs with Your Team * You can now click on any log entry and share the link directly with the rest of your team * Shared log links preserve the full context of the log, making it easy to collaborate on debugging and troubleshooting ## Runner Side Sheet * Click into any runner on the Runners page to open a detailed side sheet with telemetry, logs, and the ability to connect to the runner * Makes it much easier to debug and observe your runners without leaving the page **February 11, 2026** ## `--auth` flag for `fal run` You can now specify the authentication mode when running your app with `fal run` using the `--auth` flag. Supported values are `public` and `private`, giving you control over who can access your app during development and testing. ```bash theme={null} fal run path/to/myapp.py::MyApp --auth private ``` * `public` — no authentication required, app owner pays * `private` — only you or your team can access **February 4, 2026** ## Full-Screen Logs * The logs page now opens in a **full-screen view**, giving you significantly more vertical and horizontal space to work with * See more log lines at once and reduce scrolling when debugging complex issues **February 3, 2026** ## FalBaseModel for better input/output definitions Define your API inputs and outputs with `FalBaseModel` a Pydantic base class with built-in support for hidden fields, field ordering, and media type hints. * **Hidden fields** - Use `Hidden(Field(...))` to mark parameters as API-only, hiding them from the playground UI while keeping them accessible via API * **Field ordering** - Control the order of fields in your API schema with `FIELD_ORDERS` * **Media field helpers** - Use `ImageField`, `AudioField`, `VideoField`, and `FileField` for better playground rendering Example: ```python theme={null} from fal.toolkit import FalBaseModel, Field, Hidden, ImageField class TextToImageInput(FalBaseModel): FIELD_ORDERS = ["prompt", "negative_prompt", "image_size"] prompt: str = Field(description="Text description of the image") negative_prompt: str = Field(default="", description="What to avoid") image_size: str = Field(default="1024x1024") # Hidden from playground but accessible via API debug_mode: bool = Hidden(Field(default=False)) internal_seed: int = Hidden(Field(default=-1)) class ImageToImageInput(FalBaseModel): image_url: str = ImageField(description="Input image") strength: float = Field(default=0.8) ``` See [Handle Inputs and Outputs](/docs/serverless/development/handle-inputs-and-outputs#falbasemodel) for details. **February 2, 2026** ## Switch environments from app pages You can now quickly switch between environments directly from any app page using the new environment dropdown in the dashboard. * **Environment dropdown** - Click the environment badge on any app page to see all environments where the app is deployed * **One-click switching** - Select an environment to navigate to the same app in that environment * **Quick access** - View environment secrets or create new environments directly from the dropdown **January 30, 2026** ## Track when runners are idle and waiting for work > [!WARNING] > > **Potential Breaking Change** - The runner state model has been updated. If > you're monitoring or tracking runner states programmatically, you may need to > update your integration to handle the new IDLE state. Understand runner utilization with the new IDLE state that shows when runners are ready but not actively processing requests. * **IDLE state visibility** - see when runners finish processing and are waiting for new work * **Better resource monitoring** - distinguish between actively processing requests and waiting states * **Improved observability** - track idle time to optimize scaling and resource allocation See the new [Understanding Runners](/docs/serverless/deployment-operations/understand-runners) guide and [Optimizing Cold Starts](/docs/serverless/deployment-operations/optimize-cold-starts) guide for complete details on runner lifecycle, states, and performance optimization. **January 25, 2026** ## Control queue wait time with `start_timeout` You can now set a `start_timeout` on requests which ensures that when queue time is too long, the request is aborted without starting. See [Client Libraries → Start Timeout](/docs/model-apis/client#2-queue-management) for details. **January 21, 2026** ## Environments for isolated deployments Organize your applications, secrets, and configurations across different stages of your workflow with the new environments feature. * **Create isolated environments** for development, staging, and production * **Environment-scoped secrets** - use different API keys and credentials per environment * **Deploy to specific environments** using the `--env` flag ```bash theme={null} # Create a staging environment fal environments create staging # Deploy to staging fal deploy my_app.py --env staging # Set environment-specific secrets fal secrets set API_KEY=staging-key --env staging ``` See [environments documentation](/docs/serverless/deployment-operations/manage-environments) for details. **January 19, 2026** ## Handle graceful shutdown with `handle_exit()` and `teardown()` You can now define `handle_exit()` and `teardown()` methods in your app to handle graceful shutdown. * **`handle_exit()`** - Called when the runner is requested to terminate to signal handlers to stop early. * **`teardown()`** - Called when the runner is shutting down to clean up resources. See [lifespan docs](https://docs.fal.ai/serverless/getting-started/core-concepts#lifespan) for details. **January 13, 2026** ## Include local files in container builds with COPY and ADD > [!WARNING] > > **Experimental Feature** - This feature is currently experimental. You can now use standard Docker `COPY` and `ADD` commands to include local files in your container builds. * **Automatic file parsing** - fal parses your Dockerfile to find COPY/ADD commands and collects referenced files * **Hash-based deduplication** - Files are uploaded to fal's storage with content-addressable deduplication (files from `app_files` are reused automatically) * **.dockerignore support** - Create a `.dockerignore` file or use `add_dockerignore()` to exclude files * **Multi-stage build support** - `COPY --from=...` commands are correctly handled (only local files are collected) * **Smart rebuilds** - Changes to your `fal.App` file don't trigger rebuilds (it's pickled separately); only changes to COPY/ADD referenced files trigger rebuilds Example: ```python theme={null} dockerfile_str = """ FROM python:3.11 WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY src/ ./src/ """ class MyApp(fal.App): image = ContainerImage.from_dockerfile_str(dockerfile_str) ``` See [custom container image docs](https://docs.fal.ai/serverless/development/use-custom-container-image#using-copy-and-add-commands). **January 9, 2026** ## Skip retries for specific conditions You can now skip retries for specific conditions using the `skip_retry_conditions` option. ```python theme={null} class MyApp(fal.App): skip_retry_conditions=["timeout"] # This app won't retry on timeout ... ``` Available conditions: `"server_error"`, `"timeout"`. See [retry policy docs](https://docs.fal.ai/serverless/getting-started/core-concepts#retry-policy) for details. **January 7, 2026** ## Graceful shutdown of fal apps Starting with `fal>=1.61.0`, runners now receive a `SIGTERM` signal when terminated and are given a **5-second grace period** to complete ongoing requests before being forcefully terminated with `SIGKILL`. This applies to all termination scenarios: expiration, manual stop/kill, and scaling down. Use the `teardown()` method to handle cleanup during this grace period. See [lifespan docs](https://docs.fal.ai/serverless/getting-started/core-concepts#lifespan) for details. **December 22, 2025** ## Add a health check endpoint to your application Add a health check endpoint to your application to automatically replace unhealthy runners. * **Health check endpoint** - Pass the `health_check` parameter to the `@fal.endpoint()` decorator to configure an endpoint as your health check * **Periodic checks and recovery** - fal periodically (every 15 seconds) calls this endpoint and replace unhealthy runners if it fails for a few consecutive calls Example: ```python theme={null} class MyApp(fal.App): @fal.endpoint("/health", health_check=fal.HealthCheck(failure_threshold=3)) def health(self) -> HealthResponse: if not self.connection.is_alive(): raise RuntimeError("Lost connection to the external service") return HealthResponse(status="ok") ``` See [health check endpoint docs](https://docs.fal.ai/serverless/development/add-health-check-endpoint). **December 22, 2025** ## Disable environment build cache You can now disable the environment build cache by passing the `--no-cache` flag to the `fal deploy` or `fal run` command. See [custom container image docs](https://docs.fal.ai/serverless/development/use-custom-container-image#disable-build-cache). **November 25, 2025** ## Scale your application with the new scaling delay feature Scale your application with the new scaling delay feature. * **Scaling delay** - the amount of seconds the system will wait for a request to be picked up by a runner before triggering a scale up of a runner Example: ```python theme={null} class MyApp(fal.App): scaling_delay = 30 # ... ``` See [scaling docs](https://docs.fal.ai/serverless/deployment-operations/scale-your-application#scaling-delay). **November 17, 2025** ## Reduce cold start times with shared compiled PyTorch caches Dramatically reduce cold start times for torch.compile() models with the new inductor cache utilities. * **Load pre-compiled CUDA kernels** in \~2 seconds instead of recompiling for 20-30 seconds on each worker * **GPU-specific caching** automatically organized by GPU type (H100, H200, A100) * **Two usage patterns**: Manual control with `load_inductor_cache()` / `sync_inductor_cache()` or automatic with `synchronized_inductor_cache()` context manager * **Persistent shared storage** at `/data/inductor-caches//.zip` * First worker compiles and shares, subsequent workers load instantly Example: ```python theme={null} from fal.toolkit import synchronized_inductor_cache with synchronized_inductor_cache("mymodel/v1"): self.model = torch.compile(self.model) self.warmup() # Compilation happens once, synced automatically ``` See [compilation cache docs](https://docs.fal.ai/serverless/optimizations/optimize-startup-with-compiled-caches). **November 14, 2025** ## Get Slack notifications for serverless app failures Never miss critical issues with instant Slack alerts for your serverless applications. * **Connect your workspace** with one-click OAuth installation * **Choose notification channel** from a dropdown of your Slack channels * **Instant alerts for**: * App startup failures and timeouts * Critical platform issues * Real-time error notifications * **Team visibility** - everyone in the channel sees important updates * Configure at `https://fal.ai/dashboard/notifications/settings` **November 4, 2025** ## Stop and kill runners directly from the dashboard No more switching to the CLI to manage your runners. You now have full lifecycle control right from the dashboard. * **Graceful shutdown** or **force kill** runners with a single click * Access at `https://fal.ai/dashboard/apps/{username}/{appname}/runners` ## Stream platform logs to your own endpoint with drains Integrate fal's logging with your existing observability stack using the new Serverless Drains feature. * **Automatic log forwarding** from apps, runners, and file operations in NDJSON format * Works with Datadog, Splunk, Elasticsearch, or any HTTP endpoint * Configure at `https://fal.ai/dashboard/drains` **November 2, 2025** ## Upload larger files with improved timeout handling We've significantly improved the reliability of file uploads from URLs, especially for large datasets and model files. * **Extended timeout to 10 minutes** for `fal files upload` and `fal files upload-url` * Upload multi-GB files without timeout errors * See [`fal files` docs](https://docs.fal.ai/serverless/cli/files) **November 1, 2025** ## Restart all runners without redeploying Apply environment changes or recover from bad states instantly with the new `fal apps rollout` command. * **Restart all runners** for an app without creating a new deployment * **Graceful by default** (runners finish current requests) or use `--force` for immediate restart * Pick up new secrets, environment variables, or clear memory issues * See [`fal apps rollout` docs](https://docs.fal.ai/serverless/cli/apps/rollout) ## Stop specific runners without affecting others Target individual runners for maintenance with graceful shutdown via `fal runners stop`. * Stop specific runners without affecting others, useful for targeted maintenance * See [`fal runners` docs](https://docs.fal.ai/serverless/cli/runners) ## Debug production runners with interactive shell access Jump directly into any running container to troubleshoot issues in real-time with `fal runners shell`. * **SSH-like access** to inspect files, environment variables, and dependencies * Debug production issues without redeploying * See [`fal runners shell` docs](https://docs.fal.ai/serverless/cli/runners#shell) **October 31, 2025** ## See everything happening in your app with the events timeline Complete activity history for runners, deployments, and config changes in one place. * **Unified timeline** of runner events, deployments, and config changes * Access at `https://fal.ai/dashboard/apps/{username}/{appname}/events` **October 25, 2025** ## Get from zero to deployed in minutes with in-app onboarding New interactive guide walks you through your first serverless deployment step-by-step. * **Step-by-step walkthrough** from installation to deployment with copy-paste examples * Access at `https://fal.ai/dashboard/serverless-get-started` **October 22, 2025** ## Delete files from fal storage Remove files and directories with the new `fal files rm` command. * **Recursive deletion**: `fal files rm path/to/file-or-directory` * See [`fal files` docs](https://docs.fal.ai/serverless/cli/files) **October 21, 2025** ## Platform APIs v1 officially released Programmatically manage your model deployments with the new Platform APIs. * **Model discovery** - search and metadata retrieval for 600+ models * **Pricing and cost estimation** - real-time pricing information * **Usage tracking** - detailed line items with quantities and prices * **Analytics** - request counts, error rates, and latency percentiles * Available at `https://api.fal.ai/v1` - see [docs](https://docs.fal.ai/platform-apis) ## Get notified when you hit concurrent requests limits Never wonder why requests are queuing—we now send notifications when you reach your concurrency limit. * **Email and dashboard notifications** with smart throttling (immediate, 1h, 1d, weekly) * **Limit value included** in 429 responses for programmatic handling ## Debug errors faster with the new errors page Comprehensive error analytics to identify and resolve issues quickly. * **Server vs client error rates** with 4xx/5xx breakdown and sparklines * **Error timeline** with status code distribution and endpoint-level breakdown * Access at `https://fal.ai/dashboard/apps/{username}/{appname}/errors` **October 20, 2025** ## Stop or kill individual runners from the command line Precise control over each runner's lifecycle without touching the dashboard. * **`fal runners stop`** - gracefully stop a runner, allowing in-flight requests to complete * **`fal runners kill`** - immediately terminate a runner without waiting * See [`fal runners` docs](https://docs.fal.ai/serverless/cli/runners) **October 16, 2025** ## See exactly how long runners spend starting up Identify GPU availability bottlenecks and optimize cold start times. * **Pending uptime metrics** show how long runners wait before becoming active * Track PENDING, DOCKER\_PULL, and SETUP state durations separately **October 15, 2025** ## Connect fal docs to Cursor with MCP Access the complete fal documentation directly in Cursor using Model Context Protocol. * **Complete documentation in your IDE** with AI-powered suggestions * Simple setup: add fal MCP server to your `mcp.json` - see [guide](https://docs.fal.ai/model-apis/mcp) ## Personalized dashboard with creator and developer views The dashboard now adapts to your workflow with two distinct experiences. * **Creator view** - gallery-focused with favorite models and visual generation history * **Developer view** - metrics-driven with usage stats, error tracking, and API analytics * **Quick stats** showing credits, requests, and errors with sparklines **October 13, 2025** ## Add custom headers to your API requests Integrate seamlessly with analytics, auth, and middleware by passing custom HTTP headers. * Add custom headers for analytics, authentication, or middleware integration * Works with all client libraries ## Multi-GPU inference and training with fal.distributed Scale AI workloads across multiple GPUs with the new `fal.distributed` module. * **Data parallelism** - generate multiple outputs simultaneously (e.g., 4 images on 4 GPUs) * **Model parallelism** - split large models across GPUs for faster generation * **Distributed training** - synchronized gradient updates with DDP * Supports 2, 4, or 8 GPU configurations on H100s and A100s * See [distributed docs](https://docs.fal.ai/serverless/distributed/overview) **October 10, 2025** ## Dedicated pages for Analytics, Runners, Logs, and Versions Complete app details redesign gives each deployment aspect its own focused view. * **New Analytics page** - runner-focused metrics with date range filtering * **New Runners page** - app-scoped runner view with enhanced filters * **New Logs page** - dedicated log viewer for debugging * **New Versions page** - manage and view app revisions * **Enhanced Overview** - endpoint stats and performance metrics at a glance **October 9, 2025** ## Compare models side-by-side in the new Sandbox Find the perfect model by testing multiple options in parallel with the same prompt. * Run multiple models simultaneously with the same prompt * Available at `https://fal.ai/sandbox` **October 8, 2025** ## Manage deployments from Python without async/await New synchronous client makes serverless management feel just like the CLI. * Manage apps, runners, and deployments programmatically without async/await * Same API as CLI: `client.apps.*`, `client.runners.*`, `client.deploy()` * See [Python client docs](https://docs.fal.ai/serverless/python/client) **October 6, 2025** ## Bring your own container to any deployment Full control over your runtime environment with custom Docker images. * Use `ContainerImage.from_dockerfile_str()` or `ContainerImage.from_dockerfile()` * Install any dependencies, tools, or system packages you need * See [custom containers guide](https://docs.fal.ai/serverless/development/use-custom-container-image) **October 3, 2025** ## Dynamic auto-scaling with percentage-based buffers Scale more intelligently by setting concurrency buffers as percentages instead of fixed numbers. * Configure buffer as a percentage of current concurrency for dynamic scaling * See [scaling docs](https://docs.fal.ai/serverless/deployment-operations/scale-your-application) ## Runner logs with streaming and filtering Real-time log streaming and powerful filtering for faster debugging. * **Stream logs in real-time** with `fal runners logs --follow` * **Filter by time range** with `--since` and `--until` * **Search logs** with `--search` parameter * **Scrollable and searchable** in the dashboard with SSE-powered updates * See [`fal runners logs` docs](https://docs.fal.ai/serverless/cli/runners#logs) ## Include local files in your deployments automatically Bring configs, utilities, and code from your local machine into serverless apps. * Specify files with relative or absolute paths to include at runtime * Works with `fal run` and `fal deploy` * See [app files docs](https://docs.fal.ai/serverless/development/app-files) ## Find what you need faster with reorganized navigation Clearer dashboard structure groups features by workflow: Generate, Serverless, and Manage. * **Generate** group: Sandbox, Model Gallery * **Serverless** group: Apps, Logs, Files, Runners * **Manage** group: Usage, Billing, API Keys, Webhooks, Team Members **October 2, 2025** ## Know exactly which version each runner is running Track deployments better with revision IDs shown on every runner. * **Revision ID displayed** on runners to track which version is running * **State renamed**: "DEAD" → "TERMINATED" for clarity **October 1, 2025** ## Filter logs with custom labels and powerful queries Find what you need instantly with EXACT/CONTAINS matching and multi-condition filters. * **EXACT or CONTAINS** matching for label values * **Multiple conditions** with OR logic (e.g., `status IN ["error", "warning"]`) * Available in dashboard and API * Examples: `error_type = "ValidationError"`, `endpoint CONTAINS "/api/v2/"` ## See what runners are doing during startup Track exactly where runners are in the startup process—pending, pulling images, or setting up. * `fal runners list` now shows PENDING, DOCKER\_PULL, and SETUP states * Understand deployment progress in real-time ## View all app endpoints and config at a glance Redesigned app details page surfaces the information you need most. * Endpoints, configuration, and status all in one place **September 27, 2025** ## Monitor and clear your request queue from the CLI Check how many requests are queued and flush them when needed. * `fal queue size app_name` - check queue size for an app * `fal queue flush app_name` - flush all pending requests * See [`fal queue` docs](https://docs.fal.ai/serverless/cli/queue) **September 10, 2025** ## View runner history with time-based filtering See terminated runners and filter by state to debug failures. * `fal runners list --since "1h"` - view runners from the last hour (max 24h) * `fal runners list --state dead` - filter by state (running, pending, setup, dead) * Helpful for debugging failed deployments and understanding runner lifecycle * See [`fal runners list` docs](https://docs.fal.ai/serverless/cli/runners#list) **August 29, 2025** ## Reorganize files in fal storage without re-uploading Move and rename files instantly with the new `fal files mv` command. * Rename or move files in fal storage: `fal files mv source destination` * See [`fal files` docs](https://docs.fal.ai/serverless/cli/files) **August 26, 2025** ## See all your endpoint URLs immediately when testing No more guessing which URL to use—CLI shows playground, sync, and async routes for every run. * CLI prints playground, synchronous, and asynchronous routes for `fal run` # Access and pricing Source: https://fal.ai/docs/documentation/agent/access-and-pricing How to access fal Agent, what optional credit plans include, and what fal bills for. fal Agent is in Early Access. Access is enabled by default for signed-in accounts. You do not need a credit plan or an Enterprise contract to use fal Agent. Account and organization restrictions still apply. Sign in at [fal.ai/agent](https://fal.ai/agent). If prompted, complete account setup. ## Optional Credit Plans Credit plans provide monthly credits. They are not required for Agent access. The credits work across every fal product. fal spends them before pay-as-you-go rates, and unused credits roll over each month. | Plan | Price | Monthly credits | Discount | | :- | :- | :- | :- | | **fal Agent Starter** | \$50 / month | \$50 | No discount | | **fal Agent Pro** | \$200 / month | \$200 | 5% off UI, Sandbox, Playground, and CLI usage | | **fal Agent Max** | \$1,000 / month | \$1,000 | 10% off UI, Sandbox, Playground, and CLI usage | | **Enterprise** | Custom | Custom volume | Custom rates | You can cancel at any time. Plan benefits continue until the end of the paid period. Previously purchased credits are not affected. Canceling a plan does not remove Agent access. The discount does not apply to API usage, which is always pay-as-you-go. > [!NOTE] > > Self-service credit plans are for eligible personal accounts with billing access. > > * Team or organization accounts are ineligible. > * Enterprise accounts are ineligible. > * Invoiced accounts are ineligible. > * Accounts billed through a parent account are ineligible. > * Accounts billed through GCP are ineligible. > * Accounts billed through Vercel are ineligible. > * Active pricing agreements can prevent credit plan purchases. > > These are billing restrictions, not Agent access requirements. ## What fal bills for fal bills **model runs only**. Every generation the agent submits is a normal fal model run. It is charged at the model's rate against your credits, then at pay-as-you-go rates. Everything else in fal Agent is free to use. This includes the agent's reasoning, the sandbox, web search and URL reading, and video understanding. fal covers these costs for now. The spend chip next to the composer shows the running cost of the chat, split by model and by media type. [Spending caps](/docs/documentation/agent/spending-caps) ask you to confirm runs above a threshold. ## Model access The agent can only run models that your account can call through the API. If your organization restricts a model, the agent does not see it or suggest it. It also refuses to run the model when you mention it directly. See [Access controls](/docs/documentation/organizations/access-controls). ## Complimentary credits fal gives select filmmakers, creators, studios, and agencies complimentary credits to build with fal Agent. Selected applicants receive up to \$1,000 in credits. Applications are reviewed on a rolling basis, and selection is not guaranteed. Apply at [fal.ai/agent-access/claim](https://fal.ai/agent-access/claim). ## What happens without access Signed-out visitors see the fal Agent landing page with a live composer. Prompts entered before signing in are saved so you can continue after sign-in, if your account has access. If access is disabled for your account or organization, fal Agent shows an access-denied message. Contact your organization administrator or fal support. Buying a credit plan does not override an access restriction. # Assets and characters Source: https://fal.ai/docs/documentation/agent/assets-and-characters Reuse library media in chats, organize collections, and reference characters and smart entities. fal Agent uses [fal Assets](/docs/documentation/assets), your media library on fal. Open the library at [fal.ai/assets](https://fal.ai/assets). Assets access follows your account's enablement and organization policy. This page covers using Assets in a chat. For the full library guide, start with [Introduction to fal Assets](/docs/documentation/assets). ## Automatic registration Supported media attachments are registered as library uploads, and generated media is linked to its chat. The Assets browser displays images, video, audio, and 3D. Agent documents have their own [project workflow](/docs/documentation/agent/projects/memory). Open Assets, or use the `@` picker's **Assets** tab, to find available media from earlier work. Media remains subject to its retention policy. ## Reuse in a chat * Type `@` and open the **Assets** tab to attach any library item. * Open **Generations** in the palette to refer to an output from this chat. * Drag a tile from the media rail into the composer, or use **Attach to chat** on the tile. ## Search The agent can search your library on your behalf. It searches by text, by image similarity, and by video similarity. Ask for what you remember: ```text theme={null} Find the warehouse shots from last week and use the widest one as the background. ``` ## Collections A collection is a named group of assets. The agent can create collections, add assets to them, and list what they hold. Add a collection to a project to make its contents part of the project context. ## Characters and smart entities Assets supports **characters, props, environments, styles, and scenes**. Each smart entity has one to twenty reference images and an `@handle`. Characters also require a description. Select an entity from the `@` picker to give the agent reusable visual references for a generation. References help guide the result. Consistency depends on the selected model and its inputs. See [Characters and smart entities](/docs/documentation/assets/entities) for the entity types and [Using entities in generations](/docs/documentation/assets/entities/using) for model-specific behavior. ```text theme={null} Put @mara in a rain-soaked alley at night, then animate a slow dolly-in. ``` The agent can create a character for you from images in the chat, or you can create one in Assets. Character cards in the chat show the portrait, the handle, the bio, and the collections the character appears in. The **character-design** [skill](/docs/documentation/agent/skills) adds reference sheets, expression sheets, and outfit variations. ## Media lifetime Files follow the lifetime applied to them. See [Agent retention](/docs/documentation/agent/retention) for chat policies and [Assets retention and deletion](/docs/documentation/assets/retention) for the difference between removing library items and deleting media files. # Composer and references Source: https://fal.ai/docs/documentation/agent/chats/composer Reference models, generations, assets, characters, skills, and connected apps from one palette. Attach files, drag and drop, and paste. The composer is where you talk to the agent. It supports references through the `@` palette, file attachments, drag and drop, and long-text paste. ## The `@` palette Type `@` anywhere in the composer, or click the **+** button, to open the palette. It searches models, generations, characters, and skills at once, and it groups results into sections. | Section | What it holds | | :- | :- | | **Attach files** | Upload images, video, audio, or ZIP archives | | **Generations** | Named runs from this chat, to use as the input for the next step | | **Models** | Pin a model, or pick several to compare | | **Assets** | Your [fal Assets](/docs/documentation/agent/assets-and-characters) library | | **Characters** | Reusable identities | | **Skills** | Force a [skill](/docs/documentation/agent/skills) for this turn | | **Connectors** | A [connected app](/docs/documentation/agent/tools/connectors) | ![The composer palette with its sections: Attach files, Generations, Models, Assets, Characters, Skills, and Connectors](https://mintcdn.com/fal-d8505a2e/DmEWlE6WV9vaz0Me/images/agent/composer-palette.png?fit=max\&auto=format\&n=DmEWlE6WV9vaz0Me\&q=85\&s=f8e482d9169b2fca5a2da6fc2ec4711c) Use the arrow keys to move, `Enter` to select, `Backspace` to go back to the list, and `Escape` to close. A picked item becomes a chip in the composer. ### Inside a section Each section opens as a list with its own search. **Generations** shows the named runs from this chat with the model that made them. **Models** lists models with a modality filter. **Skills** lists every enabled skill. ![The Generations section of the palette listing two named runs with their model and media type](https://mintcdn.com/fal-d8505a2e/DmEWlE6WV9vaz0Me/images/agent/palette-generations.png?fit=max\&auto=format\&n=DmEWlE6WV9vaz0Me\&q=85\&s=51de3c4987785d4e8ad61c3a5d0d4604) ![The Models section of the palette with a modality filter and a list of models tagged by task](https://mintcdn.com/fal-d8505a2e/DmEWlE6WV9vaz0Me/images/agent/palette-models.png?fit=max\&auto=format\&n=DmEWlE6WV9vaz0Me\&q=85\&s=22d8078a91362c9ca3901e6567e3dd36) ![The Skills section of the palette listing enabled skills with their descriptions](https://mintcdn.com/fal-d8505a2e/DmEWlE6WV9vaz0Me/images/agent/palette-skills.png?fit=max\&auto=format\&n=DmEWlE6WV9vaz0Me\&q=85\&s=bf15e016aaa8d9af746f05beb2638405) A character chip carries the identity into the prompt, so you do not describe the character again. ### Generation references Every completed output gets an ordinal in the order it landed. When the agent names a run, it also gets a readable name, such as `cdg-bag-environments/open-field`. Both appear in the media viewer header. Pick a generation from the palette when you want an output as the input for the next step: ```text theme={null} Upscale the open-field shot and then animate it with a slow push-in. ``` ### Model pins The model chip under the composer shows **Auto** when no model is pinned. Pick a model from the palette to pin it for the message. Remove the chip to return to Auto. See [Models and generation](/docs/documentation/agent/models-and-generation). ## Attachments Click the attachment button or drag files into the chat. The agent uses attachments as references, edit sources, or context. | Type | Formats | Size limit | | :- | :- | :- | | Image | JPEG, PNG, WebP, GIF | 50 MB | | Video | MP4, WebM, QuickTime | 500 MB | | Audio | MP3, WAV, OGG, FLAC, M4A, AAC | 50 MB | | Document | PDF, DOCX, TXT, Markdown, CSV, TSV, JSON | 25 MB | | Code and text | YAML, XML, HTML, CSS, JS, TS, Python, Go, Rust, Java, Ruby, shell scripts | 25 MB | | Archive | ZIP, for training datasets | 2 GB | A message can carry up to 20 attachments. Uploads retry automatically. Drafts, including attachments, are saved in the browser and survive a reload. > [!NOTE] > > 3D files cannot be attached to a chat message. When you drop them on a project, they are saved to the project only. ## Drag and drop Where you drop a file decides where it goes. | Drop target | Result | | :- | :- | | Chat body | The file attaches to the message | | Media rail, scope **This chat** | The file attaches to the message and is saved to the project library | | Media rail, scope **Project** | The file is saved to the project. A dialog asks **Attach to this chat too?** | | Project page | Documents become project context. Media joins the project's Assets | In a chat without a project, files always attach to the message. ZIP files always attach to the chat and never enter a project library. ## Paste * A pasted **fal media URL** becomes an attachment with a link chip. * Any other pasted **URL** becomes a link chip. The URL stays in the message so the agent can read the page. * Pasted **text** longer than 2,000 characters or 25 lines becomes a document attachment named `Pasted text.txt`. ## Send or queue `Enter` sends the message. If the agent is busy, the message waits and runs next. `Alt+Enter` adds the message to the queue instead, so it runs after the current work. See [Queue and steering](/docs/documentation/agent/chats/queue). # Chat interface Source: https://fal.ai/docs/documentation/agent/chats/interface The fal Agent shell: sidebar, chat, media rail, history, turn navigation, keyboard shortcuts, notifications, and the installable app. fal Agent uses one shell for everything. Chats, projects, skills, history, and settings all render inside it. The shell has three columns. | Column | Contents | | :- | :- | | **Sidebar** (left) | New chat, History, Skills, Projects, Settings, and your recent chats grouped by date | | **Chat** (center) | The conversation, generations, plan cards, and the composer | | **Media rail** (right) | Every input and output of the chat, or of the whole project | The sidebar can collapse to icons, and the rail can open, close, or expand. Both states are saved to your account. ![The fal Agent shell with the sidebar, a chat with generations, and the media rail](https://mintcdn.com/fal-d8505a2e/DmEWlE6WV9vaz0Me/images/agent/chat-shell.jpg?fit=max\&auto=format\&n=DmEWlE6WV9vaz0Me\&q=85\&s=48d132c27a1a534751dec22acefc0787) ## Start a chat Click **New chat** or open [fal.ai/agent](https://fal.ai/agent). The empty state greets you by name and shows starter cards. Each card loads a full prompt, and some also load a sample image. Click **Shuffle** for a new set. The `/agent` URL returns you to the last view you used. Deep links with `?endpoint=` open a chat with a model pinned. ## Chat titles The agent names each chat from your first message, in your language. To rename a chat, open **History**, click the title, edit it, and press `Enter`. ## History **History** lists every chat with search. Hover a row to preview its recent media. Rows show **Unread updates** when a run landed while you were away, and **Needs approval** when a plan checkpoint or a cost approval is waiting. Delete a chat from its row. Deletion asks for confirmation. ## Turn navigation A rail of dots on the right edge of the chat marks each turn. Hover a dot to preview that turn's prompt and up to four output thumbnails. Click it to jump there. ## The media rail The rail mirrors the chat's media as a grid. Controls at the top: * **Scope**: **This chat** or **Project**. The project scope is available when the chat belongs to a [project](/docs/documentation/agent/projects). * **Kind**: **Media** or **Context**. Context shows project memory notes and documents. * **Filters**: All media, Image, Video, Audio, 3D, and Favorites. * **Search**: filters tiles by prompt, model, and name. The media panel separates **Attachments** (your inputs) from **Outputs**. See [Generations and the media rail](/docs/documentation/agent/generations/overview) for tile actions. ## Keyboard shortcuts | Shortcut | Action | | :- | :- | | `Enter` | Send. The message runs next | | `Shift+Enter` | New line | | `Alt+Enter` (`Option+Enter`) | Add to queue. Runs after the current work | | `Tab` | Accept the suggested prompt shown as ghost text | | `Escape` | Stop the running turn. Press twice to confirm | | `Cmd+Enter` / `Ctrl+Enter` | Submit a plan card revision | | `@` | Open the composer palette | | `Cmd+click` / `Ctrl+click` | Add a tile to a multi-selection in the grid or rail | ## Prompt suggestions After a turn, the composer shows a suggested follow-up as ghost text. Suggestions rotate and are specific to what you just made. Press `Tab` to accept one. ![The composer showing two suggested follow-up prompts with Tab to use, the Auto model chip, and the spend chip](https://mintcdn.com/fal-d8505a2e/DmEWlE6WV9vaz0Me/images/agent/composer-suggestions.png?fit=max\&auto=format\&n=DmEWlE6WV9vaz0Me\&q=85\&s=d1c8e23cc9d65d2059459c1cf2fd967d) ## Notifications When a turn finishes while the tab is in the background, the browser shows a notification. Click it to jump back to the chat. This is on by default. Turn it off in **Settings → Notifications**. The browser asks for permission on your first turn. ## Install as an app fal Agent is an installable web app. Use your browser's **Install** action to add it to your dock or home screen. The app opens in its own window and offers **New chat**, **Chats**, and **Projects** shortcuts. It works on iOS and Android with a mobile layout. The app needs a network connection. It does not cache chats offline. # Queue and steering Source: https://fal.ai/docs/documentation/agent/chats/queue Send messages while the agent works, queue follow-ups, stop a running chain, and cancel generations. A chat runs one turn at a time. Everything else waits in a queue that you can see and edit. The queue has two lanes. | Lane | How rows get there | Priority | | :- | :- | :- | | **Your messages** | You press `Enter` while a turn runs | Always run first, in order | | **Queued work** | You press **Add to queue**, or the agent schedules a continuation or a plan step | Run after your messages | ## Send while the agent works Press `Enter` while a turn is running. The message appears in the chat with an **Up next** badge and runs as soon as the current turn settles. The agent reads the queue before it continues, and it reconciles queued work that your new message makes stale. It can edit, remove, or reorder its own queued rows. It never touches your messages. ## Add to queue Press `Alt+Enter` (`Option+Enter`) or click **Add to queue**. The message goes to the queued work lane. Use this for follow-ups that must wait for the current result, such as "then export everything as a zip". ## The queue drawer The queue drawer sits behind the composer and lists **Queued requests**. It rises as rows are added. For each row you can: * Drag it to reorder, or use move up and move down. * Edit its text. * Cancel it. A separator, **Runs after your requests**, marks where your pending messages end and queued work begins. Each row shows a phase. **Waiting for source** means the row needs a previous run to land. **Approval waiting** means a checkpoint blocks it. **Chain halted** means you stopped the chain. **Ready** rows dispatch next. ## Plan steps in the queue When a [plan](/docs/documentation/agent/plan-cards) runs, every remaining step becomes a queue row. Removing a step removes the steps that depend on it. Approval checkpoints hold their row until you approve. ## Stop The send button becomes a stop button while a turn runs. `Escape` triggers it. Press `Escape` twice to confirm. Stop escalates in two presses: 1. **Halt the chain.** Queued rows stay in the drawer but do not dispatch. Continuations from landed runs wait. 2. **Cancel generations.** In-flight runs are cancelled. Their cells show **Cancelled**. Dependent rows are parked with **Source run stopped** rather than deleted. To resume a halted chain, send a message or click resume in the drawer. Resume clears the halt on every waiting row at once. ## Cancel one generation Hover an in-flight cell and click the cancel button. Only that run stops. The rest of the batch continues. ## Cost approvals A run that exceeds your [spending cap](/docs/documentation/agent/spending-caps) waits for approval. While it waits, the agent cannot submit more runs in that chat. Approve or reject it in the chat. # Sharing and forking Source: https://fal.ai/docs/documentation/agent/chats/sharing Share a read-only view of a chat with a link, restrict the audience, set an expiry, and fork a chat from any message. ## Share a chat Click **Share** in the chat header, or choose **Share chat** from a message's actions. fal Agent creates a share link at `fal.ai/chat/share/`. Viewers see a read-only copy of the chat with its generations. ![The Share chat dialog with the share link, the Base access selector, and the Link expires selector](https://mintcdn.com/fal-d8505a2e/DmEWlE6WV9vaz0Me/images/agent/share-dialog.png?fit=max\&auto=format\&n=DmEWlE6WV9vaz0Me\&q=85\&s=fb6cb372c6fa8dfd6961b0aca8b70189) ### Base access | Option | Who can open the link | | :- | :- | | **Everyone with link** | Anyone | | **Team** | Members of your team, or specific email addresses | | **Org** | Members of your organization, or specific email addresses | | **Restricted** | Only the people you list | ### Expiry Set the link to expire **Never**, **In 1 day**, **In 7 days**, or **In 30 days**. You can revoke a share at any time from the share dialog. ## Fork a chat Hover a message from the agent to show its actions. Choose **Fork from here**. A new chat starts with the history up to that message. The original chat is unchanged. Use a fork to try a different direction without losing the current thread. ![Message actions under an agent reply: copy, thumbs up, thumbs down, Fork from here, and share](https://mintcdn.com/fal-d8505a2e/DmEWlE6WV9vaz0Me/images/agent/fork-from-here.png?fit=max\&auto=format\&n=DmEWlE6WV9vaz0Me\&q=85\&s=753f35ba49b293288c0dba4e15267da0) The same row holds **Copy**, feedback buttons, and **Share chat**. ## Examples fal publishes a few example chats at `fal.ai/agent/example/`. They are visible to visitors who are signed out or do not have access yet, and show what a full session looks like. # FAQ Source: https://fal.ai/docs/documentation/agent/faq Common questions about fal Agent access, models, cost, limits, and programmatic use. > [accordion] Which models can the agent use? > > Every model in the fal catalog that your account can call. The catalog refreshes every few minutes. Restricted models are hidden from the agent and cannot be run by mention. See [Models and generation](/docs/documentation/agent/models-and-generation). > [accordion] Can I choose the model myself? > > Yes. Type `@` in the composer, open **Models**, and pick one. You can also pin a model on a plan card step. A pinned model is final. Without a pin, the agent chooses. > [accordion] How much does a chat cost? > > You pay for model runs at normal fal rates against your credits. Nothing else is billed. The agent's reasoning, the sandbox, web search, and video understanding are free to use for now. The spend chip next to the composer shows the running total. See [Access and pricing](/docs/documentation/agent/access-and-pricing). > [accordion] How do I stop the agent from spending too much? > > Set a safety cap in **Settings → Spending caps**. Runs above the cap ask for confirmation. Videos and audio ask by default. See [Spending caps](/docs/documentation/agent/spending-caps). > [accordion] Why did the agent stop in the middle of a task? > > A turn has a step limit of about 60 tool calls. Long tasks pause with a message. Send another message to continue. A plan checkpoint or a cost approval also pauses the run until you approve. > [accordion] Can the agent edit my image without regenerating it? > > Yes. Pixel-exact edits such as crop, resize, brightness, background removal, and captions run as code in the [sandbox](/docs/documentation/agent/tools/sandbox). Mark the region in the [media viewer](/docs/documentation/agent/generations/media-viewer) to point at the part to change. > [accordion] Where do my files go? > > Every input and output is saved to your fal Assets library and linked to its chat. See [Assets and characters](/docs/documentation/agent/assets-and-characters) and [Retention](/docs/documentation/agent/retention). > [accordion] Can my team share a project? > > Chats can be shared with your team or organization as read-only links. See [Sharing and forking](/docs/documentation/agent/chats/sharing). Shared editable projects are not available yet. > [accordion] Is there an API or SDK for fal Agent? > > Not yet. fal Agent is available in the browser at [fal.ai/agent](https://fal.ai/agent). For programmatic generation today, use the [Model APIs](/docs/documentation/model-apis/overview), the [MCP server](/docs/documentation/setting-up/mcp), or the [genmedia CLI](/docs/documentation/setting-up/genmedia). > [accordion] Does fal Agent work on mobile? > > Yes. The site has a mobile layout, and you can install it as an app from your browser. See [Chat interface](/docs/documentation/agent/chats/interface#install-as-an-app). > [accordion] What file types can I attach? > > Images, video, audio, documents, common code and text formats, and ZIP archives for training data. See the full table in [Composer and references](/docs/documentation/agent/chats/composer#attachments). > [accordion] How do I get help? > > Use the [fal Discord](https://discord.gg/fal-ai) or contact [support](/docs/documentation/model-apis/support). Include the chat link and the request ID from the tile's details when a run fails. # Export Source: https://fal.ai/docs/documentation/agent/generations/export Download one generation, or export every completed generation in a chat as one ZIP with a folder per batch. ## Download one file Hover a cell and click **Download**, or use the download control in the [media viewer](/docs/documentation/agent/generations/media-viewer). The file saves directly. 3D outputs offer a format menu. To download several tiles from the media rail, `Cmd+click` (`Ctrl+click`) to select them, then use the selection actions. ## Export a chat as a ZIP Ask the agent to export. For example: ```text theme={null} Export all the videos from this chat as a zip. ``` The agent builds the archive in the sandbox and shows an **export card** in the chat. The card lists the archive name, the file count, the total size, and a **Download** button. Expand it to see the folder tree. ### Archive layout The root folder is the chat title. Inside, each named batch is a folder, and each run is a file named by its variant. Unnamed runs use their ordinal. ```text theme={null} product-hero-shots/ hero-shot/ dusk.png morning.png animation/ gen-4.mp4 manifest.json ``` `manifest.json` lists every file with its prompt, model, and request ID. ### What is included * Completed generations with a permanent URL. * Filtered by batch name or media type when you ask for a subset. Not included: your uploads, failed runs, and video sequences. A [video sequence](/docs/documentation/agent/tools/video-sequences) is an arrangement, not a file. Export the sequence first to get a file. ### Limit One archive holds up to 200 files. For a larger chat, export by media type or by batch. # Media viewer Source: https://fal.ai/docs/documentation/agent/generations/media-viewer Open any generation full screen, zoom, inspect the request, mark it up, and send an edit straight back to the agent. Click a tile to open the media viewer. It shows one generation at full size with a filmstrip of the others in the chat. The header shows the ordinal, the name, the format, and the dimensions. ![The media viewer with the filmstrip, the image toolbar on the left, and the edit composer at the bottom](https://mintcdn.com/fal-d8505a2e/DmEWlE6WV9vaz0Me/images/agent/media-viewer.jpg?fit=max\&auto=format\&n=DmEWlE6WV9vaz0Me\&q=85\&s=5010b19e775ef8318c35d040d9c1f8dc) ## Controls | Control | Action | | :- | :- | | Previous and next | Move through the filmstrip | | Zoom | Zoom in and out on images. The reset control returns to 100% | | Favorite | Toggle the heart | | Request details | Open a panel with the endpoint, request ID, status, attempt, and duration. Use **Copy request id** when you contact support | | Close | Return to the chat. `Escape` also closes | ## Edit from the viewer The composer at the bottom of the viewer sends an instruction to the agent with the current image attached. Type an edit, or ask for a variation, without leaving the viewer. The left toolbar offers quick actions for image outputs. * **Edit** opens the markup canvas. See below. * **Quick animate** turns the still into a short video. * **Upscale** runs an upscaler on the image. * **Make a variation** asks for one or more new takes. A picker sets the count. ## Markup and crop **Edit** opens a drawing canvas over the image. Use it to point at the region you want changed. ![The markup canvas with pen, highlighter, eraser, arrow, text, and crop tools, and a red stroke drawn on the image](https://mintcdn.com/fal-d8505a2e/DmEWlE6WV9vaz0Me/images/agent/markup-canvas.jpg?fit=max\&auto=format\&n=DmEWlE6WV9vaz0Me\&q=85\&s=4a7adb71a4869e98484fe140375a5313) | Tool | Use | | :- | :- | | Pen and highlighter | Draw on the image. Pick a color from the swatch | | Eraser | Remove a stroke | | Arrow | Point at a region | | Text | Label a region | | Crop | Keep a region of the image | | Undo, redo, clear | Step back or start over | Click **Done**. The canvas is flattened to a PNG and placed in your composer as an attachment. Type what you want changed and send. The agent uses the marked image as the edit source. **Cancel** discards the marks. # Generations and the media rail Source: https://fal.ai/docs/documentation/agent/generations/overview How generations appear in the chat and the media rail, and what you can do with each tile. A generation is one model run's output. Generations appear twice: inline in the chat, at the point where the agent submitted them, and in the media rail on the right. ## In the chat Runs render as cells in a grid. A batch renders as one grid, laid out like a moodboard. In-flight cells show the model name and a cancel button. Completed cells show the media, a media-type badge, and on hover: | Action | Where | | :- | :- | | **Retry** | Top left. Runs the same input again | | **Download** | Top right. 3D outputs offer a format menu | | **Copy prompt** | Copies the prompt text | | **Copy input as JSON** | Copies the full model input | A toolbar also appears under a hovered cell. It offers **Attach**, **Quick animate**, **Upscale**, **Make a variation**, **Edit**, and **Details**. ![A generation cell with its ordinal and model pill, and the hover toolbar beneath it](https://mintcdn.com/fal-d8505a2e/DmEWlE6WV9vaz0Me/images/agent/tile-actions.jpg?fit=max\&auto=format\&n=DmEWlE6WV9vaz0Me\&q=85\&s=c08e7970114284e2a614d5e3cabf6d77) Videos play a preview on hover. Audio renders as a waveform tile. Files that are not media, such as a `.zip` or `.csv`, render as a file card with a download button. Retries are grouped in the same cell. Use **Previous attempt** and **Next attempt** to compare them. ![A batch of four generations in the chat, with the download button and model pill shown on the hovered cell](https://mintcdn.com/fal-d8505a2e/DmEWlE6WV9vaz0Me/images/agent/generation-grid.jpg?fit=max\&auto=format\&n=DmEWlE6WV9vaz0Me\&q=85\&s=8e5d07e49b92cb034ba00c44347cf59a) ## Names and ordinals Each completed output gets an ordinal in the order the runs landed. Your uploads and video sequences do not take an ordinal. When the agent names a batch, each run also gets a readable name, such as `cdg-bag-environments/open-field`. The media viewer header shows both. Use the **Generations** section of the `@` palette to refer to an output in your next message. ## The media rail The rail shows every tile in the chat, or in the whole project when the scope is **Project**. Filter by media type or **Favorites**, and search by prompt, model, or name. ![The media rail with Media and Context tabs, search, media-type filters, and the Attachments and Outputs sections](https://mintcdn.com/fal-d8505a2e/DmEWlE6WV9vaz0Me/images/agent/media-rail.jpg?fit=max\&auto=format\&n=DmEWlE6WV9vaz0Me\&q=85\&s=13c4ce3ce90c35bd692c6a8912c996d5) Tile actions, on hover or in the context menu: | Action | Effect | | :- | :- | | **Attach to chat** | Adds the tile as an attachment on your next message | | **Favorite** | Pins a heart on the tile. Favorites get their own filter | | **Preview** | Opens the [media viewer](/docs/documentation/agent/generations/media-viewer) | | **Jump to chat** | Scrolls the chat to the turn that made it | | **Remove from chat** | Removes the tile from this chat. This asks for confirmation and cannot be undone | `Cmd+click` (`Ctrl+click`) selects several tiles. An **Attach N** button then attaches all of them. ## Cost The spend chip next to the composer shows the number of generations and the total cost of the chat. Hover it for a breakdown by model or by media type. See [Spending caps](/docs/documentation/agent/spending-caps). ## Request details Open a tile's details to see the model, the endpoint, the request ID, the latency, and the attempt number. Use the request ID when you contact support about a run. ## Errors A failed cell shows a short explanation. The agent repairs and retries most failures on its own. See [Models and generation](/docs/documentation/agent/models-and-generation#errors-you-can-see) for the messages and what they mean. # Introduction to fal Agent Source: https://fal.ai/docs/documentation/agent/index fal Agent is an AI creative partner that plans and runs generative media work across every top image, video, audio, and 3D model on fal. fal Agent is a conversational creative partner. You describe what you want to make. The agent chooses the models, writes the prompts, and runs the generations. It keeps your references consistent from one step to the next. It works across the full fal model catalog. One chat can move from a still image to a video, to a sound bed, and to a 3D asset without a change of tool. fal Agent runs in the browser at [fal.ai/agent](https://fal.ai/agent). It is a product for creators, studios, and teams who want production-grade results without hand-picking a model for every step. > [!NOTE] > > fal Agent is in Early Access. Access is enabled by default for signed-in > accounts. You do not need a credit plan or an Enterprise contract to use fal > Agent. Account and organization restrictions still apply. See [Access and > pricing](/docs/documentation/agent/access-and-pricing). ## What fal Agent does * **Chooses and runs models.** The agent picks the model for the task, writes the inputs, and repairs failed runs. You can pin a model when you want a specific one. * **Plans multi-step work.** Larger requests become an editable plan card. You can rename steps, reorder them, pin models, and add approval checkpoints before anything runs. * **Keeps context.** Projects hold chats, media, documents, characters, and a shared memory. The agent recalls decisions and preferences across sessions. * **Edits with code.** A Python sandbox with ffmpeg, Pillow, and a video compositing renderer handles deterministic edits, captions, and cuts. * **Reads the web and video.** The agent can search the web, read pages, download public media, and answer questions about a video with timestamps. * **Arranges video sequences.** Clips become an editable timeline with audio layers. You export the final cut as one file. * **Follows skills.** Built-in skills from fal encode creative guidelines for characters, cinematography, UGC ads, photo editing, and more. You can write your own. ## How a turn works Every message you send starts a turn. The agent reasons about the request, calls tools, and streams its work into the chat. **1. Understand** The agent reads your message, your attachments, the active skills, and the project memory. If the request is ambiguous, it can ask a short multiple-choice question. **2. Plan** For multi-step work, the agent renders a plan card. You can edit the plan or run it as written. Simple requests skip this step. **3. Run** Each generation is a normal fal model run. The agent prepares the input and submits the run to the fal queue. Results stream into the chat and the media rail as they land. **4. Continue** When a run lands, the agent can continue with the next step automatically. Every remaining step is visible in the queue, and you can stop, reorder, or edit it at any time. ## What you pay for Model runs are billed as normal fal usage against your credits. Nothing else is billed. The agent's reasoning, the sandbox, web search, and video understanding are free to use for now. A spend chip next to the composer shows the running total for the chat, and [spending caps](/docs/documentation/agent/spending-caps) ask for confirmation before expensive runs. ## Start here > [card] [Quickstart](/docs/documentation/agent/quickstart) > > Run your first chat in five minutes > [card] [Access and pricing](/docs/documentation/agent/access-and-pricing) > > Optional credit plans, access restrictions, and what is billed > [card] [Plan cards](/docs/documentation/agent/plan-cards) > > Edit, approve, and version the agent's plan > [card] [Projects](/docs/documentation/agent/projects) > > Shared memory, documents, and media across chats > [card] [Skills](/docs/documentation/agent/skills) > > Built-in creative guidelines and your own skills > [card] [Tools](/docs/documentation/agent/tools/sandbox) > > Sandbox, web, video understanding, sequences, and more # Models and generation Source: https://fal.ai/docs/documentation/agent/models-and-generation How fal Agent chooses models, validates inputs, runs batches, compares models, and repairs failed runs. Every generation in fal Agent is a normal fal model run. The agent adds the parts that are usually manual: model choice, batching, and repair. ## The model catalog The agent works from the live fal model registry. The catalog refreshes every few minutes, so new models are available soon after they launch. The catalog is filtered by your account's access policy. Restricted models are not visible to the agent and cannot be run by mention. If a model is not in the catalog by name, the agent can search the registry for it. ## Auto model choice When you do not pin a model, the composer shows an **Auto** chip and the agent chooses. The choice follows fal's current recommendations for the task, the media type, the resolution, and whether references are attached. The recommendations change as new models launch, so the agent stays current without a settings change on your side. To pin a model, type `@` in the composer and pick one. You can also pin a model on one step of a [plan card](/docs/documentation/agent/plan-cards). A pinned model is final. The agent does not substitute another model for it. ## Batches A batch is two or more runs submitted together. Batches render as one grid in the chat. The agent uses batches for: * **Variations.** Several takes on one idea, spread across two or three aspect ratios. * **Candidates.** The same prompt on several models to pick the best. * **Sets.** A campaign with one output per format. Each run in a batch can carry a name. The name becomes the `#` reference token in the composer and the folder path in an [export](/docs/documentation/agent/generations/export). ## Model comparison Ask the agent to compare two or more models on one prompt. The result is a comparison card with one column per model. Each column shows the generation, the model name, and a spec line with latency, estimated price, resolution, and seed. **Fastest** and **cheapest** labels are computed from the results. The card does not give a verdict. You decide. ## Repair after failure When a run fails after submission, the agent receives the failure and diagnoses it. Typical repairs are: * **Input constraints.** An oversized reference image is resized in the sandbox and resubmitted. * **Input mismatch.** The input is rebuilt to match what the model expects. * **Transient provider errors.** The run is retried once. The agent repairs a run up to three times. After that, it explains the failure and asks how to proceed. Retried runs are paginated in the cell as **Attempt N of M**. ## Errors you can see Failed cells show a short explanation. Some messages are rewritten for clarity. The raw provider message stays available on hover. | Message | Meaning | | :- | :- | | This model isn't available on your account. | Your access policy restricts the model | | Insufficient credits. Add credits to your account and try again. | Your balance is too low for the run | | Account locked — generations are paused. | Billing needs attention. Check the [Billing](https://fal.ai/dashboard/billing) page | | Couldn't reach the model service. Retry to try again. | A transient failure on the provider side | | Cancelled | You stopped the run. This is not a failure | ## Cancellation Hover an in-flight cell and click the cancel button to stop that run. The cell shows **Cancelled**. To stop everything, use the stop button in the composer. See [Queue and steering](/docs/documentation/agent/chats/queue). ## Limits | Limit | Value | | :- | :- | | Async repairs per run | 3 | | Tool steps per turn | About 60. Longer work continues in the next turn | | Concurrent turns per chat | 1 | When a turn needs more steps than the limit, the agent stops and tells you. Send another message to continue. # Plan cards Source: https://fal.ai/docs/documentation/agent/plan-cards Review, edit, approve, and version the agent's plan before and during a multi-step run. A plan card is the agent's proposal for multi-step work. It appears in the chat as a titled, numbered list of steps. Each step can carry a model chip, a short reason, and an approval checkpoint. A **Why this plan** disclosure explains the overall approach. Simple requests do not produce a plan card. The agent runs them directly. ## Read the card | Element | Meaning | | :- | :- | | Step label | What the step produces | | Model chip | The model the agent intends to use. Empty means Auto | | Reason | One line on why this step or model | | **Pause here for approval** | The run stops before this step until you approve it | | Status badge | **Running**, **Checking status…**, or **Another plan is running** | ## Edit the plan You can edit the card directly before you run it, and you can edit the remaining steps while it runs. * **Rename** a step by clicking its label. * **Reorder** steps by dragging them. * **Add** or **remove** steps with the controls on each row. Removing a step also removes the steps that depend on it. * **Pin a model** on a step by clicking its model chip. A pinned model is final. The agent does not replace it. * **Toggle an approval checkpoint** on any step. The agent sees your edits. When it continues, it works from the edited plan, not its original proposal. ## Run, cancel, or revise * **Run plan** starts execution. Every remaining step becomes a visible row in the [queue](/docs/documentation/agent/chats/queue), so you can see the whole tail. * **Cancel plan** tells the agent you do not want this plan. The agent treats it as feedback and proposes a revision. * **Not happy with the plan?** Type a change in the text box on the card. This sends a normal message and produces a new plan version. Keyboard: `Cmd+Enter` (`Ctrl+Enter`) submits the revision box. ## Approval checkpoints A checkpoint is a hard stop. The agent cannot run past an unapproved checkpoint, even if it wants to. When execution reaches one, the chat row in the sidebar shows **Needs approval**, and the queue row waits. Approve it on the card to continue. Approval is consumed once, so the same step does not ask twice. Checkpoints are separate from [spending caps](/docs/documentation/agent/spending-caps), which gate on cost. ## Plan versions One chat has one logical plan with a version history. * A re-render in the same turn updates the card in place. * A re-plan in a later turn creates a new card, **v2**, **v3**, and so on, at the bottom of the chat. * The old card freezes as superseded and shows **Jump to the latest plan version**. ## Steps that continue automatically When a step's run lands, the agent continues with the next step without a message from you. The card shows the next step as **Up next**. If a batch lands partially, the agent continues with the runs that succeeded and reports the rest. You can interrupt at any time. See [Queue and steering](/docs/documentation/agent/chats/queue) for how a message sent mid-run is handled, and how to halt or resume a chain. # Projects Source: https://fal.ai/docs/documentation/agent/projects/index Group chats, media, documents, characters, and collections under one shared memory. A project is a container for related work. It holds chats, generated and uploaded media, documents, characters, collections, and a shared memory. The agent uses everything in the project as context, so you start a new session, not a new project. ## Create a project Open **Projects** in the sidebar and click **New project**. Give it a name, such as "Horror Shorts". You can also start a project from a chat with **New project from this chat** in the chat header. The Projects page lists your projects with search and sorting by **Last updated**, **Created at**, or **Name**. Rename or delete a project from its menu. ## The project home Open a project to see its outputs grid and a side panel with its chats, characters, collections, and documents. The header offers: | Action | Effect | | :- | :- | | **New chat** | Starts a chat inside the project | | **Add resource** | Add media from Assets, upload media, upload documents, add characters, or add collections | | **Add chats** | Move existing chats into the project | ## Add a chat to a project From the breadcrumb in a chat header, choose **Add to a project** or **Move to another project**. A chat belongs to one project at a time. Moving it moves its media into the project's pool. ## What the project adds to a chat * **Project scope in the media rail.** Switch the rail to **Project** to see every input and output across the project's chats. * **Context tab.** The rail's **Context** tab lists memory notes and documents. * **Memory tools.** The agent can search the project's memory and assets, read its documents, and save notes. See [Memory and documents](/docs/documentation/agent/projects/memory). * **Drop target.** Files dropped on the rail go to the project. See [Drag and drop](/docs/documentation/agent/chats/composer#drag-and-drop). ## Private chats A chat in a project contributes to the shared memory by default. To exclude one, choose **Private in project** from the breadcrumb. The chat stays in the project, but its turns no longer feed the memory. > [card] [Memory and documents](/docs/documentation/agent/projects/memory) > > How project memory is built, what the agent remembers, and how documents are indexed # Memory and documents Source: https://fal.ai/docs/documentation/agent/projects/memory How project memory captures decisions and preferences, and how uploaded documents become project context. Project memory lets the agent recall what happened in earlier chats. It has two parts: notes distilled from the chats, and documents you upload. ## Memory notes After each turn in a project chat, fal Agent ingests the turn into the project's memory. A background pass distills notes and a short primer that summarizes the project. Notes have a kind: | Kind | Example | | :- | :- | | **Decision** | "Final palette is teal and rust." | | **Preference** | "Prefers 4:5 for all product shots." | | **Style** | "35mm, shallow depth of field, warm grade." | | **Entity** | "Mara is the lead character. Red coat, silver hair." | | **Fact** | "The launch date is March 12." | Notes are short, standalone statements. A new note that repeats an old one replaces it. ### Manage notes Open the rail's **Context** tab to see the notes. You can pin a note so it is always in context, edit its text, change its kind, or delete it. You can also ask the agent to remember something directly: ```text theme={null} Remember: every video ends on the logo card, 1.5 seconds, no audio. ``` ### How the agent uses memory At the start of a turn the agent receives the primer and the pinned notes. It can search the rest of the memory, including verbatim history from earlier chats. It can also search the project's media by text or by image similarity. It saves a new note when a decision is made. ## Documents Upload PDF, DOCX, TXT, Markdown, CSV, TSV, or JSON files with **Add resource → Upload documents**. You can also drop them on the project page. Documents become project context. * The text is split into chunks and indexed for search. A document is indexed up to about 250,000 characters. * A one-line summary of each document appears in the document roster. The summary says what the document contains and what it is useful for. * The agent reads a document in pages when it needs the full text. Documents uploaded to a project are indexed far more deeply than a document attached to one message, which is read only in part. Put briefs, scripts, and brand guides in the project. A document's status shows **Ready**, **No text** when nothing could be extracted, or **Failed**. Failed documents can be retried. ## Memory and retention Derived memory and indexed documents have no expiry. Both are turned off when a finite [retention policy](/docs/documentation/agent/retention) applies to the workspace. # Quickstart Source: https://fal.ai/docs/documentation/agent/quickstart Start your first fal Agent chat, attach a reference, review the plan, and download the result. This guide takes you from sign-in to a downloaded generation. It takes about five minutes. ## Before you start You need a fal account. Access is enabled by default for signed-in accounts. You do not need a credit plan or an Enterprise contract to use fal Agent. Account and organization restrictions still apply. Model runs are billed as normal fal usage. See [Access and pricing](/docs/documentation/agent/access-and-pricing) for details. **1. Open fal Agent** Go to [fal.ai/agent](https://fal.ai/agent). Sign in with Google, GitHub, or SSO. If prompted, complete account setup. Prompts entered before sign-in are saved so you can continue after sign-in, if your account has access. If access is disabled for your account or organization, contact your organization administrator or fal support. Buying a credit plan does not override an access restriction. **2. Describe what you want** Type a request in the composer. Be specific about the subject, the format, and the number of outputs. For example: ```text theme={null} Make three product hero shots of this bottle on a marble surface. Soft morning light, 4:5 aspect ratio. Then animate the best one. ``` Press `Enter` to send. `Shift+Enter` adds a new line. ![A new chat with starter cards and the composer](https://mintcdn.com/fal-d8505a2e/DmEWlE6WV9vaz0Me/images/agent/new-chat.jpg?fit=max\&auto=format\&n=DmEWlE6WV9vaz0Me\&q=85\&s=56c4366fa9623988d6bcf2c61fdf376e) **3. Attach a reference** Drag an image, a video, or a document into the chat, or click the attachment button. The agent uses attachments as references, edit sources, or context. See [Composer and references](/docs/documentation/agent/chats/composer) for the supported file types and limits. **4. Review the plan** For a multi-step request, the agent shows a plan card before it runs anything. Read the steps and the model chips. You can rename a step, reorder steps, pin a different model, or add an approval checkpoint. Click **Run plan** when the plan looks right. Simple requests run directly without a plan card. **5. Watch the generations land** Each run appears as a cell in the chat and in the media rail on the right. In-flight cells show a cancel button. When a run finishes, hover the cell for **Retry** and **Download**. Failed runs show a short explanation, and the agent repairs the input and retries when it can. **6. Iterate** Type `@` to open the palette. Pick a previous output under **Generations**, or pin a model under **Models**. The agent keeps the chat context, so you can say "make the second one warmer" without repeating the prompt. **7. Download or export** Click **Download** on a cell to save one file. Ask the agent to "export everything as a zip" to get one archive with a folder per batch and a manifest. See [Export](/docs/documentation/agent/generations/export). ## Next steps > [card] [Chat interface](/docs/documentation/agent/chats/interface) > > Sidebar, media rail, history, shortcuts, and notifications > [card] [Models and generation](/docs/documentation/agent/models-and-generation) > > How the agent chooses models and repairs failed runs > [card] [Projects](/docs/documentation/agent/projects) > > Group chats and media under a shared memory > [card] [Spending caps](/docs/documentation/agent/spending-caps) > > Confirm expensive runs before they start # Retention and data Source: https://fal.ai/docs/documentation/agent/retention How long fal Agent keeps prompts, generations, and chats, how organizations set a retention policy, and how external content is handled. ## Default retention Self-serve accounts keep chats, prompts, and generations forever. You can delete a chat at any time from History, and you can remove a tile from a chat in the media rail. ## Organization retention policy Enterprise accounts and teams under an organization can set a **Chat retention** period in **Settings → General**. The policy applies to the whole workspace. | Options | | :- | | Forever, 1 hour, 2 hours, 6 hours, 12 hours, 1 day, 2 days, 3 days, 5 days, 1 week, 10 days, 2 weeks, 30 days, 90 days, 6 months, 1 year | A team inherits the organization's policy unless it sets its own. The setting shows **Inherited from your organization** with a **Reset to org default** link when a team has overridden it. Only admins can change the policy. ### What the policy does When a finite policy applies: * Every upload and every model output is stamped with a matching lifetime on the fal CDN. The files expire. * Every chat turn gets a matching expiry. Expired turns are hidden immediately and removed afterward. * Request and response payloads for model runs are not archived. * [Project memory](/docs/documentation/agent/projects/memory) distillation is turned off, because notes have no expiry. * Project documents cannot be uploaded, because an indexed document has no expiry. The policy applies to new turns from the moment it is set. It does not shorten the lifetime of existing files. ## What the agent shares with models Model runs send your prompt and your attached or referenced media to the fal model endpoint, as with any fal API call. The agent's reasoning runs on a language model operated for fal. Chat content is not used to train models. ## External content Content the agent fetches from the web, from a downloaded video, or from a connected app is treated as data. Instructions inside that content do not change the agent's behavior. The same applies to text inside uploaded documents. ## Sharing A shared chat is visible to the audience you choose until the share expires or you revoke it. See [Sharing and forking](/docs/documentation/agent/chats/sharing). ## Delete data * **Delete a chat** from History. This removes the chat and its turns. * **Remove a tile** from the media rail. This removes it from the chat. The file stays in your Assets library until you delete it there. * **Delete an asset from the library** at [fal.ai/assets](https://fal.ai/assets). This removes the library item, not the underlying CDN file. See [Assets retention and deletion](/docs/documentation/assets/retention) for file-deletion controls. # Tool activity Source: https://fal.ai/docs/documentation/agent/sdk/activity Read tool progress, visible reasoning, and activated skills from response snapshots. Response snapshots include activity from their execution turns. Use `fal.activities` to display progress and `fal.activated_skills` to inspect loaded skills. ```ts theme={null} import { agent } from "./client.ts"; for await (const response of agent.stream({ input: "Plan a product photo.", })) { for (const activity of response.fal.activities ?? []) { console.log( activity.id, activity.label, activity.status, ); } console.log(response.fal.activated_skills ?? []); } ``` Each update contains the complete activity snapshot. Replace displayed state instead of appending every update. Activity IDs remain stable when you retrieve or reconnect to the same response. | Field | Meaning | | - | - | | `id` | Stable activity identity within the response. | | `turn_id` | Execution turn that produced the activity. | | `kind` | `tool` or `reasoning`. | | `label` | Display label. | | `status` | `running` or `completed`. | | `started_at`, `ended_at` | Unix timestamps in milliseconds. The end time is optional. | | `duration_ms` | Optional duration in milliseconds. | Tool activities include `node`, an optional tool `name`, and optional JSON `arguments` and `output`. Reasoning activities include visible reasoning in `content`. Check the activity kind before reading its fields. Use structured [input requests](/docs/documentation/agent/sdk/inputs) for questions and approvals. Read the response status and error to determine whether the task succeeded. `activated_skills` contains names loaded during these turns, including active skills inherited from the conversation. It does not list every available skill. See [skills](/docs/documentation/agent/sdk/skills) for discovery and activation. Both arrays are optional. Missing fields mean the response does not report tool or skill activity. # Client configuration Source: https://fal.ai/docs/documentation/agent/sdk/configuration Configure authentication, transport, retries, and the public Agent exports. Create one client for the credentials your application uses. Agent requests use `https://fal.ai/api/agent-v2/sdk`. ```ts theme={null} import { createFalClient } from "@fal-ai/client"; const agent = createFalClient({ credentials: process.env.FAL_KEY, retry: { maxRetries: 3 }, }).agent; ``` See the [quickstart](/docs/documentation/agent/sdk/quickstart) for environment setup and a runnable task. ## Configuration fields | Field | Behavior | | - | - | | `credentials` | API key string or synchronous function that returns a string or `undefined`. | | `fetch` | Custom fetch implementation. Defaults to the runtime's global `fetch`. | | `retry` | Partial retry configuration. Omitted fields use the defaults below. | | `requestMiddleware` | Function that receives request configuration and returns a promise with the updated configuration. | | `proxyUrl` | Shared fal client proxy configuration. The proxy must support the Agent paths and streaming. | | `suppressLocalCredentialsWarning` | Suppress the browser credential warning. This does not protect an exposed key. | | `responseHandler` | Shared fal client configuration. Agent JSON calls use the SDK's JSON response handler. | Use a key with the **AGENT** permission preset. The SDK authenticates requests with `Authorization: Key :`. Browser sessions do not authenticate SDK requests. The key acts on its account's resources. It does not inherit a signed-in browser user's account selection or administrator role. When `credentials` is omitted, the shared client reads `FAL_KEY` from the environment. It also supports the `FAL_KEY_ID` and `FAL_KEY_SECRET` pair. ## Browser applications Keep the API key on your server. Use a server endpoint to call the Agent SDK for browser clients. The server must enforce your application's user permissions before forwarding requests. Your proxy must forward Agent requests and preserve streaming responses. `proxyUrl` accepts a URL string or `{ url, when }`. The `when` value is `"browser"`, `"always"`, or a function that receives `{ isBrowser }` and returns a boolean. A URL string uses the `"browser"` behavior. `requestMiddleware` receives `{ url, method, headers? }` and returns a promise containing the same shape. Headers map names to strings or string arrays. Preserve the required authorization, content type, and idempotency headers when changing a request. ## Request retries | Retry field | Default | Meaning | | - | - | - | | `maxRetries` | `3` | Additional attempts after a retryable failure. | | `baseDelay` | `1000` | Initial retry delay in milliseconds. | | `maxDelay` | `30000` | Maximum base delay in milliseconds. | | `backoffMultiplier` | `2` | Delay multiplier between attempts. | | `retryableStatusCodes` | `[429, 502, 503, 504]` | HTTP failures eligible for retry. | | `enableJitter` | `true` | Add variation to retry delays. | Reads and response commands use this retry policy for eligible HTTP and transport failures. Resource writes for projects, settings, preferences, skills, library, queues, runs, and final selections are sent once. Idle conversation creation is also sent once. Conversation rename and deletion can use automatic retries. Read the conversation after a network error before repeating either operation. A retry within one command preserves its idempotency key. To recover after a process restart, persist the request and key before submission. See [response recovery](/docs/documentation/agent/sdk/responses#recover-an-uncertain-submission). `timeoutMs` covers local request attempts and waits. An abort or timeout stops retries. Neither cancels server execution. Streaming also has `maxReconnects` and `reconnectDelayMs`. See [response options](/docs/documentation/agent/sdk/responses#options). ## Public exports | Export | Use | | - | - | | `createFalClient(config).agent` | Create the configured Agent client. | | `AgentClient` | Type for the full Agent client. See the [method reference](/docs/documentation/agent/sdk/methods). | | `AgentResponsesClient` | Type for `agent.responses`. | | `isAgentTerminal(response)` | True for `completed`, `incomplete`, `failed`, or `cancelled`. | | `isAgentStopped(response)` | True for terminal responses, `waiting_for_input`, or a present `fal.pending_submission`. | | `AgentRequestError` | Request failure with optional response and retry context. | | `AgentProtocolError` | Invalid response or stream protocol. | | `Agent*` data types | Complete definitions in the [type reference](/docs/documentation/agent/sdk/types). | ```ts theme={null} import { agent } from "./client.ts"; import { isAgentStopped, isAgentTerminal, } from "@fal-ai/client"; const response = await agent.responses.retrieve("RESPONSE_ID"); console.log( isAgentStopped(response), isAgentTerminal(response), ); ``` `createAgentClient(config)` accepts a resolved `RequiredConfig`. For standard setup, use `createFalClient()` to supply transport and retry defaults. ## Runtime requirements The client uses `fetch`, `AbortController`, `URL`, and asynchronous iterators. These guides use Node.js 22.22 or later, including its global `File` constructor for document uploads. Use `agent.projects.documents.upload` to upload and import a project document. For other uploads, use the shared fal storage client and pass the resulting URL to an Agent request or resource method. # Errors and troubleshooting Source: https://fal.ai/docs/documentation/agent/sdk/errors Distinguish request failures from execution failures and recover without duplicate work. Use the [quickstart client](/docs/documentation/agent/sdk/quickstart#create-a-client). Replace uppercase IDs with your resource IDs. ## Request errors Inspect `response.status` and `response.error` for execution failures. Catch `AgentRequestError` for transport or request failures. ```ts theme={null} import { agent } from "./client.ts"; import { AgentRequestError } from "@fal-ai/client"; try { await agent.responses.retrieve("RESPONSE_ID"); } catch (error) { if (!(error instanceof AgentRequestError)) throw error; console.error( error.status, error.message, error.responseId, ); } ``` | Error field | Meaning | | - | - | | `message` | Request failure description. | | `status` | Optional HTTP status. | | `responseId` | Accepted or observed response identity when known. | | `idempotencyKey` | Mutation key when available. | | `lastResponse` | Last observed snapshot when available. | | `cause` | Underlying transport, abort, timeout, or protocol error. | Error context is optional. An absent HTTP status can indicate a local timeout, abort, or network failure. | HTTP status | Action | | - | - | | `400` | Correct the request or cursor using the returned error message. | | `401` / `403` | Check your credentials and account access. | | `404` | Check the resource ID and access permissions. | | `409` | Retrieve current state. Resolve the revision, cursor, or idempotency conflict before retrying. | | `410` | The retained response is no longer available. | | `422` | Correct the input using the returned error message. | ## Local and protocol errors Invalid options or IDs can throw `TypeError` before a request starts. Correct the argument instead of retrying it. `AgentProtocolError` indicates an invalid snapshot, response identity, or stream envelope. It can appear inside an `AgentRequestError.cause` chain. Retrieve the response by its saved ID. `AgentEvent` describes the transport envelope. `agent.stream` yields response views, not raw event objects. ## Choose a recovery action | Situation | What happened | Next action | | - | - | - | | `run()` resolved with `failed` | The request was accepted, but execution failed. | Read `response.error` and any available artifacts before deciding on a new task. | | A helper returned `waiting_for_input` | The response needs an answer or approval. | Read `pending_inputs`, answer, then resume observation of the same ID. | | Create or answer lost its acknowledgement | The server might have accepted the command. | Retry the exact body with the same idempotency key. | | A stream disconnected | Local observation stopped. Execution can continue. | Reconnect with `responses.stream(id)` or retrieve the response. | | A local timeout expired | The helper reached its observation deadline. | Retrieve the response. Call `responses.cancel` to stop execution. | | A plan or final-selection write returned `409` | The expected revision or sequence no longer matches. | Read the latest state and apply your changes to that version. | | A history page returned `409` | The history snapshot changed. | Discard accumulated pages and restart pagination. | | A resource write lost its acknowledgement | The resource could have changed. | Read it back before retrying. A run retry can create another paid attempt. | ## Rate limits and service failures For `429`, reduce concurrent requests and avoid immediate retry loops. For `5xx` or network failures, allow time between attempts. When retrying a submission, preserve its original idempotency key and body. Correct validation or permission errors before retrying. ## Capture useful diagnostics Record the SDK version, method, HTTP status, error message, and response ID when available. For execution failures, record the response status and phase. Remove credentials and private prompt content before sharing logs. # Use the docs with coding agents Source: https://fal.ai/docs/documentation/agent/sdk/for-agents Give a coding agent the exact guides and references needed to build an Agent SDK integration. Start with the [quickstart](/docs/documentation/agent/sdk/quickstart), [method reference](/docs/documentation/agent/sdk/methods), and [type reference](/docs/documentation/agent/sdk/types). Give your coding agent the installed package version and the guide for the task you want to implement. ## Find the right page | Task | Read | | - | - | | Configure the client | [Configuration](/docs/documentation/agent/sdk/configuration). | | Create, stream, recover, or cancel a task | [Responses and recovery](/docs/documentation/agent/sdk/responses). | | Answer questions or approvals | [Questions and approvals](/docs/documentation/agent/sdk/inputs). | | Edit or execute a plan | [Plans](/docs/documentation/agent/sdk/plans). | | Read artifacts or costs | [Media and costs](/docs/documentation/agent/sdk/media). | | Read conversation history | [Conversations](/docs/documentation/agent/sdk/resources). | | Manage projects, documents, or memory | [Projects](/docs/documentation/agent/sdk/projects). | | Choose models or defaults | [Models and settings](/docs/documentation/agent/sdk/settings). | | Manage queued work or generation attempts | [Queues and runs](/docs/documentation/agent/sdk/queue). | | Manage assets, collections, or smart entities | [Library](/docs/documentation/agent/sdk/library). | | Manage skills or read tool activity | [Skills](/docs/documentation/agent/sdk/skills) and [activity](/docs/documentation/agent/sdk/activity). | | Diagnose a failure | [Errors](/docs/documentation/agent/sdk/errors). | Use the page's **Copy page** action to copy Markdown. Mintlify also serves Markdown page exports and a documentation index at `llms.txt`. Use the index from the same documentation host as the page you are reading. # fal Agent SDK for JavaScript and TypeScript Source: https://fal.ai/docs/documentation/agent/sdk/index Install the fal Agent SDK for JavaScript and TypeScript. Generate AI media, stream progress, and handle questions and approvals with code examples. The fal Agent SDK connects your JavaScript or TypeScript application to [fal Agent](/docs/documentation/agent). Describe a task in natural language to generate images, video, audio, or 3D media through the fal model catalog. The agent chooses models, prepares prompts, and executes the task. Use the Agent SDK when your application needs the agent to coordinate a task across multiple steps. It supports conversations, editable plans, user approvals, and generated media. For a direct call to a specific model, use the [fal model clients](/docs/api-reference/client-libraries) instead. > [!NOTE] > > The Agent SDK is in alpha. These examples use `@fal-ai/client@1.11.0-alpha.4`. > Media generation can incur charges. See [Access and > pricing](/docs/documentation/agent/access-and-pricing). ## Install the SDK The Agent SDK is part of the [`@fal-ai/client` npm package](https://www.npmjs.com/package/@fal-ai/client). It supports JavaScript and includes TypeScript types for requests, responses, and resources. Use Node.js 22.22 or later for these examples. See [client configuration](/docs/documentation/agent/sdk/configuration#runtime-requirements) for runtime requirements. ```bash npm theme={null} npm install @fal-ai/client@1.11.0-alpha.4 ``` ```bash yarn theme={null} yarn add @fal-ai/client@1.11.0-alpha.4 ``` ```bash pnpm theme={null} pnpm add @fal-ai/client@1.11.0-alpha.4 ``` ### Python support The Agent SDK currently supports JavaScript and TypeScript. The [fal Python client](/docs/api-reference/client-libraries/python/index) supports direct model calls. It does not provide the Agent SDK methods for conversations, plans, or approvals. ### Authentication Create a [fal API key](/docs/documentation/setting-up/authentication) with the **AGENT** permission preset. Set the key in your environment: ```bash theme={null} export FAL_KEY="YOUR_API_KEY" ``` Replace `YOUR_API_KEY` with your key. The SDK reads `FAL_KEY` when you omit `credentials`. Keep the API key on your server. For a browser application, use a server endpoint that enforces your users' permissions. See [browser applications](/docs/documentation/agent/sdk/configuration#browser-applications). ## Generate media Use `agent.run()` to submit a task and wait for its result. The agent creates a response that contains the task status, assistant text, generated media, and any questions or approvals. An artifact identifies generated media and can contain files with download URLs. Create `agent.mts`: ```ts theme={null} import { createFalClient } from "@fal-ai/client"; const agent = createFalClient().agent; const response = await agent.run( { input: "Generate a product photo of a blue ceramic mug." }, { timeoutMs: 5 * 60 * 1000 }, ); console.log(response.id, response.status, response.output_text); console.log(response.pending_inputs, response.error); for (const artifact of response.artifacts) { for (const file of artifact.files ?? []) { console.log(file.url); } } ``` Install `tsx` to execute the TypeScript example: ```bash theme={null} npm install --save-dev tsx npx tsx agent.mts ``` `run()` returns when execution stops or needs user input. Check the response before you use its media: | Field | Purpose | | - | - | | `status` | Reports the task's execution state. | | `output_text` | Contains the assistant's text. | | `artifacts` | Contains generated media and optional files with URLs. | | `pending_inputs` | Contains questions and approvals that need the user's answer. | Execution failures appear in `response.status` and `response.error`. Request failures throw `AgentRequestError`. See [errors and troubleshooting](/docs/documentation/agent/sdk/errors) for failure and recovery details. See [media and costs](/docs/documentation/agent/sdk/media) to reuse media or select final results. ### SDK methods Use these methods to submit tasks and control their execution: | SDK method | Purpose | | - | - | | `agent.run()` | Submit a new task and poll until execution stops. | | `agent.stream()` | Submit a new task and stream progress. | | `agent.responses.create()` | Submit a new task. Return its initial response. | | `agent.responses.retrieve()` | Read the current state of an existing task. | | `agent.responses.wait()` | Poll an existing task until execution stops. | | `agent.responses.stream()` | Stream an existing task. | | `agent.responses.answer()` | Answer a question or approval for an existing task. | | `agent.responses.cancel()` | Request cancellation of an existing task. | See the [method reference](/docs/documentation/agent/sdk/methods) for all methods and the [type reference](/docs/documentation/agent/sdk/types) for their types. ## Progress and user input ### Stream progress Use `agent.stream()` to start a task with progress updates: ```ts theme={null} import { createFalClient } from "@fal-ai/client"; const agent = createFalClient().agent; for await (const response of agent.stream( { input: "Generate a product photo of a blue ceramic mug." }, { timeoutMs: 5 * 60 * 1000 }, )) { console.log(response.status, response.output_text); console.log(response.artifacts, response.pending_inputs); } ``` This example creates a new task. Use `responses.stream(responseId)` to observe a task that already exists. Each update contains the complete response state, called a snapshot. Replace the displayed state on each update. Do not append each snapshot's `output_text` to the previous text. ### Questions and approvals The agent can pause to ask a question or request approval. When `pending_inputs` contains a request, show it to the user. Collect the user's answer. Submit the answer with `responses.answer()` and the same response ID. Then resume observation with `responses.wait()` or `responses.stream()`. See [questions and approvals](/docs/documentation/agent/sdk/inputs) for answer formats and examples. ### Recovery and cancellation Save the response ID to reconnect after a process restart, timeout, or lost connection. Use `responses.wait()` or `responses.stream()` with that ID to observe the existing task. For an application that stores task state, submit the task with `responses.create()`. Save the response ID. Then call `responses.wait()` or `responses.stream()`. See [responses and recovery](/docs/documentation/agent/sdk/responses) for submission retries and reconnection options. > [!WARNING] > > A timeout, an aborted signal, or a closed stream does not cancel server > execution. Use `responses.cancel()` to request cancellation of the task. ## Next steps * Use the [quickstart](/docs/documentation/agent/sdk/quickstart) to run your first task. * Configure credentials, transport, and retries with [client configuration](/docs/documentation/agent/sdk/configuration). * Control a task's steps with [plans](/docs/documentation/agent/sdk/plans). * Organize tasks with [conversations](/docs/documentation/agent/sdk/resources) and [projects](/docs/documentation/agent/sdk/projects). * Add reusable instructions with [skills](/docs/documentation/agent/sdk/skills). * Display execution progress with [tool activity](/docs/documentation/agent/sdk/activity). * Find integration guides in [guidance for coding agents](/docs/documentation/agent/sdk/for-agents). # Questions and approvals Source: https://fal.ai/docs/documentation/agent/sdk/inputs Answer questions and approvals, then resume the same Agent response. Use the [quickstart client](/docs/documentation/agent/sdk/quickstart#create-a-client). Replace uppercase IDs with values from the pending request. The `SAVED_*_KEY` values represent persisted keys for those answers. When `response.fal.phase` is `waiting_for_input`, read `response.pending_inputs` for the questions or approvals that need an answer. ## Answer a clarification Render each question's text and options using its `multiple` and `allow_text` fields. Use IDs from the pending input request. ```ts theme={null} import { agent } from "./client.ts"; await agent.responses.answer( "RESPONSE_ID", { input_request_id: "INPUT_REQUEST_ID", answer: { kind: "answers", answers: [ { question_id: "QUESTION_ID", selected_option_ids: ["OPTION_ID"], }, ], }, }, { idempotencyKey: "SAVED_ANSWER_KEY" }, ); ``` Answer every question exactly once. Select only the returned option IDs, without duplicates. When `multiple` is false, select at most one option. Include free text only when `allow_text` is true. Each answer requires an option or nonempty text. Submit 1–20 answers, with at most 20 selected options per question and 2,000 characters of text. Model preference questions use the same answer format. Select the returned option IDs. The answer applies the requested preference change before execution continues. ## Submit an approval decision An approval identifies its target with `target.item_id` and `target.revision`. The `accepted_answers` field lists the permitted decisions for that target. ```ts theme={null} import { agent } from "./client.ts"; await agent.responses.answer( "RESPONSE_ID", { input_request_id: "INPUT_REQUEST_ID", answer: { kind: "approval", decision: "approve", }, }, { idempotencyKey: "SAVED_APPROVAL_KEY" }, ); ``` Send `approve` to allow the requested action or `reject` to decline it. Input request states are `pending`, `answered`, `rejected`, `expired`, and `cancelled`. An optional `expires_at` gives the expiry time. Only pending requests can accept an answer. ## Resume and recover After answering, call `responses.wait(id)` or `responses.stream(id)` with the same response ID. The agent can request another input. If the acknowledgement is lost, retry with the exact answer body and idempotency key. If the input is stale, retrieve the response and render its current pending inputs. ### Recover a saved answer that could not resume An answer can be saved before the next turn starts. If that turn fails to start, `fal.pending_submission` contains the `input_request_id`, `action: "retry_input"`, and an `error`. The response stays unfinished. Polling and streaming helpers return the snapshot. Fix the reported problem. Retry `responses.answer` with the exact saved body and idempotency key. This resumes the saved answer without applying the decision twice. Observation alone does not retry submission. # Library assets, collections, and entities Source: https://fal.ai/docs/documentation/agent/sdk/library Manage assets, manual and smart collections, and all five smart entity types. Use the [quickstart client](/docs/documentation/agent/sdk/quickstart#create-a-client). Replace uppercase IDs with your resource IDs. Manage assets, collections, and reusable visual references in your fal Assets library. The API key selects the personal or team account. The library enforces the same account access, ownership, and read/write permissions as Assets. See [Access and availability](/docs/documentation/assets/access) for the product rules. ## Use the correct asset ID Use a non-null `assetRecordId` for library mutations. A search result can have a missing or null `assetRecordId`. | Field | Use | | - | - | | `assetRecordId` | Retrieve, favorite, update, delete, or add the library record to a collection. | | `assetId` | Attach an existing asset to a project. Can be `null`. | | `vectorId` | Search identity. Do not use it for library mutations. | | `requestId` | Generation request identity. Can be `null`. | An SDK artifact has its own ID. It is not a library record. ## Search assets ```ts theme={null} import { agent } from "./client.ts"; const page = await agent.library.assets.list({ q: "blue ceramic mug", mediaTypes: ["image"], limit: 20, }); console.log( page.items, page.nextCursor, page.scopeTruncated, ); ``` All query fields are optional: | Field | Values and behavior | | - | - | | `q` | Text search. Defaults to an empty string. | | `searchImageUrl` | Image URL for similarity search. | | `searchVideoUrl` | Video URL for similarity search. | | `mediaTypes` | Array containing `image`, `video`, `audio`, or `3d`. | | `sources` | Array containing `upload` or `response`. | | `section` | `all-media`, `generated`, `uploads`, or `favorites`. Defaults to `all-media`. | | `endpoints` | Generation endpoint IDs. | | `collectionId` | Restrict the search to a collection. | | `recursive` | Include descendant collections when searching a collection. | | `assetRecordIds` | Restrict results to these records. Maximum 10,000 IDs. | | `tagIds` | Tag IDs used to filter results. | | `tagMode` | `any` or `all`. Defaults to `any`. | | `sortOrder` | `newest` or `oldest`. Defaults to `newest`. | | `cursor` | The previous page's `nextCursor`. Omit it or use `null` for the first page. | | `limit` | From 1 to 100. Defaults to 48. | The response contains `items`, `nextCursor`, `totalCount`, and `scopeTruncated`. A null `totalCount` means the total is unavailable. A true `scopeTruncated` means the search does not cover the full scope. ```ts theme={null} import { agent } from "./client.ts"; let cursor: string | null = null; do { const page = await agent.library.assets.list({ section: "favorites", mediaTypes: ["image"], cursor, }); console.log(page.items); if (page.scopeTruncated) console.warn("The search scope is incomplete."); cursor = page.nextCursor; } while (cursor); ``` Keep the filters unchanged when advancing the cursor. Start a new search when you change the filters. ## Read asset metadata `library.assets.retrieve(assetRecordId)` returns an [AgentLibraryAsset](/docs/documentation/agent/sdk/types#agentlibraryasset). Search results use the same type. | Fields | Meaning | | - | - | | `url`, `type`, `title` | Media location, modality, and display title. The URL can be `null`. | | `endpoint`, `source`, `prompt` | Generation endpoint, origin, and prompt. Each can be `null`. | | `width`, `height`, `size`, `contentType` | Media dimensions, byte size, and MIME type when available. | | `createdAt` | Creation time, or `null`. | | `isFavorited`, `collectionIds` | Favorite state and collection memberships. | | `tags` | Optional tag records with ID, name, color, and creation time. | ## Register and update assets Register an existing media URL: ```ts theme={null} import { agent } from "./client.ts"; const asset = await agent.library.assets.register({ url: "https://fal.media/files/FILE_ID/mug.png", type: "image", favorite: true, }); console.log(asset.assetRecordId); ``` Replace the example URL with the HTTPS URL returned by the fal storage client. Arbitrary external hosts are rejected. Upload media with `fal.storage.upload` before registration. Registration does not upload the file. Optional inputs include `size` in bytes, `collectionId`, and `favorite`. | Method | Behavior | | - | - | | `library.assets.setFavorite(id, boolean)` | Set the favorite state. Returns the record identity and `isFavorited`. | | `library.assets.updatePrompt(id, prompt)` | Update an uploaded asset's prompt. Use 1–2,000 characters after trimming. | | `library.assets.delete(id)` | Delete the library record. Returns `{ success: true }`. | The prompt update applies to uploaded assets. It does not rewrite a generated asset's original prompt. ```ts theme={null} import { agent } from "./client.ts"; await agent.library.assets.setFavorite( "ASSET_RECORD_ID", true, ); await agent.library.assets.updatePrompt( "ASSET_RECORD_ID", "Blue ceramic mug", ); ``` ## Manage tags ```ts theme={null} import { agent } from "./client.ts"; const tag = await agent.library.tags.create({ name: "launch", }); await agent.library.assets.assignTag( "ASSET_RECORD_ID", tag.id, ); console.log( await agent.library.assets.tags( "ASSET_RECORD_ID", ), ); ``` `library.tags.list` returns available asset tags. System tags are excluded. Use `library.tags.update(id, change)` to change a name or color. Tag names are trimmed, stored in lowercase, and unique within the account. Use `library.assets.removeTag(assetRecordId, tagId)` to remove one assignment. Deleting a tag removes its assignments without deleting assets. ## Find smart entities `library.entities` supports all five types through the same methods. | Type | Reference purpose | | - | - | | `character` | A person or creature. | | `prop` | An object or product. | | `environment` | A location or setting. | | `style` | A visual treatment or medium. | | `scene` | A composition or arrangement. | List the account's entities, or filter by type: ```ts theme={null} import { agent } from "./client.ts"; const entities = await agent.library.entities.list({ types: [ "character", "prop", "environment", "style", "scene", ], limit: 100, offset: 0, }); for (const entity of entities) { console.log( entity.id, entity.type, entity.name, entity.handle, ); } ``` Omit `types` to include all five types. The default limit is 100. The maximum is 1,000. Use an offset to read another page. The response is an array without a pagination cursor. Use `search` for a case-insensitive substring match against entity names and handles. The search text has a maximum of 255 characters after trimming. ```ts theme={null} import { agent } from "./client.ts"; const props = await agent.library.entities.list({ types: ["prop"], search: "mug", }); console.log(props); ``` Resolve known handles without searching every page: ```ts theme={null} import { agent } from "./client.ts"; const entities = await agent.library.entities.resolve({ handles: [ "@milo", "@blue-mug", "@workshop", "@watercolor", "@breakfast", ], }); console.log(entities); ``` `resolve` accepts an optional `types` filter. Supply one to 100 handles, with or without the leading `@`. It returns matching entities in the key's account. Unknown handles and handles from other accounts are omitted. ## Read entity metadata and references ```ts theme={null} import { agent } from "./client.ts"; const entity = await agent.library.entities.retrieve( "ENTITY_ID", ); console.log( entity.type, entity.description, entity.metadata, entity.thumbnailUrl, ); const referenceUrls = entity.references.map( (reference) => reference.url, ); console.log(referenceUrls); ``` List, resolve, retrieve, create, and update results contain the same typed entity data. Each defining reference includes an `assetRecordId` and a usable image `url`. The `references` array excludes the associated-media gallery. Deleted or expired reference assets are unavailable. `metadata` contains product-specific fields. Check their shape before use. The character metadata is managed by the product and cannot be set through entity writes. ## Create and update smart entities This example creates one entity of each type. Replace each reference URL with a fal storage URL or an existing asset target before execution. ```ts theme={null} import { agent } from "./client.ts"; const inputs = [ { type: "character", name: "Milo", handle: "milo", description: "A gray cat with green eyes.", reference: "MILO", }, { type: "prop", name: "Blue mug", handle: "blue-mug", description: "A blue ceramic mug.", reference: "MUG", }, { type: "environment", name: "Workshop", handle: "workshop", description: "A sunlit pottery workshop.", reference: "WORKSHOP", }, { type: "style", name: "Watercolor", handle: "watercolor", description: "Soft watercolor with visible paper texture.", reference: "WATERCOLOR", }, { type: "scene", name: "Breakfast", handle: "breakfast", description: "A mug and plate on a kitchen table.", reference: "BREAKFAST", }, ] as const; for (const { reference, ...input } of inputs) { const entity = await agent.library.entities.create({ ...input, referenceImages: [ `https://fal.media/files/${reference}.png`, ], }); console.log(entity.id, entity.type); } ``` Names contain 1–255 characters after trimming. Descriptions have a maximum of 2,000 characters. Characters require a description. The other four types allow an omitted or null description. All five types require one to twenty reference images. The product validates storage URLs, asset access, and image types. Handles are unique across the account's five entity types. Handles have a maximum of 64 characters. The product normalizes handles and derives a handle from the name when omitted during creation. Use `entities.checkHandle({ handle, excludeId })` to check availability. Supply `excludeId` when editing an existing entity. Another request can claim the handle before the write completes. ```ts theme={null} import { agent } from "./client.ts"; const availability = await agent.library.entities.checkHandle({ handle: "blue-mug", excludeId: "PROP_ID", }); console.log( availability.handle, availability.available, ); const prop = await agent.library.entities.update( "PROP_ID", { description: "A blue ceramic mug with a rounded handle.", referenceImages: [ "https://fal.media/files/MUG_FRONT.png", "https://fal.media/files/MUG_SIDE.png", ], coverImageUrl: "https://fal.media/files/MUG_FRONT.png", }, ); console.log(prop.references); ``` Updates preserve omitted fields. A supplied `referenceImages` array replaces the complete defining reference set. The entity type cannot change. Character handles cannot change. The other four types allow handle edits and nullable metadata. Set their handle to `null` to clear it. Retrieve them by ID or search by name afterward. Handle resolution does not return entities with a cleared handle. Their cover must be one of the defining references. Characters also support a separate cover image, which does not become a defining reference. ## Manage the associated-media gallery The gallery contains manually linked assets and recorded generations that used the entity. Adding an asset to the gallery does not add a defining reference. ```ts theme={null} import { agent } from "./client.ts"; await agent.library.entities.addAsset( "ENTITY_ID", "ASSET_RECORD_ID", ); const gallery = await agent.library.entities.listAssets( "ENTITY_ID", { mediaTypes: ["image"], limit: 50, offset: 0, }, ); console.log( gallery.items, gallery.nextOffset, gallery.totalCount, ); await agent.library.entities.removeAsset( "ENTITY_ID", "ASSET_RECORD_ID", ); ``` By default, a reference appears in the gallery only if it also has a manual link or recorded generation usage. Set `includeReferences: true` to include the defining reference membership too. The default limit is 50. The maximum is 100. Use the returned `nextOffset` for the next page. A null value ends pagination. Removing a manual link does not delete the asset or erase recorded generation usage. Use `entities.setFavorite(id, boolean)` and `entities.delete(id)` to favorite or delete any entity type. Deleting an entity does not delete its source assets. The existing collection favorite, delete, add-asset, and remove-asset methods also accept entity IDs. ## Character methods The `library.characters` methods keep their existing inputs and results: ```ts theme={null} import { agent } from "./client.ts"; const character = await agent.library.characters.create({ name: "Milo", identifier: "milo", description: "A gray cat with green eyes.", referenceImages: [ "https://fal.media/files/REFERENCE.png", ], }); console.log(character.id); ``` Use `characters.checkIdentifier(identifier)` to check availability before creation. Use `characters.update(id, input)` to replace the name, description, and complete reference list. Character identifiers cannot change. `characters.references(id)` reads the resolved reference images. The legacy references response can include a display-only cover marked `isCover`. Exclude that entry when saving `referenceImages`. Use `library.entities.list({ types: ["character"] })` to list only characters. The asset query's `characterSearchIdentifiers` field filters assets by character usage. See the [reference](/docs/documentation/agent/sdk/methods#library) for exact inputs and results. ## Create a manual collection ```ts theme={null} import { agent } from "./client.ts"; const collection = await agent.library.collections.create({ name: "Mugs", }); await agent.library.collections.addAsset( collection.id, "ASSET_RECORD_ID", ); ``` A collection name contains 1–255 characters. Optional fields include `description`, `icon`, `color`, `coverImageUrl`, `filters`, and `parentCollectionId`. The description has a maximum of 1,000 characters. The icon and color each have a maximum of 32 characters. Use `removeAsset(collectionId, assetRecordId)` to remove a manual membership. Adding or removing membership does not upload or delete the asset. ## Create a smart collection Smart collections select assets through a filter expression. This example selects images with a similar description: ```ts theme={null} import { agent } from "./client.ts"; const collection = await agent.library.collections.create({ name: "Blue product photos", filters: { and: [ { field: "type", op: "eq", value: "image" }, { semantic: { text: "blue product photography", min_similarity: 0.6, }, }, ], }, }); console.log(collection.id); ``` A filter uses one of these forms: | Form | Meaning | | - | - | | `{ and: [...] }` | Match every child expression. Requires at least one child. | | `{ or: [...] }` | Match any child expression. Requires at least one child. | | `{ field, op, value }` | Compare an asset field with a value. | | `{ semantic: { ... } }` | Match semantic similarity. | Comparison fields are `endpoint`, `status`, `type`, `source`, and `created_at`. Operators are `eq`, `neq`, `in`, `gt`, `gte`, `lt`, and `lte`. Values can be strings, numbers, string arrays, or number arrays. Use a value compatible with the field. For `in`, supply an array. A semantic expression requires exactly one of `text`, `image_url`, or `video_url`. `min_similarity` ranges from `0` to `1`. The maximum filter depth is three levels, including the root expression. Use `library.assets.list({ collectionId })` to read matching assets. Manage smart collection membership through its filters. ## List and manage collections `library.collections.list({ limit, offset, includeCharacters, includeSmartEntities })` returns an array. `includeCharacters` defaults to `true`. It preserves the existing character inclusion behavior. Set `includeSmartEntities: true` to include all five entity types, regardless of `includeCharacters`. When `includeSmartEntities` is false or omitted, `includeCharacters` controls character inclusion. The limit ranges from 1 to 1,000. The offset ranges from 0 to 10,000. This method does not return `nextCursor`. ```ts theme={null} import { agent } from "./client.ts"; const collections = await agent.library.collections.list({ limit: 50, offset: 0, includeSmartEntities: true, }); console.log(collections); ``` | Method | Behavior | | - | - | | `library.collections.update(id, input)` | Change metadata or filters. Omitted fields stay unchanged. | | `library.collections.move(id, parentId)` | Move the collection. Use `null` for the root. | | `library.collections.setFavorite(id, boolean)` | Set the favorite state. | | `library.collections.delete(id)` | Delete the collection without deleting its source assets. | Updates accept `name`, `description`, `icon`, `color`, `coverImageUrl`, and `filters`. Use `null` to clear a nullable field. The name cannot be `null`. An [AgentLibraryCollection](/docs/documentation/agent/sdk/types#agentlibrarycollection) includes metadata, type, filters, parent ID, handle fields, favorite state, and timestamps. It also includes `assetCount` and `previewAssets`. The count can be `null`. Types are `manual`, `smart`, `character`, `prop`, `environment`, `style`, and `scene`. Use `library.entities` to create or update an entity's defining data. Use `library.collections` to create manual or smart collections. ## Handle uncertain writes Library writes are sent once. They do not accept an idempotency key. After a network error, retrieve the asset or list the collections before repeating the change. All methods accept optional `signal` and `timeoutMs` as their final argument. # Media and costs Source: https://fal.ai/docs/documentation/agent/sdk/media Read completed artifacts, reuse media in follow-ups, and select final results. Use the [quickstart client](/docs/documentation/agent/sdk/quickstart#create-a-client). Replace uppercase IDs with your resource IDs. Pending generation appears as a `fal.operation`. Completed media appears in `response.artifacts` as a `fal.artifact`. ## Read artifacts `artifacts.retrieve(id, { revision }?)` returns an `AgentArtifact`. Omit `revision` to read the available version. Media artifacts use revision `1`. An unavailable revision returns `404`. Each artifact has an ID, revision, and optional files. A file includes its role, URL, MIME type, and optional URL expiry. ```ts theme={null} import { agent } from "./client.ts"; const artifact = await agent.artifacts.retrieve("ARTIFACT_ID"); console.log(artifact.files); ``` Artifact reads enforce ownership and retention. An artifact ID is different from a library asset-record ID. ## Refine an existing result Reference a completed artifact alongside the new instruction to reuse media without uploading it again. ```ts theme={null} import { agent } from "./client.ts"; const response = await agent.run({ conversation: "CONVERSATION_ID", input: [ { role: "user", content: [ { type: "input_text", text: "Make the lighting warmer.", }, { type: "fal.input_artifact", artifact_id: "ARTIFACT_ID", }, ], }, ], }); console.log(response.status, response.artifacts); ``` A `fal.input_artifact` part accepts an optional `revision` of `1`. Omit it to use the available artifact. This creates a new response in the same conversation. A media refinement can incur new generation charges. For an external image, use `{ type: "input_image", image_url }`. For a file, use `{ type: "input_file", file_url, mime_type }`. The URL must be accessible to the runtime. These content parts reference files and do not upload them. ## Select final results Completion does not mark every artifact as a final result. After the response finishes, select final artifacts with its current sequence number. ```ts theme={null} import { agent } from "./client.ts"; const response = await agent.responses.retrieve("RESPONSE_ID"); await agent.responses.selectFinalArtifacts( response.id, { artifact_ids: ["ARTIFACT_ID"], expected_sequence_number: response.fal.sequence_number, }, ); ``` The returned `final_artifacts` reflects the selection. Pass an empty array to clear it. On a `409`, retrieve the current response and apply the selection to that version. ## Inspect generation costs ```ts theme={null} import { agent } from "./client.ts"; const summary = await agent.conversations.generationSummary( "CONVERSATION_ID", ); console.log(summary); ``` The summary reports generation costs and unpriced requests for that conversation. `totalCostNanoUsd` and `costsNanoUsd` use billionths of a US dollar. Divide by `1_000_000_000` for USD. `unpricedRequestCount` counts requests without a price. The reported total excludes those costs and LLM usage. ## Handle partial results A failed response can retain usable artifacts. Inspect each operation for generation failures and the response error for execution failure. Export blocks can contain download links without a corresponding SDK artifact. Render their `fallback_text` when your application does not understand the block kind. # Method reference Source: https://fal.ai/docs/documentation/agent/sdk/methods Signatures, inputs, return types, and guide links for every Agent client method. All methods belong to the configured `agent` client. A `?` marks an optional argument or field. Signatures describe types. Examples import the quickstart client. Replace uppercase IDs, file URLs, saved keys, and example revisions before execution. Read the [request limits](/docs/documentation/agent/sdk/responses#request-fields) before constructing an `AgentRequest`. See [client configuration](/docs/documentation/agent/sdk/configuration) for setup and retry behavior. ## Responses ### responses.answer Answer a pending clarification or approval. Use the request ID and permitted answers from the current pending input. ```typescript Signature theme={null} ( id: string, input: { input_request_id: string; answer: AgentAnswer; }, options?: AgentRequestOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.responses.answer( "RESPONSE_ID", { input_request_id: "INPUT_REQUEST_ID", answer: { kind: "approval", decision: "approve", }, }, { idempotencyKey: "SAVED_ANSWER_KEY" }, ); console.log(result); ``` Guide: [responses](/docs/documentation/agent/sdk/responses). Types: [AgentAnswer](/docs/documentation/agent/sdk/types#agentanswer), [AgentRequestOptions](/docs/documentation/agent/sdk/types#agentrequestoptions), [AgentResponseView](/docs/documentation/agent/sdk/types#agentresponseview). ### responses.cancel Request server cancellation. Observe the same response to confirm its final state. ```typescript Signature theme={null} (id: string, options?: AgentRequestOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.responses.cancel("RESPONSE_ID"); console.log(result); ``` Guide: [responses](/docs/documentation/agent/sdk/responses). Types: [AgentRequestOptions](/docs/documentation/agent/sdk/types#agentrequestoptions), [AgentResponseView](/docs/documentation/agent/sdk/types#agentresponseview). ### responses.create Submit a task and return its accepted snapshot. Save the response ID before observing execution. ```typescript Signature theme={null} ( request: AgentRequest, options?: AgentRequestOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.responses.create( { input: "Generate a blue ceramic mug." }, { idempotencyKey: "SAVED_COMMAND_KEY" }, ); console.log(result); ``` Guide: [responses](/docs/documentation/agent/sdk/responses). Types: [AgentRequest](/docs/documentation/agent/sdk/types#agentrequest), [AgentRequestOptions](/docs/documentation/agent/sdk/types#agentrequestoptions), [AgentResponseView](/docs/documentation/agent/sdk/types#agentresponseview). ### responses.retrieve Read one response snapshot. This method does not wait for execution to finish. ```typescript Signature theme={null} (id: string, options?: AgentRequestOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.responses.retrieve("RESPONSE_ID"); console.log(result); ``` Guide: [responses](/docs/documentation/agent/sdk/responses). Types: [AgentRequestOptions](/docs/documentation/agent/sdk/types#agentrequestoptions), [AgentResponseView](/docs/documentation/agent/sdk/types#agentresponseview). ### responses.selectFinalArtifacts Save the final artifact selection. Send the current sequence number to detect conflicting writes. Replace the example cursor with the current snapshot sequence. ```typescript Signature theme={null} ( id: string, input: { artifact_ids: string[]; expected_sequence_number: number; }, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.responses.selectFinalArtifacts( "RESPONSE_ID", { artifact_ids: ["ARTIFACT_ID"], expected_sequence_number: 12, }, ); console.log(result); ``` Guide: [responses](/docs/documentation/agent/sdk/responses). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentResponseView](/docs/documentation/agent/sdk/types#agentresponseview). ### responses.stream Stream complete snapshots of an existing response. Replace displayed state on each update. ```typescript Signature theme={null} (id: string, options?: AgentStreamOptions) => AsyncIterable; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; for await (const response of agent.responses.stream( "RESPONSE_ID", )) { console.log(response.output_text); } ``` Guide: [responses](/docs/documentation/agent/sdk/responses). Types: [AgentStreamOptions](/docs/documentation/agent/sdk/types#agentstreamoptions), [AgentResponseView](/docs/documentation/agent/sdk/types#agentresponseview). ### responses.wait Poll an existing response until it stops or requires input. A timeout only stops local observation. ```typescript Signature theme={null} (id: string, options?: AgentRunOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.responses.wait( "RESPONSE_ID", { timeoutMs: 60_000 }, ); console.log(result); ``` Guide: [responses](/docs/documentation/agent/sdk/responses). Types: [AgentRunOptions](/docs/documentation/agent/sdk/types#agentrunoptions), [AgentResponseView](/docs/documentation/agent/sdk/types#agentresponseview). ### run Create a response and poll until execution stops or requires input. This method can incur generation charges. ```typescript Signature theme={null} ( request: AgentRequest, options?: AgentRunOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.run({ input: "Generate a blue ceramic mug.", }); console.log(result); ``` Guide: [responses](/docs/documentation/agent/sdk/responses). Types: [AgentRequest](/docs/documentation/agent/sdk/types#agentrequest), [AgentRunOptions](/docs/documentation/agent/sdk/types#agentrunoptions), [AgentResponseView](/docs/documentation/agent/sdk/types#agentresponseview). ### stream Create a response and yield complete snapshots. This method starts new work each time you call it. ```typescript Signature theme={null} ( request: AgentRequest, options?: AgentStreamOptions, ) => AsyncIterable; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; for await (const response of agent.stream({ input: "Generate a blue ceramic mug.", })) { console.log(response.output_text); } ``` Guide: [responses](/docs/documentation/agent/sdk/responses). Types: [AgentRequest](/docs/documentation/agent/sdk/types#agentrequest), [AgentStreamOptions](/docs/documentation/agent/sdk/types#agentstreamoptions), [AgentResponseView](/docs/documentation/agent/sdk/types#agentresponseview). ## Conversations ### conversations.create Create an idle conversation. An omitted title or null title leaves the conversation untitled. ```typescript Signature theme={null} ( input?: { title?: string | null }, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.conversations.create({ title: "Product campaign", }); console.log(result); ``` Guide: [resources](/docs/documentation/agent/sdk/resources). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentConversation](/docs/documentation/agent/sdk/types#agentconversation). ### conversations.delete Delete a conversation. Repeat the request when deleted is false, after running work stops. ```typescript Signature theme={null} (id: string, options?: AgentRequestOptions) => Promise<{ id: string; deleted: boolean }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.conversations.delete( "CONVERSATION_ID", ); console.log(result); ``` Guide: [resources](/docs/documentation/agent/sdk/resources). Types: [AgentRequestOptions](/docs/documentation/agent/sdk/types#agentrequestoptions). ### conversations.fork Copy settled conversation history into a new conversation. Set atMessageId to copy through that message's completed turn. Active turns are excluded. Project placement completes asynchronously. ```typescript Signature theme={null} ( id: string, input?: { atMessageId?: string; createProject?: boolean; }, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const fork = await agent.conversations.fork( "CONVERSATION_ID", { atMessageId: "MESSAGE_ID", }, ); console.log(fork.id); ``` Guide: [resources](/docs/documentation/agent/sdk/resources). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentConversation](/docs/documentation/agent/sdk/types#agentconversation). ### conversations.generationSummary Read billed generation costs and counts. Nano-USD totals exclude unpriced requests and LLM usage. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.conversations.generationSummary( "CONVERSATION_ID", ); console.log(result); ``` Guide: [resources](/docs/documentation/agent/sdk/resources). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentGenerationSummary](/docs/documentation/agent/sdk/types#agentgenerationsummary). ### conversations.items.list Read conversation history with cursor pagination. Restart pagination after a snapshot conflict. ```typescript Signature theme={null} (id: string, options?: AgentPageOptions) => Promise>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.conversations.items.list( "CONVERSATION_ID", { limit: 20 }, ); console.log(result); ``` Guide: [resources](/docs/documentation/agent/sdk/resources). Types: [AgentPageOptions](/docs/documentation/agent/sdk/types#agentpageoptions), [AgentPage](/docs/documentation/agent/sdk/types#agentpage), [AgentConversationItem](/docs/documentation/agent/sdk/types#agentconversationitem). ### conversations.list List conversations with cursor pagination. Use next\_cursor for the next page. ```typescript Signature theme={null} (options?: AgentPageOptions) => Promise>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.conversations.list({ limit: 20, }); console.log(result); ``` Guide: [resources](/docs/documentation/agent/sdk/resources). Types: [AgentPageOptions](/docs/documentation/agent/sdk/types#agentpageoptions), [AgentPage](/docs/documentation/agent/sdk/types#agentpage), [AgentConversation](/docs/documentation/agent/sdk/types#agentconversation). ### conversations.retrieve Read a conversation's title and active response IDs. ```typescript Signature theme={null} (id: string, options?: AgentRequestOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.conversations.retrieve( "CONVERSATION_ID", ); console.log(result); ``` Guide: [resources](/docs/documentation/agent/sdk/resources). Types: [AgentRequestOptions](/docs/documentation/agent/sdk/types#agentrequestoptions), [AgentConversation](/docs/documentation/agent/sdk/types#agentconversation). ### conversations.sharing.retrieve Read the conversation's share policy, or null if none exists. The policy ID identifies its /chat/share/ link on the fal website. Empty recipient lists allow anyone with the link. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const share = await agent.conversations.sharing.retrieve( "CONVERSATION_ID", ); console.log(share?.policy); ``` Guide: [resources](/docs/documentation/agent/sdk/resources). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentConversationSharePolicy](/docs/documentation/agent/sdk/types#agentconversationsharepolicy). ### conversations.sharing.update Create or replace the conversation's share policy. Specify account IDs or email addresses to restrict access. Empty recipients make the link public. expiresAt accepts an ISO 8601 timestamp; omit it or pass null to remove expiration. ```typescript Signature theme={null} ( id: string, input: AgentConversationSharingInput, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const share = await agent.conversations.sharing.update( "CONVERSATION_ID", { emails: ["reviewer@example.com"] }, ); console.log(share.id); ``` Guide: [resources](/docs/documentation/agent/sdk/resources). Types: [AgentConversationSharingInput](/docs/documentation/agent/sdk/types#agentconversationsharinginput), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentConversationSharePolicy](/docs/documentation/agent/sdk/types#agentconversationsharepolicy). ### conversations.update Rename a conversation. Read it after an uncertain acknowledgement before repeating the write. ```typescript Signature theme={null} ( id: string, change: { title: string }, options?: AgentRequestOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.conversations.update( "CONVERSATION_ID", { title: "Mug concepts" }, ); console.log(result); ``` Guide: [resources](/docs/documentation/agent/sdk/resources). Types: [AgentRequestOptions](/docs/documentation/agent/sdk/types#agentrequestoptions), [AgentConversation](/docs/documentation/agent/sdk/types#agentconversation). ## Plans ### plans.retrieve Read a plan block within its owning conversation. ```typescript Signature theme={null} ( id: string, options: AgentRequestOptions & { conversation: string; }, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.plans.retrieve( "PLAN_ID", { conversation: "CONVERSATION_ID" }, ); console.log(result); ``` Guide: [plans](/docs/documentation/agent/sdk/plans). Types: [AgentRequestOptions](/docs/documentation/agent/sdk/types#agentrequestoptions), [AgentPlanBlock](/docs/documentation/agent/sdk/types#agentplanblock). ### plans.run Run a plan at its current revision. Replace the example revision with the value returned by `plans.retrieve`. Save an idempotency key before submission. ```typescript Signature theme={null} ( id: string, input: { conversation: string; expected_revision: number; }, options?: AgentRequestOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.plans.run( "PLAN_ID", { conversation: "CONVERSATION_ID", expected_revision: 3, }, { idempotencyKey: "SAVED_PLAN_KEY" }, ); console.log(result); ``` Guide: [plans](/docs/documentation/agent/sdk/plans). Types: [AgentRequestOptions](/docs/documentation/agent/sdk/types#agentrequestoptions), [AgentResponseView](/docs/documentation/agent/sdk/types#agentresponseview). ### plans.update Replace the editable step list at the specified revision. Preserve step IDs to retain existing steps. The example replaces the complete list with one step at revision 3. ```typescript Signature theme={null} ( id: string, change: AgentPlanUpdate, options?: AgentRequestOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.plans.update( "PLAN_ID", { conversation: "CONVERSATION_ID", expected_revision: 3, steps: [ { id: "STEP_ID", label: "Generate a product photo", model_pinned: false, requires_approval: true, }, ], }, { idempotencyKey: "SAVED_EDIT_KEY" }, ); console.log(result); ``` Guide: [plans](/docs/documentation/agent/sdk/plans). Types: [AgentPlanUpdate](/docs/documentation/agent/sdk/types#agentplanupdate), [AgentRequestOptions](/docs/documentation/agent/sdk/types#agentrequestoptions), [AgentPlanBlock](/docs/documentation/agent/sdk/types#agentplanblock). ## Artifacts ### artifacts.retrieve Read an artifact. Omit revision for the available current version. ```typescript Signature theme={null} ( id: string, options?: AgentRequestOptions & { revision?: 1 }, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.artifacts.retrieve("ARTIFACT_ID"); console.log(result); ``` Guide: [media](/docs/documentation/agent/sdk/media). Types: [AgentRequestOptions](/docs/documentation/agent/sdk/types#agentrequestoptions), [AgentArtifact](/docs/documentation/agent/sdk/types#agentartifact). ## Projects ### projects.assets.attach Attach an existing asset to a project. Use its assetId or library assetRecordId. ```typescript Signature theme={null} ( id: string, assetId: string, options?: AgentResourceOptions, ) => Promise<{ success: true }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.assets.attach( "PROJECT_ID", "ASSET_ID", ); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### projects.assets.detach Detach an asset from a project without deleting its source file. ```typescript Signature theme={null} ( id: string, assetId: string, options?: AgentResourceOptions, ) => Promise<{ success: true }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.assets.detach( "PROJECT_ID", "ASSET_ID", ); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### projects.collections.attach Attach an existing collection to a project. ```typescript Signature theme={null} ( id: string, collectionId: string, options?: AgentResourceOptions, ) => Promise<{ success: true }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.collections.attach( "PROJECT_ID", "COLLECTION_ID", ); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### projects.collections.detach Remove a collection's project association. ```typescript Signature theme={null} ( id: string, collectionId: string, options?: AgentResourceOptions, ) => Promise<{ success: true }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.collections.detach( "PROJECT_ID", "COLLECTION_ID", ); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### projects.conversations.add Add an existing conversation to a project. ```typescript Signature theme={null} ( id: string, conversation: string, options?: AgentResourceOptions, ) => Promise<{ success: true }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.conversations.add( "PROJECT_ID", "CONVERSATION_ID", ); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### projects.conversations.create Create an idle conversation within a project. ```typescript Signature theme={null} ( id: string, input?: { title?: string | null }, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.conversations.create( "PROJECT_ID", { title: "Product concepts" }, ); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentConversation](/docs/documentation/agent/sdk/types#agentconversation). ### projects.conversations.list List visible conversations in a project. This method returns an array without a pagination cursor. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.conversations.list( "PROJECT_ID", ); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentProjectConversation](/docs/documentation/agent/sdk/types#agentprojectconversation). ### projects.conversations.remove Remove a conversation's project association. This does not delete the conversation. ```typescript Signature theme={null} ( id: string, conversation: string, options?: AgentResourceOptions, ) => Promise<{ success: true }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.conversations.remove( "PROJECT_ID", "CONVERSATION_ID", ); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### projects.conversations.setMemoryPrivacy Set excluded to true to exclude the conversation from project memory. The conversation must belong to the project. ```typescript Signature theme={null} ( id: string, conversation: string, excluded: boolean, options?: AgentResourceOptions, ) => Promise<{ success: true }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.conversations.setMemoryPrivacy( "PROJECT_ID", "CONVERSATION_ID", true, ); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### projects.create Create a project with a name and optional color. ```typescript Signature theme={null} ( input: { name: string; color?: string }, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.create({ name: "Autumn campaign", }); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentProject](/docs/documentation/agent/sdk/types#agentproject). ### projects.delete Delete the project association and project-scoped resources. This does not delete its conversations or source media. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise<{ success: true }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.delete("PROJECT_ID"); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### projects.documents.attach Attach a fal storage URL and extracted text. Replace the sample file URL, metadata, and text with your uploaded document. ```typescript Signature theme={null} ( id: string, input: AgentProjectDocumentInput, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.documents.attach( "PROJECT_ID", { url: "https://fal.media/files/FILE_ID/brief.txt", fileName: "brief.txt", contentType: "text/plain", sizeBytes: 16, text: "Blue background.", }, ); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentProjectDocumentInput](/docs/documentation/agent/sdk/types#agentprojectdocumentinput), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentProjectDocument](/docs/documentation/agent/sdk/types#agentprojectdocument). ### projects.documents.import Extract and attach a document already uploaded to supported fal storage. The server downloads at most 25 MiB without following redirects. MIME type can be inferred from the filename. PDF and DOCX text is extracted automatically. Empty documents have no\_text status. ```typescript Signature theme={null} ( id: string, input: AgentProjectDocumentImport, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const document = await agent.projects.documents.import( "project_id", { url: "https://fal.media/files/brief.pdf", fileName: "brief.pdf", }, ); console.log(document.status); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentProjectDocumentImport](/docs/documentation/agent/sdk/types#agentprojectdocumentimport), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentProjectDocument](/docs/documentation/agent/sdk/types#agentprojectdocument). ### projects.documents.list List project documents and their processing status. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.documents.list("PROJECT_ID"); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentProjectDocument](/docs/documentation/agent/sdk/types#agentprojectdocument). ### projects.documents.preview Read a document's extracted text. Use the document's assetId. ```typescript Signature theme={null} ( id: string, assetId: string, options?: AgentResourceOptions, ) => Promise<{ text: string; truncated: boolean }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.documents.preview( "PROJECT_ID", "ASSET_ID", ); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### projects.documents.remove Remove the document from the project. Use the document's assetId. ```typescript Signature theme={null} ( id: string, assetId: string, options?: AgentResourceOptions, ) => Promise<{ success: true }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.documents.remove( "PROJECT_ID", "ASSET_ID", ); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### projects.documents.retry Retry document processing. Read its status after submission. ```typescript Signature theme={null} ( id: string, assetId: string, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.documents.retry( "PROJECT_ID", "ASSET_ID", ); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentProjectDocument](/docs/documentation/agent/sdk/types#agentprojectdocument). ### projects.documents.upload Upload a document, extract its text, and attach it to a project. Supports PDF, DOCX, and text files up to 25 MiB. Ingestion continues in the background; poll documents.list for its status. Uploads use fal storage credentials configured on the client. Aborting observation does not undo an uploaded file. ```typescript Signature theme={null} ( id: string, file: File, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const file = new File( ["Use warm colors."], "brief.txt", { type: "text/plain", }, ); const document = await agent.projects.documents.upload( "project_id", file, ); console.log(document.status); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentProjectDocument](/docs/documentation/agent/sdk/types#agentprojectdocument). ### projects.list List project summaries, including counts and cover media. ```typescript Signature theme={null} (options?: AgentResourceOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.list(); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentProjectSummary](/docs/documentation/agent/sdk/types#agentprojectsummary). ### projects.memory.create Create a memory note. supersededId identifies a note replaced by this operation, when present. ```typescript Signature theme={null} ( id: string, input: { kind: AgentMemoryKind; content: string }, options?: AgentResourceOptions, ) => Promise<{ id: string; supersededId: string | null; }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.memory.create( "PROJECT_ID", { kind: "style", content: "Use a blue background.", }, ); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentMemoryKind](/docs/documentation/agent/sdk/types#agentmemorykind), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### projects.memory.retrieve Read the project's primer and active memory notes. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.memory.retrieve( "PROJECT_ID", ); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentProjectMemory](/docs/documentation/agent/sdk/types#agentprojectmemory). ### projects.memory.update Edit, pin, delete, or restore a memory note within the project. ```typescript Signature theme={null} ( id: string, noteId: string, input: { content?: string; pinned?: boolean; status?: "active" | "deleted"; }, options?: AgentResourceOptions, ) => Promise<{ success: true }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.memory.update( "PROJECT_ID", "NOTE_ID", { pinned: true }, ); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### projects.resources Read attached media, collections, characters, smart entities, and generated media. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.resources("PROJECT_ID"); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentProjectResources](/docs/documentation/agent/sdk/types#agentprojectresources). ### projects.retrieve Read project identity, name, color, and creation time. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.retrieve("PROJECT_ID"); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentProject](/docs/documentation/agent/sdk/types#agentproject). ### projects.update Change a project's name, color, or both. Supply at least one field. ```typescript Signature theme={null} ( id: string, input: { name?: string; color?: string }, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.projects.update( "PROJECT_ID", { name: "Winter campaign" }, ); console.log(result); ``` Guide: [projects](/docs/documentation/agent/sdk/projects). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentProject](/docs/documentation/agent/sdk/types#agentproject). ## Models ### models.capabilities Read a generation model's configurable fields, required flags, and default values. ```typescript Signature theme={null} ( endpointId: string, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.models.capabilities( "MODEL_ENDPOINT_ID", ); console.log(result); ``` Guide: [settings](/docs/documentation/agent/sdk/settings). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentModelCapabilities](/docs/documentation/agent/sdk/types#agentmodelcapabilities). ### models.list Search generation models. Use page-based pagination, not a history cursor. ```typescript Signature theme={null} ( filter?: { keywords?: string; categories?: string[]; page?: number; limit?: number; }, options?: AgentResourceOptions, ) => Promise<{ items: AgentModel[]; total?: number | null; page?: number; size?: number; pages?: number | null; }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.models.list({ keywords: "image", page: 1, limit: 10, }); console.log(result); ``` Guide: [settings](/docs/documentation/agent/sdk/settings). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentModel](/docs/documentation/agent/sdk/types#agentmodel). ### models.listAgentModels List available reasoning models. Use these IDs for the defaultModel account preference. ```typescript Signature theme={null} (options?: AgentResourceOptions) => Promise< { id: string; label: string; tag?: "recommended" | "experimental"; }[] >; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.models.listAgentModels(); console.log(result); ``` Guide: [settings](/docs/documentation/agent/sdk/settings). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ## Settings ### settings.conversations.retrieve Read generation settings for a conversation. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const settings = await agent.settings.conversations.retrieve( "CONVERSATION_ID", ); console.log(settings); ``` Guide: [settings](/docs/documentation/agent/sdk/settings). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentGenerationSettings](/docs/documentation/agent/sdk/types#agentgenerationsettings). ### settings.conversations.update Replace conversation settings with the expected revision. Preserve unrelated fields from the latest read. ```typescript Signature theme={null} ( id: string, input: { settings: AgentGenerationSettings; expectedRevision: number; }, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const settings = await agent.settings.conversations.retrieve( "CONVERSATION_ID", ); const result = await agent.settings.conversations.update( "CONVERSATION_ID", { settings: { ...settings, reviewBeforeGenerating: true, }, expectedRevision: settings.revision, }, ); console.log(result); ``` Guide: [settings](/docs/documentation/agent/sdk/settings). Types: [AgentGenerationSettings](/docs/documentation/agent/sdk/types#agentgenerationsettings), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### settings.defaults.retrieve Read local, inherited, and effective generation defaults with their sources. ```typescript Signature theme={null} ( target: AgentDefaultsTarget, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.settings.defaults.retrieve({ scope: "personal", }); console.log(result); ``` Guide: [settings](/docs/documentation/agent/sdk/settings). Types: [AgentDefaultsTarget](/docs/documentation/agent/sdk/types#agentdefaultstarget), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentDefaultsView](/docs/documentation/agent/sdk/types#agentdefaultsview). ### settings.defaults.update Change or inherit defaults. Send the last local object as expectedLocal to detect conflicting edits. ```typescript Signature theme={null} ( target: AgentDefaultsTarget, input: AgentDefaultsUpdate, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const target = { scope: "personal" } as const; const defaults = await agent.settings.defaults.retrieve(target); const result = await agent.settings.defaults.update( target, { expectedLocal: defaults.local, changes: { preferences: { aspect_ratio: "16:9" }, preferredModels: {}, }, }, ); console.log(result.effective); ``` Guide: [settings](/docs/documentation/agent/sdk/settings). Types: [AgentDefaultsTarget](/docs/documentation/agent/sdk/types#agentdefaultstarget), [AgentDefaultsUpdate](/docs/documentation/agent/sdk/types#agentdefaultsupdate), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentDefaultsView](/docs/documentation/agent/sdk/types#agentdefaultsview). ### settings.projects.retrieve Read generation settings saved on a project. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const settings = await agent.settings.projects.retrieve( "PROJECT_ID", ); console.log(settings); ``` Guide: [settings](/docs/documentation/agent/sdk/settings). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentGenerationSettings](/docs/documentation/agent/sdk/types#agentgenerationsettings). ### settings.projects.update Replace project settings with the expected revision. Preserve unrelated fields from the latest read. ```typescript Signature theme={null} ( id: string, input: { settings: AgentGenerationSettings; expectedRevision: number; }, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const settings = await agent.settings.projects.retrieve( "PROJECT_ID", ); const result = await agent.settings.projects.update( "PROJECT_ID", { settings: { ...settings, reviewBeforeGenerating: true, }, expectedRevision: settings.revision, }, ); console.log(result); ``` Guide: [settings](/docs/documentation/agent/sdk/settings). Types: [AgentGenerationSettings](/docs/documentation/agent/sdk/types#agentgenerationsettings), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ## Preferences ### preferences.retrieve Read account preferences, including generation defaults. ```typescript Signature theme={null} (options?: AgentResourceOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.preferences.retrieve(); console.log(result); ``` Guide: [settings](/docs/documentation/agent/sdk/settings). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentPreferences](/docs/documentation/agent/sdk/types#agentpreferences). ### preferences.update Update fields within one preference section. The section determines the accepted input fields. ```typescript Signature theme={null} < S extends | "general" | "cost" | "skills" | "notifications", >( section: S, input: Partial, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.preferences.update( "notifications", { turnComplete: false }, ); console.log(result); ``` Guide: [settings](/docs/documentation/agent/sdk/settings). Types: [AgentPreferences](/docs/documentation/agent/sdk/types#agentpreferences), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ## Queue ### queue.cancel Cancel a queued turn by its turn ID. ```typescript Signature theme={null} ( conversation: string, turnId: string, options?: AgentResourceOptions, ) => Promise<{ success: boolean }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.queue.cancel( "CONVERSATION_ID", "TURN_ID", ); console.log(result); ``` Guide: [queue](/docs/documentation/agent/sdk/queue). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### queue.dispatch Attempt to dispatch eligible queued work. promoted false means this call did not start a turn. ```typescript Signature theme={null} ( conversation: string, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.queue.dispatch( "CONVERSATION_ID", ); console.log(result); ``` Guide: [queue](/docs/documentation/agent/sdk/queue). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentQueueDispatch](/docs/documentation/agent/sdk/types#agentqueuedispatch). ### queue.edit Replace a queued prompt with 1–10,000 characters. This does not edit a running response. ```typescript Signature theme={null} ( conversation: string, turnId: string, content: string, options?: AgentResourceOptions, ) => Promise<{ success: boolean }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.queue.edit( "CONVERSATION_ID", "TURN_ID", "Use a blue background.", ); console.log(result); ``` Guide: [queue](/docs/documentation/agent/sdk/queue). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### queue.reorder Reorder queued turns by turn ID. Supply at most 50 IDs. Steps within a plan retain their required order. Retrieve the queue for its effective order. ```typescript Signature theme={null} ( conversation: string, turnIds: string[], options?: AgentResourceOptions, ) => Promise<{ success: boolean }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.queue.reorder( "CONVERSATION_ID", ["TURN_ID_1", "TURN_ID_2"], ); console.log(result); ``` Guide: [queue](/docs/documentation/agent/sdk/queue). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### queue.retrieve Read queued turns and active turn IDs for a conversation. ```typescript Signature theme={null} ( conversation: string, options?: AgentResourceOptions, ) => Promise<{ items: AgentQueueItem[]; active_turn_ids: string[]; }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.queue.retrieve( "CONVERSATION_ID", ); console.log(result); ``` Guide: [queue](/docs/documentation/agent/sdk/queue). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentQueueItem](/docs/documentation/agent/sdk/types#agentqueueitem). ### queue.run Request immediate execution of a queued turn. This can bypass its normal queue position. ```typescript Signature theme={null} ( conversation: string, turnId: string, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.queue.run( "CONVERSATION_ID", "TURN_ID", ); console.log(result); ``` Guide: [queue](/docs/documentation/agent/sdk/queue). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentQueueDispatch](/docs/documentation/agent/sdk/types#agentqueuedispatch). ### queue.setApproval Change a continuation's approval requirement. Removing the requirement can dispatch work immediately. ```typescript Signature theme={null} ( conversation: string, turnId: string, input: { requiresApproval: boolean; approveCheckpoints?: boolean; }, options?: AgentResourceOptions, ) => Promise<{ updated: boolean; dispatch: AgentQueueDispatch | null; }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.queue.setApproval( "CONVERSATION_ID", "TURN_ID", { requiresApproval: true }, ); console.log(result); ``` Guide: [queue](/docs/documentation/agent/sdk/queue). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentQueueDispatch](/docs/documentation/agent/sdk/types#agentqueuedispatch). ### queue.setHalted Pause or resume queue dispatch. Resuming also attempts to dispatch eligible work. ```typescript Signature theme={null} ( conversation: string, halted: boolean, options?: AgentResourceOptions, ) => Promise<{ updatedCount: number; dispatch: AgentQueueDispatch | null; }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.queue.setHalted( "CONVERSATION_ID", true, ); console.log(result); ``` Guide: [queue](/docs/documentation/agent/sdk/queue). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentQueueDispatch](/docs/documentation/agent/sdk/types#agentqueuedispatch). ## Runs ### runs.answer Answer a cost approval from the retrieved run. The decision applies to its approval group. ```typescript Signature theme={null} ( id: string, conversation: string, input: { input_request_id: string; decision: "approve" | "reject"; }, options?: AgentResourceOptions, ) => Promise<{ submittedCount?: number; failedCount?: number; cancelledCount?: number; }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.runs.answer( "RUN_ID", "CONVERSATION_ID", { input_request_id: "INPUT_REQUEST_ID", decision: "approve", }, ); console.log(result); ``` Guide: [queue](/docs/documentation/agent/sdk/queue). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### runs.cancel Request cancellation of a generation run. Inspect cancelled and retrieve the run afterward. ```typescript Signature theme={null} ( id: string, conversation: string, options?: AgentResourceOptions, ) => Promise<{ cancelled: boolean }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.runs.cancel( "RUN_ID", "CONVERSATION_ID", ); console.log(result); ``` Guide: [queue](/docs/documentation/agent/sdk/queue). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### runs.retrieve Read a generation run's operation, artifacts, and pending cost approvals. ```typescript Signature theme={null} ( id: string, conversation: string, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.runs.retrieve( "RUN_ID", "CONVERSATION_ID", ); console.log(result); ``` Guide: [queue](/docs/documentation/agent/sdk/queue). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentRunView](/docs/documentation/agent/sdk/types#agentrunview). ### runs.retry Request another generation attempt. This can incur charges and require a new approval. ```typescript Signature theme={null} ( id: string, conversation: string, options?: AgentResourceOptions, ) => Promise<{ mediaId: string; runId: string; attempt: number; requestId: string; approvalRequired?: boolean; }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.runs.retry( "RUN_ID", "CONVERSATION_ID", ); console.log(result); ``` Guide: [queue](/docs/documentation/agent/sdk/queue). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ## Library ### library.assets.assignTag Assign an existing tag to an asset record. ```typescript Signature theme={null} ( id: string, tagId: string, options?: AgentResourceOptions, ) => Promise<{ success: true }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; await agent.library.assets.assignTag( "ASSET_RECORD_ID", "TAG_ID", ); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### library.assets.delete Delete a library asset using its assetRecordId. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise<{ success: true }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.library.assets.delete( "ASSET_RECORD_ID", ); console.log(result); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### library.assets.list Search library assets. Follow nextCursor and inspect scopeTruncated before treating the result as complete. ```typescript Signature theme={null} ( input?: AgentLibraryAssetQuery, options?: AgentResourceOptions, ) => Promise<{ items: AgentLibraryAsset[]; nextCursor: string | null; totalCount: number | null; scopeTruncated: boolean; }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.library.assets.list({ mediaTypes: ["image"], limit: 20, }); console.log(result); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentLibraryAssetQuery](/docs/documentation/agent/sdk/types#agentlibraryassetquery), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryAsset](/docs/documentation/agent/sdk/types#agentlibraryasset). ### library.assets.register Register a media URL returned by fal storage. Replace the sample URL with your uploaded media URL. ```typescript Signature theme={null} ( input: { url: string; type: AgentLibraryMediaType; size?: number; collectionId?: string | null; favorite?: boolean; }, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.library.assets.register({ url: "https://fal.media/files/FILE_ID/mug.png", type: "image", }); console.log(result); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentLibraryMediaType](/docs/documentation/agent/sdk/types#agentlibrarymediatype), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryAsset](/docs/documentation/agent/sdk/types#agentlibraryasset). ### library.assets.removeTag Remove a tag assignment without deleting the tag or asset. ```typescript Signature theme={null} ( id: string, tagId: string, options?: AgentResourceOptions, ) => Promise<{ success: true }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; await agent.library.assets.removeTag( "ASSET_RECORD_ID", "TAG_ID", ); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### library.assets.retrieve Read asset metadata using its library assetRecordId. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.library.assets.retrieve( "ASSET_RECORD_ID", ); console.log(result); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryAsset](/docs/documentation/agent/sdk/types#agentlibraryasset). ### library.assets.setFavorite Set an asset's favorite state using its assetRecordId. ```typescript Signature theme={null} ( id: string, favorite: boolean, options?: AgentResourceOptions, ) => Promise<{ assetRecordId: string; assetId: null; isFavorited: boolean; }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.library.assets.setFavorite( "ASSET_RECORD_ID", true, ); console.log(result); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### library.assets.tags Read the tags assigned to an asset record. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const tags = await agent.library.assets.tags( "ASSET_RECORD_ID", ); console.log(tags); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryTag](/docs/documentation/agent/sdk/types#agentlibrarytag). ### library.assets.updatePrompt Update an uploaded asset's prompt with 1–2,000 characters. Generated assets do not support this operation. ```typescript Signature theme={null} ( id: string, prompt: string, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.library.assets.updatePrompt( "ASSET_RECORD_ID", "Blue ceramic mug", ); console.log(result); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryAsset](/docs/documentation/agent/sdk/types#agentlibraryasset). ### library.characters.checkIdentifier Normalize a proposed character identifier and check availability. Creation can still fail if another request takes it first. ```typescript Signature theme={null} ( identifier: string, options?: AgentResourceOptions, ) => Promise<{ identifier: string; available: boolean; }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.library.characters.checkIdentifier( "milo", ); console.log(result); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### library.characters.create Create a character from a description and one to twenty reference images. References accept fal-hosted URLs or existing asset targets. ```typescript Signature theme={null} ( input: AgentCharacterInput & { identifier?: string; }, options?: AgentResourceOptions, ) => Promise< AgentLibraryCollection & { type: "character" } >; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const character = await agent.library.characters.create({ name: "Milo", identifier: "milo", description: "A gray cat with green eyes.", referenceImages: [ "https://fal.media/files/REFERENCE.png", ], }); console.log(character); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentCharacterInput](/docs/documentation/agent/sdk/types#agentcharacterinput), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryCollection](/docs/documentation/agent/sdk/types#agentlibrarycollection). ### library.characters.references Read reference image URLs and asset record IDs. Exclude entries with isCover when saving the reference list. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const references = await agent.library.characters.references( "CHARACTER_ID", ); console.log(references); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentCharacterReference](/docs/documentation/agent/sdk/types#agentcharacterreference). ### library.characters.update Replace a character name, description, and complete reference list. Character identifiers cannot be changed. ```typescript Signature theme={null} ( id: string, input: AgentCharacterInput, options?: AgentResourceOptions, ) => Promise< AgentLibraryCollection & { type: "character" } >; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const character = await agent.library.characters.update( "CHARACTER_ID", { name: "Milo", description: "A gray cat with green eyes.", referenceImages: [ "https://fal.media/files/REFERENCE.png", ], }, ); console.log(character); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentCharacterInput](/docs/documentation/agent/sdk/types#agentcharacterinput), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryCollection](/docs/documentation/agent/sdk/types#agentlibrarycollection). ### library.collections.addAsset Add an asset to a manual collection or smart entity gallery. Use the assetRecordId. This does not change defining references. ```typescript Signature theme={null} ( id: string, assetRecordId: string, options?: AgentResourceOptions, ) => Promise<{ collectionId: string; assetRecordId: string; }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.library.collections.addAsset( "COLLECTION_ID", "ASSET_RECORD_ID", ); console.log(result); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### library.collections.create Create a manual collection or a smart collection with filters. ```typescript Signature theme={null} ( input: AgentCollectionInput, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.library.collections.create({ name: "Mugs", }); console.log(result); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentCollectionInput](/docs/documentation/agent/sdk/types#agentcollectioninput), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryCollection](/docs/documentation/agent/sdk/types#agentlibrarycollection). ### library.collections.delete Delete a collection or smart entity through the shared product operation. This does not delete its source assets. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise<{ success: true }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.library.collections.delete( "COLLECTION_ID", ); console.log(result); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### library.collections.list List collections with offset pagination. includeCharacters preserves character inclusion. Set includeSmartEntities to true to include all five entity types. ```typescript Signature theme={null} ( input?: { limit?: number; offset?: number; includeCharacters?: boolean; includeSmartEntities?: boolean; }, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.library.collections.list( { limit: 20, offset: 0, includeSmartEntities: true, }, ); console.log(result); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryCollection](/docs/documentation/agent/sdk/types#agentlibrarycollection). ### library.collections.move Move a collection under a parent. Use null to move it to the root. ```typescript Signature theme={null} ( id: string, parentCollectionId: string | null, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.library.collections.move( "COLLECTION_ID", null, ); console.log(result); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryCollection](/docs/documentation/agent/sdk/types#agentlibrarycollection). ### library.collections.removeAsset Remove a manual collection membership or smart entity gallery link. Assets, defining references, and recorded generation usage are preserved. ```typescript Signature theme={null} ( id: string, assetRecordId: string, options?: AgentResourceOptions, ) => Promise<{ success: true }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.library.collections.removeAsset( "COLLECTION_ID", "ASSET_RECORD_ID", ); console.log(result); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### library.collections.setFavorite Set a collection or smart entity's favorite state. ```typescript Signature theme={null} ( id: string, favorite: boolean, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.library.collections.setFavorite( "COLLECTION_ID", true, ); console.log(result); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryCollection](/docs/documentation/agent/sdk/types#agentlibrarycollection). ### library.collections.update Update collection metadata or filters. Use null to clear nullable fields. ```typescript Signature theme={null} ( id: string, input: { name?: string; description?: string | null; icon?: string | null; color?: string | null; coverImageUrl?: string | null; filters?: AgentCollectionFilter | null; }, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.library.collections.update( "COLLECTION_ID", { description: "Ceramic mug concepts" }, ); console.log(result); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentCollectionFilter](/docs/documentation/agent/sdk/types#agentcollectionfilter), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryCollection](/docs/documentation/agent/sdk/types#agentlibrarycollection). ### library.entities.addAsset Link an existing asset to an entity gallery. This does not change its defining reference images. ```typescript Signature theme={null} ( id: string, assetRef: string, options?: AgentResourceOptions, ) => Promise<{ smartEntityId: string; assetRecordId: string; }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; await agent.library.entities.addAsset( "ENTITY_ID", "ASSET_RECORD_ID", ); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### library.entities.checkHandle Normalize a handle and check availability across all five types. Set excludeId when editing. Availability does not reserve the handle. ```typescript Signature theme={null} ( input: { handle: string; excludeId?: string }, options?: AgentResourceOptions, ) => Promise<{ handle: string; available: boolean; }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.library.entities.checkHandle({ handle: "blue-mug", excludeId: "PROP_ID", }); console.log(result.handle, result.available); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### library.entities.create Create any smart entity type with one to twenty defining references. Characters require a description and reject custom metadata. ```typescript Signature theme={null} ( input: AgentLibraryEntityInput, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const entity = await agent.library.entities.create({ type: "prop", name: "Blue mug", handle: "blue-mug", referenceImages: [ "https://fal.media/files/MUG.png", ], }); console.log(entity); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentLibraryEntityInput](/docs/documentation/agent/sdk/types#agentlibraryentityinput), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryEntity](/docs/documentation/agent/sdk/types#agentlibraryentity). ### library.entities.delete Delete any smart entity type through the shared product operation. Source assets are preserved. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise<{ success: true }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; await agent.library.entities.delete("ENTITY_ID"); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### library.entities.list List smart entities with offset pagination. Filter by types or search names and handles. Omit types to include all five entity types. ```typescript Signature theme={null} ( input?: AgentLibraryEntityQuery, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const entities = await agent.library.entities.list({ types: [ "character", "prop", "environment", "style", "scene", ], limit: 100, offset: 0, }); console.log(entities); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentLibraryEntityQuery](/docs/documentation/agent/sdk/types#agentlibraryentityquery), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryEntity](/docs/documentation/agent/sdk/types#agentlibraryentity). ### library.entities.listAssets Read associated media with offset pagination. Set includeReferences to include images whose only association is defining reference membership. ```typescript Signature theme={null} ( id: string, input?: { mediaTypes?: AgentLibraryMediaType[]; limit?: number; offset?: number; includeReferences?: boolean; }, options?: AgentResourceOptions, ) => Promise<{ items: AgentLibraryAsset[]; nextOffset: number | null; totalCount: number; }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const page = await agent.library.entities.listAssets( "ENTITY_ID", { mediaTypes: ["image"], limit: 50, offset: 0 }, ); console.log( page.items, page.nextOffset, page.totalCount, ); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentLibraryMediaType](/docs/documentation/agent/sdk/types#agentlibrarymediatype), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryAsset](/docs/documentation/agent/sdk/types#agentlibraryasset). ### library.entities.removeAsset Remove a manual gallery link without deleting the asset. Recorded generation usage and defining reference images are preserved. ```typescript Signature theme={null} ( id: string, assetRef: string, options?: AgentResourceOptions, ) => Promise<{ success: true }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; await agent.library.entities.removeAsset( "ENTITY_ID", "ASSET_RECORD_ID", ); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### library.entities.resolve Resolve one to 100 handles within the account. Unknown handles are omitted. Use types to restrict the matching entity types. ```typescript Signature theme={null} ( input: { handles: string[]; types?: AgentLibraryEntityType[]; }, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const entities = await agent.library.entities.resolve({ handles: [ "@milo", "@blue-mug", "@workshop", "@watercolor", "@breakfast", ], }); console.log(entities); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentLibraryEntityType](/docs/documentation/agent/sdk/types#agentlibraryentitytype), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryEntity](/docs/documentation/agent/sdk/types#agentlibraryentity). ### library.entities.retrieve Read an entity and its defining reference-image URLs. The references exclude its associated-media gallery. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const entity = await agent.library.entities.retrieve( "ENTITY_ID", ); console.log( entity.type, entity.metadata, entity.references, ); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryEntity](/docs/documentation/agent/sdk/types#agentlibraryentity). ### library.entities.setFavorite Set the favorite state for any smart entity type. ```typescript Signature theme={null} ( id: string, favorite: boolean, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const entity = await agent.library.entities.setFavorite( "ENTITY_ID", true, ); console.log(entity); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryEntity](/docs/documentation/agent/sdk/types#agentlibraryentity). ### library.entities.update Update entity fields. Supplied references replace the complete defining set. Types and character handles cannot change. Character metadata is managed automatically. ```typescript Signature theme={null} ( id: string, input: AgentLibraryEntityUpdate, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const entity = await agent.library.entities.update( "PROP_ID", { description: "A blue ceramic mug with a rounded handle.", referenceImages: [ "https://fal.media/files/MUG_FRONT.png", "https://fal.media/files/MUG_SIDE.png", ], }, ); console.log(entity); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentLibraryEntityUpdate](/docs/documentation/agent/sdk/types#agentlibraryentityupdate), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryEntity](/docs/documentation/agent/sdk/types#agentlibraryentity). ### library.tags.create Create a tag. Names are trimmed and stored in lowercase. ```typescript Signature theme={null} ( input: { name: string; color?: string }, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const tag = await agent.library.tags.create({ name: "campaign", color: "blue", }); console.log(tag); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryTag](/docs/documentation/agent/sdk/types#agentlibrarytag). ### library.tags.delete Delete a tag and its asset assignments. This does not delete assets. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise<{ success: true }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; await agent.library.tags.delete("TAG_ID"); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### library.tags.list List available asset tags. System tags are excluded. ```typescript Signature theme={null} (options?: AgentResourceOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const tags = await agent.library.tags.list(); console.log(tags); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryTag](/docs/documentation/agent/sdk/types#agentlibrarytag). ### library.tags.update Change a tag name or color. Tag names must be unique within the account. ```typescript Signature theme={null} ( id: string, input: { name?: string; color?: string }, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const tag = await agent.library.tags.update( "TAG_ID", { name: "launch" }, ); console.log(tag); ``` Guide: [library](/docs/documentation/agent/sdk/library). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentLibraryTag](/docs/documentation/agent/sdk/types#agentlibrarytag). ## Skills ### skills.checkForUpdates Check an imported skill against its repository default branch. Custom and detached skills cannot check for updates. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise<{ currentSha: string | null; latestSha: string; hasUpdate: boolean; }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const update = await agent.skills.checkForUpdates("SKILL_ID"); console.log(update.hasUpdate); ``` Guide: [skills](/docs/documentation/agent/sdk/skills). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### skills.create Create a custom skill. Names use lowercase letters, digits, and hyphens. presetClash reports a matching fal skill. ```typescript Signature theme={null} ( input: AgentSkillContent, options?: AgentResourceOptions, ) => Promise<{ skill: AgentInstalledSkill; presetClash: boolean; }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const { skill } = await agent.skills.create({ name: "product-photos", description: "Create consistent product photos.", body: "Preserve the product shape and colors.", }); console.log(skill.id); ``` Guide: [skills](/docs/documentation/agent/sdk/skills). Types: [AgentSkillContent](/docs/documentation/agent/sdk/types#agentskillcontent), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentInstalledSkill](/docs/documentation/agent/sdk/types#agentinstalledskill). ### skills.importFromGithub Import a skill from a public GitHub repository. Script-based skills are unsupported. ```typescript Signature theme={null} ( input: AgentSkillSource, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const skill = await agent.skills.importFromGithub({ repoUrl: "https://github.com/OWNER/REPO", subpath: "skills/photo-editing", }); console.log(skill.id); ``` Guide: [skills](/docs/documentation/agent/sdk/skills). Types: [AgentSkillSource](/docs/documentation/agent/sdk/types#agentskillsource), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentInstalledSkill](/docs/documentation/agent/sdk/types#agentinstalledskill). ### skills.list List fal skills and your installed skills. Disabled and shadowed flags explain which skills are available. ```typescript Signature theme={null} ( filter?: { search?: string; conversationId?: string; }, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const skills = await agent.skills.list(); console.log(skills); ``` Guide: [skills](/docs/documentation/agent/sdk/skills). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentSkill](/docs/documentation/agent/sdk/types#agentskill). ### skills.previewImport Inspect a public GitHub skill before importing it. Check scripts and name conflicts before continuing. ```typescript Signature theme={null} ( input: AgentSkillSource, options?: AgentResourceOptions, ) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const preview = await agent.skills.previewImport({ repoUrl: "https://github.com/OWNER/REPO", subpath: "skills/photo-editing", }); console.log(preview); ``` Guide: [skills](/docs/documentation/agent/sdk/skills). Types: [AgentSkillSource](/docs/documentation/agent/sdk/types#agentskillsource), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentSkillImportPreview](/docs/documentation/agent/sdk/types#agentskillimportpreview). ### skills.retrieve Read a visible fal or installed skill by ID. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const skill = await agent.skills.retrieve("SKILL_ID"); console.log(skill.body); ``` Guide: [skills](/docs/documentation/agent/sdk/skills). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentSkill](/docs/documentation/agent/sdk/types#agentskill). ### skills.save Replace custom skill content. Saving an imported skill detaches its GitHub source and disables source updates. ```typescript Signature theme={null} ( id: string, content: AgentSkillContent, options?: AgentResourceOptions, ) => Promise<{ skill: AgentInstalledSkill; presetClash: boolean; }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; await agent.skills.save("SKILL_ID", { name: "product-photos", description: "Create consistent product photos.", body: "Preserve the product shape and colors.", }); ``` Guide: [skills](/docs/documentation/agent/sdk/skills). Types: [AgentSkillContent](/docs/documentation/agent/sdk/types#agentskillcontent), [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentInstalledSkill](/docs/documentation/agent/sdk/types#agentinstalledskill). ### skills.setEnabled Enable or disable one skill. Pass its origin and ID from skills.list. The account-level skills switch still applies. ```typescript Signature theme={null} ( input: { origin: "fal" | "user"; key: string; enabled: boolean; }, options?: AgentResourceOptions, ) => Promise<{ ok: true }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; await agent.skills.setEnabled({ origin: "user", key: "SKILL_ID", enabled: true, }); ``` Guide: [skills](/docs/documentation/agent/sdk/skills). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### skills.uninstall Remove an installed user skill and its disabled preference entry. Fal skills cannot be uninstalled. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise<{ ok: true }>; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; await agent.skills.uninstall("SKILL_ID"); ``` Guide: [skills](/docs/documentation/agent/sdk/skills). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions). ### skills.update Update an imported skill from its repository default branch. Replaces its body, references, assets, and source commit. ```typescript Signature theme={null} (id: string, options?: AgentResourceOptions) => Promise; ``` Example: ```ts theme={null} import { agent } from "./client.ts"; const skill = await agent.skills.update("SKILL_ID"); console.log(skill.sourceCommitSha); ``` Guide: [skills](/docs/documentation/agent/sdk/skills). Types: [AgentResourceOptions](/docs/documentation/agent/sdk/types#agentresourceoptions), [AgentInstalledSkill](/docs/documentation/agent/sdk/types#agentinstalledskill). # Edit and run plans Source: https://fal.ai/docs/documentation/agent/sdk/plans Update plan steps with revision checks and approval checkpoints. Use the [quickstart client](/docs/documentation/agent/sdk/quickstart#create-a-client). Replace uppercase IDs with your plan and conversation IDs. The `SAVED_*_KEY` values represent persisted keys for those commands. A plan is a `fal.block` with `kind: "plan"` inside an assistant message. Use its ID with `agent.plans`. Pass the owning conversation ID with every plan request. ## Methods | Method | Result | | - | - | | `plans.retrieve(id, { conversation, ...options })` | Current `AgentPlanBlock`. | | `plans.update(id, change, options?)` | Updated `AgentPlanBlock` with its revision. | | `plans.run(id, { conversation, expected_revision }, options?)` | Accepted `AgentResponseView`. | `update` and `run` accept an `idempotencyKey` through their options. Persist one key for each logical command before sending it. ## Update the editable steps An update replaces the complete editable step list. Keep existing IDs to preserve steps. Omit an ID to add a step. Remove a step by omitting it from the array. Change execution order by reordering the array. | Field | Requirement | | - | - | | `conversation` | Owning conversation ID. | | `expected_revision` | Revision returned by the latest plan read. | | `title` | Optional nonempty title, up to 120 characters. | | `steps` | Complete array of 1–50 editable steps. | | `steps[].id` | Existing step ID, or omitted for a new step. Existing IDs must be unique. | | `steps[].label` | Step instruction of 1–500 characters after trimming. | | `steps[].endpoint_id` | Model endpoint of 1–200 characters, or `null` to clear it. | | `steps[].model_pinned` | Required boolean. A pinned model requires an endpoint. | | `steps[].requires_approval` | Required boolean for the approval checkpoint. | This example replaces the plan with one new step. ```ts theme={null} import { agent } from "./client.ts"; const conversation = "CONVERSATION_ID"; const plan = await agent.plans.retrieve("PLAN_ID", { conversation, }); await agent.plans.update( plan.id, { conversation, expected_revision: plan.revision, steps: [ { label: "Generate a product photo", model_pinned: false, requires_approval: true, }, ], }, { idempotencyKey: "SAVED_EDIT_KEY" }, ); ``` A stale revision or an edit during execution returns `409`. Retrieve the latest plan and apply your changes to that version before retrying. ## Run a plan Send the revision you want to run. In this example, that revision is `3`. ```ts theme={null} import { agent } from "./client.ts"; const response = await agent.plans.run( "PLAN_ID", { conversation: "CONVERSATION_ID", expected_revision: 3, }, { idempotencyKey: "SAVED_RUN_KEY" }, ); console.log(response.id); ``` The returned response can pause at an approval checkpoint. Use the [approval flow](/docs/documentation/agent/sdk/inputs) to continue that response. # Projects, documents, and memory Source: https://fal.ai/docs/documentation/agent/sdk/projects Organize conversations and media, attach documents, and maintain project memory. Use the [quickstart client](/docs/documentation/agent/sdk/quickstart#create-a-client). Replace uppercase IDs with your resource IDs. ## Create and manage projects ```ts theme={null} import { agent } from "./client.ts"; const project = await agent.projects.create({ name: "Autumn campaign", color: "#2563eb", }); const conversation = await agent.projects.conversations.create( project.id, { title: "Product concepts", }, ); console.log(project.id, conversation.id); ``` Project names contain 1–40 characters after trimming. Colors accept preset tag colors or valid hexadecimal colors, with a maximum of 20 characters. | Method | Behavior | | - | - | | `projects.list()` | Return project summaries as an array. | | `projects.retrieve(projectId)` | Read the project's ID, name, color, and creation time. | | `projects.update(projectId, { name?, color? })` | Change at least one field. | | `projects.delete(projectId)` | Delete the project and its memory, document records, and saved settings. | Deleting a project does not delete its conversations or source media. Project summaries include counts, update times, and cover media. See [AgentProjectSummary](/docs/documentation/agent/sdk/types#agentprojectsummary) for every field. ## Manage conversations | Method | Behavior | | - | - | | `projects.conversations.list(projectId)` | List visible conversations with their title, media count, and update time. | | `projects.conversations.create(projectId, { title }?)` | Create an idle conversation. | | `projects.conversations.add(projectId, conversationId)` | Add an existing conversation. | | `projects.conversations.remove(projectId, conversationId)` | Remove its project association without deleting the conversation. | | `projects.conversations.setMemoryPrivacy(projectId, conversationId, excluded)` | Control whether the conversation contributes to project memory. | ```ts theme={null} import { agent } from "./client.ts"; await agent.projects.conversations.add( "PROJECT_ID", "CONVERSATION_ID", ); await agent.projects.conversations.setMemoryPrivacy( "PROJECT_ID", "CONVERSATION_ID", true, ); ``` The privacy change requires membership in the specified project. An exclusion controls memory participation. It does not delete the conversation. ## Attach media and collections ```ts theme={null} import { agent } from "./client.ts"; await agent.projects.assets.attach( "PROJECT_ID", "ASSET_ID", ); await agent.projects.collections.attach( "PROJECT_ID", "COLLECTION_ID", ); const resources = await agent.projects.resources("PROJECT_ID"); console.log( resources.attachedMedia, resources.collections, ); ``` Project attachments accept an asset's `assetId` or its library `assetRecordId`. Library mutations use `assetRecordId`. SDK artifact IDs cannot identify project attachments or library assets. Use `projects.assets.detach(projectId, assetId)` or `projects.collections.detach(projectId, collectionId)` to remove an association. Detaching does not delete the source asset or collection. The resources response contains `attachedMedia`, `collections`, `characters`, `smartEntities`, and `generatedMedia`. Attached media has typed identity and display fields. The other arrays contain JSON records with product-specific fields. Check each record before reading fields outside the [declared type](/docs/documentation/agent/sdk/types#agentprojectresources). ## Attach a document Upload and attach a file in one call. The server extracts PDF, DOCX, and text content. This example uses the global `File` constructor available in the [quickstart's Node.js environment](/docs/documentation/agent/sdk/quickstart). ```ts theme={null} import { agent } from "./client.ts"; const file = new File( ["Use warm product lighting."], "brief.txt", { type: "text/plain", }, ); const document = await agent.projects.documents.upload( "PROJECT_ID", file, ); console.log(document.assetId, document.status); ``` Uploads use the client's fal storage credentials. Document ingestion continues in the background. Use `documents.list(projectId)` to check its status. To attach a file already in fal storage, use `documents.import`: ```ts theme={null} import { agent } from "./client.ts"; const document = await agent.projects.documents.import( "PROJECT_ID", { url: "https://fal.media/files/BRIEF.pdf", fileName: "brief.pdf", }, ); console.log(document.status); ``` The server accepts supported fal storage URLs, rejects redirects, and limits downloads to 25 MiB and 30 seconds. DOCX archives also have a 25 MiB expanded limit and a maximum of 1,000 entries. Automatic extraction keeps up to 250,000 characters, plus a truncation notice. It does not perform OCR. Request timeout and cancellation cover both the storage upload and document import. A failed attachment can leave the file in storage. Use `documents.import` to retry with its URL when available. ### Supply extracted text Use `documents.attach(projectId, input)` when you already have extracted text, including text from your own OCR process. | Input | Meaning | | - | - | | `url` | HTTPS URL returned by fal storage. Arbitrary external hosts are rejected. | | `fileName` | Original document name. | | `contentType` | Document MIME type. | | `sizeBytes` | Original file size in bytes, not the extracted text length. | | `text` | Extracted document text. | | `pageCount` | Optional page count, or `null`. | | `truncated` | Whether extraction omitted part of the document. | A project supports up to 50 documents. Each file can be at most 25 MiB. The text can contain at most 260,000 characters. The filename contains 1–256 characters and cannot contain a null character. `pageCount` is a nonnegative integer when supplied. Accepted MIME types are `application/pdf`, `application/vnd.openxmlformats-officedocument.wordprocessingml.document`, `text/plain`, `text/markdown`, `text/csv`, `text/tab-separated-values`, and `application/json`. Use `assetId` for subsequent document operations. ```ts theme={null} import { agent } from "./client.ts"; const documents = await agent.projects.documents.list("PROJECT_ID"); console.log(documents); const preview = await agent.projects.documents.preview( "PROJECT_ID", "ASSET_ID", ); console.log(preview.text, preview.truncated); ``` Check `status` and `error` in subsequent list results until processing completes. Document states include `pending`, `processing`, `ready`, `failed`, and `no_text`. Treat unrecognized states as nonfinal. A `no_text` document has no usable extracted text. Supply extracted text from a supported extraction method. Use `projects.documents.retry(projectId, assetId)` to retry failed processing. Use `projects.documents.remove(projectId, assetId)` to remove the document. ## Maintain project memory ```ts theme={null} import { agent } from "./client.ts"; const note = await agent.projects.memory.create( "PROJECT_ID", { kind: "style", content: "Use warm lighting and a blue background.", }, ); await agent.projects.memory.update( "PROJECT_ID", note.id, { pinned: true }, ); ``` A note's `kind` is `decision`, `fact`, `preference`, `style`, or `entity`. Its content contains 1–500 characters after trimming. A create result contains `id` and `supersededId`. A non-null `supersededId` identifies the note that the new note replaced. `projects.memory.retrieve(projectId)` returns the `primer`, `primerUpdatedAt`, and active `notes`. Each note contains its ID, kind, content, pinned state, source conversation ID, and creation time. A missing primer, source conversation, or note kind can be `null`. ```ts theme={null} import { agent } from "./client.ts"; await agent.projects.memory.update( "PROJECT_ID", "NOTE_ID", { content: "Use soft daylight and a blue background.", }, ); ``` Set `status: "deleted"` to delete a note. Set `status: "active"` to restore it. Keep its ID if your application supports undo. ## Handle errors A missing or inaccessible resource returns `404`. An expired conversation or run can return `410`. Read the affected project resource after an uncertain write. Project methods accept optional `signal` and `timeoutMs` options as their final argument. See the [method reference](/docs/documentation/agent/sdk/methods) for every argument and return type. # Queues and generation runs Source: https://fal.ai/docs/documentation/agent/sdk/queue Control queued work, handle generation approvals, and inspect or retry a generation attempt. Use the [quickstart client](/docs/documentation/agent/sdk/quickstart#create-a-client). Replace uppercase IDs with your resource IDs. A response represents an agent task. A queued turn represents work within a conversation. A generation run represents one media operation. Use each resource's own ID with its methods. ## Inspect a queue ```ts theme={null} import { agent } from "./client.ts"; const queue = await agent.queue.retrieve( "CONVERSATION_ID", ); console.log(queue.items, queue.active_turn_ids); ``` | Queue item field | Meaning | | - | - | | `turnId` | ID for queue actions. | | `qlane` | `user` for user work or `drawer` for continuation work. | | `kind` | `prompt` or `continuation`. | | `prompt`, `stepLabel` | Optional prompt text and step label. | | `position` | Queue ordering value. | | `requiresApproval` | Whether an approval hold blocks the turn. | | `parked` | Whether the turn is held outside normal dispatch. | | `halted` | Whether dispatch is paused for the turn. | | `planStep` | Optional plan block, execution, step ID, and step order. | `active_turn_ids` identifies running turns. It does not contain response IDs. Submit tasks through responses or run a plan to add work to the queue. ## Pause, edit, and resume ```ts theme={null} import { agent } from "./client.ts"; await agent.queue.setHalted( "CONVERSATION_ID", true, ); await agent.queue.edit( "CONVERSATION_ID", "TURN_ID", "Use a blue background.", ); ``` Halting pauses dispatch. It does not cancel work already running. `setHalted` returns `updatedCount` and an optional `dispatch` result. | Method | Input and behavior | | - | - | | `queue.reorder(conversationId, turnIds)` | Reorder up to 50 queued turn IDs. | | `queue.edit(conversationId, turnId, content)` | Replace a queued prompt with 1–10,000 characters. | | `queue.cancel(conversationId, turnId)` | Cancel the selected queued turn. | | `queue.setHalted(conversationId, false)` | Resume dispatch and attempt to start eligible work. | | `queue.dispatch(conversationId)` | Attempt to start eligible queued work. | | `queue.run(conversationId, turnId)` | Request immediate execution of a selected queued turn. | Steps within a plan retain their required order. Queued messages from the user dispatch first. Retrieve the queue after reordering to read its effective order. Reorder, edit, and cancel return `{ success }`. If a turn starts before your edit, retrieve the queue again. Use `responses.cancel` to cancel the task, or `runs.cancel` to cancel a generation run. ## Read dispatch results ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.queue.dispatch( "CONVERSATION_ID", ); if (result.promoted) console.log(result.turnId); else console.log(result.reason ?? "No turn started."); ``` | Field | Meaning | | - | - | | `promoted` | Whether the call started a turn. | | `turnId` | Turn identity when available. | | `assistantMessageId` | Associated assistant message identity when available. | | `requeued` | Whether work returned to the queue after a failed dispatch attempt. | | `reason` | Explanation when available. Treat it as an open string, not a fixed enum. | A successful HTTP request can return `promoted: false`. Inspect the queue for running work, approval holds, or a halted state. A queue change can succeed while its dispatch attempt fails. In that case, retrieve the queue before calling `queue.dispatch` again. ## Release an approval hold Set `requiresApproval` to `false` to release a queued continuation's hold: ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.queue.setApproval( "CONVERSATION_ID", "TURN_ID", { requiresApproval: false, }, ); console.log(result.updated, result.dispatch); ``` Set `requiresApproval: true` to add a hold. A false value can dispatch work immediately. If `updated` is false, the turn can have started or been cancelled. Retrieve the queue again. `approveCheckpoints: true` also approves the relevant plan checkpoints and can release related continuations. Prefer [response approvals](/docs/documentation/agent/sdk/inputs) when responding to `response.pending_inputs`. ## Inspect a generation run For an operation with `kind: "generation"`, use its `id` as the run ID. Pass its owning conversation ID as the second argument. ```ts theme={null} import { agent } from "./client.ts"; const run = await agent.runs.retrieve( "RUN_ID", "CONVERSATION_ID", ); console.log( run.operation.status, run.artifacts, run.input_requests, ); ``` The result contains an `operation`, available `artifacts`, and cost approval `input_requests`. The operation includes its status, artifact IDs, optional progress, and an error when it fails. A failed run can still have useful artifacts. ## Retry a generation A retry creates another generation attempt and can incur charges. ```ts theme={null} import { agent } from "./client.ts"; const retry = await agent.runs.retry( "RUN_ID", "CONVERSATION_ID", ); console.log( retry.runId, retry.attempt, retry.approvalRequired, ); ``` The result contains `mediaId`, `runId`, `attempt`, `requestId`, and optional `approvalRequired`. Use the returned run ID to inspect the attempt. If it requires approval, retrieve the run and answer its pending input request. ## Answer a cost approval Use the input request ID from the retrieved run. ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.runs.answer( "RUN_ID", "CONVERSATION_ID", { input_request_id: "INPUT_REQUEST_ID", decision: "approve", }, ); console.log( result.submittedCount, result.failedCount, result.cancelledCount, ); ``` Use `reject` to decline. The decision applies to the request's approval group, which can contain multiple generations. The result contains optional counts. Missing counts are not evidence of zero work. On `409`, retrieve the run again and use the current input request for the next decision. ## Cancel a run ```ts theme={null} import { agent } from "./client.ts"; const result = await agent.runs.cancel( "RUN_ID", "CONVERSATION_ID", ); console.log(result.cancelled); ``` Inspect the run after cancellation. A cancellation does not refund charges already incurred. `cancelled: false` does not confirm that the provider stopped. If the run is still generating, retrieve its latest state and retry cancellation. Queue and run methods accept optional `signal` and `timeoutMs` options. Writes are sent once and are not retried automatically. After an uncertain retry or approval, retrieve the run before sending another request. See [errors and troubleshooting](/docs/documentation/agent/sdk/errors) for request failures and execution failures. # Agent SDK quickstart Source: https://fal.ai/docs/documentation/agent/sdk/quickstart Install the TypeScript SDK, run your first task, and read the result. Generate an image from a Node.js application. Use Node.js 22.22 or later for these examples. ## Install The Agent SDK is in alpha. Install the version used in this guide: ```bash theme={null} npm install @fal-ai/client@1.11.0-alpha.4 npm install --save-dev tsx ``` ## Configure your credentials Create a fal API key with the **AGENT** permission preset. Set your API key in the environment: ```bash theme={null} export FAL_KEY="YOUR_API_KEY" ``` Replace `YOUR_API_KEY` with your key. The SDK sends Agent requests to `https://fal.ai/api/agent-v2/sdk`. Keep the API key on your server. Do not include it in browser code. ## Create a client Create `client.ts`. The other examples in this guide import this client. ```ts theme={null} import { createFalClient } from "@fal-ai/client"; export const agent = createFalClient().agent; ``` ## Run your first task Create `agent.mts` next to `client.ts`: ```ts theme={null} import { agent } from "./client.ts"; const response = await agent.run({ input: "Generate a product photo of a blue ceramic mug.", }); console.log(response.status, response.output_text); console.log( response.artifacts, response.pending_inputs, response.error, ); ``` Run the file: ```bash theme={null} npx tsx agent.mts ``` `run()` returns when execution stops or needs user input. Check `status` and `fal.phase` before using the result. Media generation can incur charges. ## Stream progress Use `stream()` to observe updates as the task runs: ```ts theme={null} import { agent } from "./client.ts"; for await (const response of agent.stream({ input: "Photograph a blue mug.", })) { console.log(response.output_text); } ``` Each update contains the complete response snapshot. Replace the displayed text on each update instead of appending it. This example starts a new task. Use `responses.stream(responseId)` to observe an existing task. ## Continue the conversation Replace `CONVERSATION_ID` with `response.fal.conversation_id` from the earlier response: ```ts theme={null} import { agent } from "./client.ts"; const response = await agent.run({ conversation: "CONVERSATION_ID", input: "Make another version with warmer lighting.", }); console.log(response.output_text); ``` A follow-up creates a new response in the same conversation. To answer a pending question, use `responses.answer()` with the existing response ID. ## Next steps * [Save response IDs and recover interrupted requests](/docs/documentation/agent/sdk/responses). * [Answer questions and approvals](/docs/documentation/agent/sdk/inputs). * [Edit and run a plan](/docs/documentation/agent/sdk/plans). * [Reuse generated media](/docs/documentation/agent/sdk/media). # Conversations and history Source: https://fal.ai/docs/documentation/agent/sdk/resources Create conversations, read their history, and manage their lifecycle. Use the [quickstart client](/docs/documentation/agent/sdk/quickstart#create-a-client). Replace uppercase IDs with your resource IDs. ## Conversations | Method | Purpose | | - | - | | `conversations.create({ title }?, options?)` | Creates an idle conversation without running the agent. | | `conversations.list(options?)` | Lists accessible conversations. | | `conversations.retrieve(id, options?)` | Reads the title and active response IDs. | | `conversations.update(id, { title }, options?)` | Renames the conversation. | | `conversations.delete(id, options?)` | Starts or completes deletion. | | `conversations.items.list(id, options?)` | Reads input, answer, and output history. | | `conversations.generationSummary(id, options?)` | Reads generation cost information. | ```ts theme={null} import { agent } from "./client.ts"; const conversation = await agent.conversations.create({ title: "Product campaign", }); const response = await agent.run({ conversation: conversation.id, input: "Suggest a visual direction. Do not generate media.", }); console.log(conversation.id, response.id); ``` Conversation titles have a maximum of 120 characters. A rename requires a nonempty title after trimming. `conversations.retrieve` returns `id`, `title`, and `active_response_ids`. ## Paginate history Conversation and history list methods return `{ data, next_cursor }`. Page options accept `cursor` and a `limit` from 1 to 100. ```ts theme={null} import { agent } from "./client.ts"; let cursor: string | undefined; do { const page = await agent.conversations.items.list( "CONVERSATION_ID", { cursor, }, ); console.log(page.data); cursor = page.next_cursor ?? undefined; } while (cursor); ``` History items contain `id`, `response_id`, and `sequence_number`. An item's `type` determines its payload. `input` contains a request input, `answer` contains an input request ID and answer, and `output` contains an output item. The response ID can be `null`. See [AgentConversationItem](/docs/documentation/agent/sdk/types#agentconversationitem). History pagination returns `409` if the underlying snapshot changes. Discard the accumulated pages and restart from the first page. ## Fork a conversation ```ts theme={null} import { agent } from "./client.ts"; const fork = await agent.conversations.fork( "CONVERSATION_ID", { atMessageId: "MESSAGE_ID", }, ); console.log(fork.id); ``` The fork copies settled history through the selected message's completed turn. Omit `atMessageId` to copy the available settled history. Active turns are excluded. The optional `createProject` field controls project creation. Project placement completes asynchronously. ## Share a conversation ```ts theme={null} import { agent } from "./client.ts"; const share = await agent.conversations.sharing.update( "CONVERSATION_ID", { emails: ["reviewer@example.com"], }, ); console.log( `https://fal.ai/chat/share/${share.id}`, ); ``` This replaces the policy. Empty recipient lists allow anyone with the link to access the conversation. Use `allowedAccountIds` for account access or `scopedAccountId` with `scopedEmails` for recipients within one account. The optional `expiresAt` field accepts an ISO 8601 timestamp. Omitting it or passing `null` removes expiration. Read the current policy with `conversations.sharing.retrieve(id)` before replacing it. The result is `null` when no policy exists. ## Delete a conversation Deletion can return `{ deleted: false }` while running work stops. Repeat the deletion request to complete cleanup. ## Recover uncertain writes Conversation creation is sent once. Rename and deletion can use transport retries. Read the resource after a lost acknowledgement before deciding whether to repeat the write. Request options support `signal` and `timeoutMs`. ## Related resources * [Projects, documents, and memory](/docs/documentation/agent/sdk/projects). * [Models, settings, and preferences](/docs/documentation/agent/sdk/settings). * [Queues and generation runs](/docs/documentation/agent/sdk/queue). * [Library assets, collections, and entities](/docs/documentation/agent/sdk/library). * [Complete method signatures](/docs/documentation/agent/sdk/methods). # Responses and recovery Source: https://fal.ai/docs/documentation/agent/sdk/responses Submit tasks, observe response snapshots, and recover without creating duplicate work. Use the [quickstart client](/docs/documentation/agent/sdk/quickstart#create-a-client). Replace uppercase IDs with your resource IDs. A response represents one task. Use its ID to observe, answer, or cancel that task. ## Methods All methods below belong to the configured `agent` client. `Response` in this table means `AgentResponseView`. | Method | Result | Behavior | | - | - | - | | `run(request, options?)` | `Promise` | Creates a response, then polls until it stops or needs input. | | `stream(request, options?)` | `AsyncIterable` | Creates a response, then streams snapshots. | | `responses.create(request, options?)` | `Promise` | Returns the accepted response without waiting for completion. | | `responses.retrieve(id, options?)` | `Promise` | Reads the current snapshot once. | | `responses.wait(id, options?)` | `Promise` | Polls an existing response. | | `responses.stream(id, options?)` | `AsyncIterable` | Streams an existing response. | | `responses.answer(id, input, options?)` | `Promise` | Answers a pending input request. | | `responses.cancel(id, options?)` | `Promise` | Requests cancellation of execution. | | `responses.selectFinalArtifacts(id, input, options?)` | `Promise` | Saves explicit final artifact selections. | ## Request fields | Field | Required | Description | | - | - | - | | `input` | Yes | A string of 1–100,000 characters, or an array containing one user message. | | `conversation` | No | Adds a new response to this conversation. | | `previous_response_id` | No | Continues from the latest settled response. Mutually exclusive with `conversation`. | | `model` | No | Reasoning model ID from `models.listAgentModels()`. Overrides the default for this response. | | `fal.generation_settings` | No | A generation settings snapshot. | | `fal.generation_settings_overrides` | No | Generation setting overrides for this response. | | `fal.skills` | No | Skill names to activate. Activated skills carry into later conversation turns. | | `fal.on_ambiguity` | No | Only `"ask"` is supported. | A structured user message has `role: "user"` and 1–40 content parts. Supported parts are `input_text`, `input_image`, `input_file`, and `fal.input_artifact`. Use `image_url` for images and `file_url` for files. See [media inputs](/docs/documentation/agent/sdk/media). Follow-ups create new response IDs. Answers continue the existing response ID. ## Options | Option | Default | Applies to | | - | - | - | | `signal` | None | Local requests and observation. Aborting does not cancel server execution. | | `timeoutMs` | No deadline | Positive finite deadline for the helper, including retries and observation. | | `idempotencyKey` | Generated for mutations | Reuse the same key and body to recover a create, answer, or plan command. | | `onAccepted` | None | `run()` and `stream()`. Called after acceptance, before observation. | | `pollIntervalMs` | `1000` | Polling helpers. Must be nonnegative and finite. | | `maxReconnects` | `3` | Streaming. Maximum consecutive failed or disconnected observation attempts. | | `reconnectDelayMs` | `500` | Streaming. Delay between reconnect attempts. | `selectFinalArtifacts` uses resource options: `signal` and `timeoutMs` only. It uses `expected_sequence_number` to detect conflicting writes. `maxReconnects` must be a nonnegative integer. `reconnectDelayMs` must be nonnegative and finite. Idempotency keys must be nonempty, single-line strings with at most 200 characters. `onAccepted` is synchronous. The helper does not await a promise returned by this callback. Use `responses.create` when durable asynchronous storage must finish before observation starts. ## Read the response | Field | Meaning | | - | - | | `id` | Stable response ID. | | `status` | Execution status from the table below. | | `output` | Ordered messages, operations, artifacts, and input requests. | | `output_text` | Derived text from the output messages. | | `artifacts` | Derived list of available artifacts. | | `final_artifacts` | Artifacts explicitly selected as final results. | | `pending_inputs` | Input requests that currently require an answer. | | `error` | Response failure details, or `null`. | | `fal.conversation_id` | Conversation that owns the response. | | `fal.phase` | `queued`, `running`, `waiting_for_input`, `cancelling`, or `finished`. | | `fal.sequence_number` | Cursor for changes reflected in this snapshot. | | Status | Terminal | Meaning | | - | - | - | | `queued` | No | The task is waiting to run. | | `in_progress` | No | The task is active or waiting for user input. | | `completed` | Yes | The response completed. Inspect individual operations for handled generation failures. | | `incomplete` | Yes | The response stopped before full completion. | | `failed` | Yes | The response failed. Available artifacts can remain usable. | | `cancelled` | Yes | The response was cancelled. | Observation also stops at `fal.phase === "waiting_for_input"`, even when the status is not terminal. After answering, resume observation with the same response ID. Observation also stops when `fal.pending_submission` reports a saved answer that could not resume. Follow [saved-answer recovery](/docs/documentation/agent/sdk/inputs#recover-a-saved-answer-that-could-not-resume) before resuming observation. `fal.model_usage` reports conversation model tokens across the response's turns. Its `scope` is `"conversation_model"`. The `input_tokens` and `output_tokens` fields are included only when every turn has reported that count. These counts exclude media generation and auxiliary model calls. An absent field or `null` means unavailable, never zero. `usage` is `null` when complete accounting is unavailable. Do not treat conversation model counts as a billing total. `fal.pending_input_ids` and `fal.final_artifact_ids` reference items in `output`. The convenience views are derived getters. `JSON.stringify(response)` omits them. Read the getters explicitly when saving a presentation view. ## Example snapshot This illustrative accepted response has no output yet. IDs vary for each request. The derived fields `output_text`, `artifacts`, `final_artifacts`, and `pending_inputs` are added by the SDK. ```json theme={null} { "id": "resp_example", "status": "queued", "output": [], "error": null, "usage": null, "fal": { "conversation_id": "conversation_example", "phase": "queued", "sequence_number": 0, "pending_input_ids": [], "final_artifact_ids": [] }, "output_text": "", "artifacts": [], "final_artifacts": [], "pending_inputs": [] } ``` ### Output item types | `type` | Contents | How to use it | | - | - | - | | `message` | Assistant content with `output_text` or `fal.block` parts. | Render text and supported blocks. Use a block's `fallback_text` for unknown kinds. | | `fal.operation` | Operation status, artifact IDs, and an optional error or progress. | Show work in progress and handled generation failures. | | `fal.artifact` | Completed media identity, revision, and optional files. | Display, download, or reference the media in a new task. | | `fal.input_request` | A clarification or approval with its status and prompt. | Collect a decision from the user, then answer the request. | Treat IDs as opaque strings. Response, input request, and artifact IDs identify different resources. ## Stream snapshots The stream yields complete snapshots, not text deltas. Replace the displayed state on each update. Do not append each snapshot's `output_text`. ```ts theme={null} import { agent } from "./client.ts"; for await (const response of agent.responses.stream( "RESPONSE_ID", )) { console.log( response.status, response.output_text, ); } ``` The SDK reconnects to existing work when an SSE connection closes. ## Recover an uncertain submission Save the exact request body and idempotency key before the first attempt. ```ts theme={null} import { agent } from "./client.ts"; const response = await agent.responses.create( { input: "Photograph a blue ceramic mug." }, { idempotencyKey: "SAVED_COMMAND_KEY" }, ); console.log(response.id); ``` Retry an uncertain command with the same key and body. A command key is scoped to your account and fal project, so replacing your API key does not create new work. A new command key creates new work. A changed body with an existing command key returns a conflict. `SAVED_COMMAND_KEY` represents the key stored before the original attempt. Use its exact saved input, too. ## Handle errors Inspect `response.status` and `response.error` for execution failures. Catch `AgentRequestError` for request failures. See [errors and troubleshooting](/docs/documentation/agent/sdk/errors) for recovery actions and error context. ## Cancel execution ```ts theme={null} import { agent } from "./client.ts"; await agent.responses.cancel("RESPONSE_ID"); const response = await agent.responses.wait("RESPONSE_ID"); console.log(response.status); ``` Closing a stream, aborting a signal, or reaching a timeout only stops local observation. Cancellation requests server and provider cancellation. It does not refund charges already incurred. If cancellation fails, retrieve the same response and retry cancellation. The response can remain active until cancellation is confirmed. # Models and settings Source: https://fal.ai/docs/documentation/agent/sdk/settings Choose models, change generation defaults, and update account preferences. Use the [quickstart client](/docs/documentation/agent/sdk/quickstart#create-a-client). Replace uppercase IDs with your resource IDs. ## Choose a model The reasoning model handles the conversation. Generation models produce images, video, audio, and 3D media. `models.listAgentModels()` returns reasoning model IDs, labels, and optional tags. Set `general.defaultModel` to an available ID. Use `null` to restore the service default. ```ts theme={null} import { agent } from "./client.ts"; const models = await agent.models.listAgentModels(); console.log(models); ``` After the user selects a model, save its ID: ```ts theme={null} import { agent } from "./client.ts"; await agent.preferences.update("general", { defaultModel: "AGENT_MODEL_ID", }); ``` Choose a model for one response with `model`. This leaves the saved default unchanged: ```ts theme={null} import { agent } from "./client.ts"; const response = await agent.run({ model: "AGENT_MODEL_ID", input: "Suggest three visual directions for a running shoe campaign.", }); console.log(response.output_text); ``` Use `fal.generation_settings_overrides` for generation choices on one response: ```ts theme={null} import { agent } from "./client.ts"; const response = await agent.run({ input: "Create a landscape product photograph of a ceramic mug.", fal: { generation_settings_overrides: { preferences: { aspect_ratio: "16:9" }, reviewBeforeGenerating: true, }, }, }); console.log(response.pending_inputs); ``` Generation settings require access to that feature. Unavailable controls return `403`. Use `fal.generation_settings` when submitting a complete settings snapshot from `settings.conversations.retrieve(conversationId)`. Search generation models with `models.list({ keywords, categories, page, limit })`. The page starts at `1`. The default limit is `40`, with a maximum of `100`. The result contains `items` and optional `total`, `page`, `size`, and `pages` fields. ```ts theme={null} import { agent } from "./client.ts"; const page = await agent.models.list({ keywords: "image", limit: 10, }); console.log(page.items); const capabilities = await agent.models.capabilities( "MODEL_ENDPOINT_ID", ); console.log(capabilities.fields); ``` Each model has an `id`, `modelId`, `title`, `category`, `shortDescription`, `thumbnailUrl`, and `isFavorited` flag. An optional `modelLabId` identifies its provider. Capabilities describe the endpoint's fields. Each field has a `name`, `label`, `type`, `description`, and `required` flag. A field can include a `defaultValue` and additional schema properties. Use these values to build controls. Do not assume that every model accepts the same options. ## Set generation defaults Defaults apply at three scopes. A conversation inherits project defaults, which inherit personal defaults. Use the returned `sources` to identify the effective source of each field. | Target | Scope | | - | - | | `{ scope: "personal" }` | Account defaults. | | `{ scope: "project", projectId }` | Defaults for a project. | | `{ scope: "chat", chatId }` | Defaults for a conversation. `chatId` is its conversation ID. | A defaults read returns these fields: | Field | Meaning | | - | - | | `local` | Values set at the requested scope. | | `inherited` | Settings from the parent scopes. | | `effective` | Settings after the local values apply. | | `sources` | Sources for effective preference and model values. | | `inheritedSources` | Sources before local values apply. | | `revision` | Current settings revision. | | `projectId` | Associated project ID, or `null`. | Use `expectedLocal` to detect a concurrent edit. Send the `local` object from your last read. ```ts theme={null} import { agent } from "./client.ts"; const target = { scope: "chat", chatId: "CONVERSATION_ID", } as const; const defaults = await agent.settings.defaults.retrieve(target); await agent.settings.defaults.update(target, { expectedLocal: defaults.local, changes: { preferences: { aspect_ratio: "16:9" }, preferredModels: {}, }, }); ``` `changes` sets the supplied fields. Omitted fields retain their local values. A `null` value selects automatic behavior at this scope. It does not restore inheritance. Use `inherit` to remove a local override: ```ts theme={null} import { agent } from "./client.ts"; const target = { scope: "chat", chatId: "CONVERSATION_ID", } as const; const defaults = await agent.settings.defaults.retrieve(target); await agent.settings.defaults.update(target, { expectedLocal: defaults.local, inherit: { preferences: ["aspect_ratio"] }, }); ``` For model defaults, use `changes.preferredModels` or `inherit.preferredModels` with a generation task name. A selected endpoint must support that task. | Preference | Accepted values | | - | - | | `aspect_ratio` | `1:1`, `16:9`, `9:16`, `4:3`, `3:4`, `3:2`, `2:3`, `21:9`. | | `resolution` | `720p`, `1080p`, `2K`, `4K`. | | `duration` | Positive duration in seconds, at most `3600`. | | `generate_audio` | Boolean. | Generation tasks are `text-to-image`, `text-to-video`, `image-to-video`, `music`, `text-to-speech`, `sound-effects`, and `image-to-3d`. A model's capabilities can restrict which preference values it supports. Source values are `personal`, `project`, `chat`, `generation`, and `auto`. ## Change generation settings Use `settings.conversations` for a conversation and `settings.projects` for a project. Both expose `retrieve(id)` and `update(id, { settings, expectedRevision })`. An update sends the complete settings object. Preserve fields that you do not intend to change. ```ts theme={null} import { agent } from "./client.ts"; const conversation = "CONVERSATION_ID"; const settings = await agent.settings.conversations.retrieve( conversation, ); await agent.settings.conversations.update( conversation, { settings: { ...settings, reviewBeforeGenerating: true, }, expectedRevision: settings.revision, }, ); ``` | Field | Meaning | | - | - | | `version` | Schema version. Use `1`. | | `revision` | Nonnegative settings revision returned by a read. | | `groups` | Settings keyed by generation task. | | `groups[task].model` | Optional generation endpoint. | | `groups[task].fields` | Model fields keyed by field name. | | `fields[name].value` | String, finite number, boolean, string array, or `{ width, height }`. | | `fields[name].sourceEndpointId` | Endpoint whose capabilities define the field. | | `fields[name].label` | Display label for the field. | | `preferences` | Shared generation preferences. | | `preferredModels` | Effective model choices keyed by task. | | `preferredModelOverrides` | Local model overrides, including `null` for automatic selection. | | `defaults` | Local defaults used for inheritance. | | `reviewBeforeGenerating` | Whether generation requires review. | Use `settings.defaults.update` for inherited preferences and model defaults. Use the complete settings update for `groups` and `reviewBeforeGenerating`. On `409`, read the settings again and apply your changes to that version before submitting another update. ## Update account preferences `preferences.retrieve()` returns the account preferences. `preferences.update(section, input)` changes supplied fields within one section and returns the updated preferences. Arrays replace the corresponding array. An omitted field stays unchanged. ```ts theme={null} import { agent } from "./client.ts"; await agent.preferences.update("notifications", { turnComplete: false, }); ``` ### General | Field | Meaning | | - | - | | `preferredName` | Name used by the agent. Maximum 100 characters. An empty string uses the account name. | | `profession` | Profile category, or `null`. See the complete enum in [AgentPreferences](/docs/documentation/agent/sdk/types#agentpreferences). | | `defaultModel` | Available reasoning model ID, or `null` for the default. | | `liveVoice` | Voice preference for supported live interfaces. This field does not create an SDK voice session. | | `sequencerEnabled` | Enable the video sequencer experience. | The [type reference](/docs/documentation/agent/sdk/types#agentpreferences) lists every voice and profession value. A model or setting unavailable to the account returns `403`. ### Cost | Field | Default | Meaning | | - | - | - | | `confirmImage` | `false` | Include image costs in the approval threshold. | | `confirmVideo` | `true` | Include video costs in the approval threshold. | | `confirmAudio` | `true` | Include audio costs in the approval threshold. | | `confirm3d` | `true` | Include 3D costs in the approval threshold. | | `alwaysConfirmAudio` | `false` | Require audio approval regardless of cost. | | `alwaysConfirm3d` | `false` | Require 3D approval regardless of cost. | | `safetyCapUsd` | `5` | Nonnegative threshold for cumulative confirmed media costs within a turn. | The threshold requests approval. It is not a hard spending limit. ### Skills | Field | Meaning | | - | - | | `enabled` | Enable skills. Defaults to `true`. | | `disabledPresetNames` | Names of disabled preset skills. | | `disabledFalSkillIds` | IDs of disabled fal skills. | | `disabledSkillIds` | IDs of disabled user-installed skills. | The disabled lists default to empty arrays. Use [skills methods](/docs/documentation/agent/sdk/skills) to discover, install, edit, or enable individual skills. ### Notifications `turnComplete` controls completion notifications in the fal Agent interface. It defaults to `true`. This preference does not deliver a webhook or send notifications from your application. ## Recover an uncertain update Settings and preference writes are not retried automatically. After a network error, read the affected resource before repeating a write. See the [method reference](/docs/documentation/agent/sdk/methods) for complete signatures and return types. # Skills Source: https://fal.ai/docs/documentation/agent/sdk/skills Discover, install, edit, and activate skills for fal Agent conversations. Skills provide instructions and reference files for a task. The agent can select enabled skills automatically. Use `fal.skills` when you want to activate a specific skill. ## Discover and activate a skill ```ts theme={null} import { agent } from "./client.ts"; const skills = await agent.skills.list({ search: "product" }); const skill = skills.find((item) => !item.disabled && !item.shadowed); if (skill) { const response = await agent.run({ input: "Plan product photos for a blue ceramic mug.", fal: { skills: [skill.name] }, }); console.log(response.output_text); } ``` Use skill names for activation and skill IDs for management. A request accepts up to 50 skill names, each containing 1–100 characters. Activation persists in the conversation. Later turns inherit activated skills. An empty array does not clear existing activations. Unavailable or disabled names are ignored. The account's master skills switch still applies. `skills.list` accepts optional `search` and `conversationId` fields. Results include fal skills and installed user skills, with `disabled` and `shadowed` flags. A fal skill can shadow a user skill with the same name. Use `skills.retrieve(id)` to read one visible skill, including its body and reference files. ## Import from GitHub ```ts theme={null} import { agent } from "./client.ts"; const source = { repoUrl: "https://github.com/YOUR_ORG/YOUR_SKILLS", subpath: "skills/product-photos", }; const preview = await agent.skills.previewImport(source); console.log(preview.warnings); ``` The source accepts an optional Git ref and a subdirectory path. Private repositories are not supported. The preview reports the resolved commit, file counts, name conflicts, and unsupported scripts. Previewing does not install the skill. Review the contents and warnings before installation. ```ts theme={null} import { agent } from "./client.ts"; const skill = await agent.skills.importFromGithub({ repoUrl: "https://github.com/YOUR_ORG/YOUR_SKILLS", ref: "REVIEWED_COMMIT_SHA", subpath: "skills/product-photos", }); console.log(skill.id); ``` Scripts are not supported for installation. A conflicting user skill name blocks installation. Importing the same repository and path updates the existing installation. A conflicting fal skill produces a shadowing warning instead. ## Create and edit ```ts theme={null} import { agent } from "./client.ts"; const { skill } = await agent.skills.create({ name: "product-photos", description: "Plan consistent product photography.", body: "Use soft studio light. Keep the product color unchanged.", }); console.log(skill.id); ``` Use `skills.save(id, content)` to replace a user skill's name, description, body, and references. Names contain 1–64 lowercase letters, digits, or hyphens, without a leading or trailing hyphen. Descriptions contain 1–1,024 characters. The body must not be empty. Reference paths must identify text files under `references/`. Saving an imported skill detaches it from GitHub. Repository updates are then unavailable for that skill. You cannot edit or uninstall fal-provided skills through these methods. ## Enable, update, or uninstall ```ts theme={null} import { agent } from "./client.ts"; const skill = await agent.skills.retrieve("SKILL_ID"); await agent.skills.setEnabled({ origin: skill.origin, key: skill.id, enabled: true, }); ``` Disabling a skill preserves its installation. Uninstalling removes an owned user skill. Use `skills.checkForUpdates(id)` for GitHub installations. The result contains `currentSha`, `latestSha`, and `hasUpdate`. Call `skills.update(id)` to fetch and apply the repository update. Skill writes are sent once. After an uncertain network result, read the skill before repeating a mutation. See the [method reference](/docs/documentation/agent/sdk/methods#skills) for every method and its return type. # Type reference Source: https://fal.ai/docs/documentation/agent/sdk/types Complete field definitions for Agent requests, responses, settings, projects, and library resources. Import the `Agent*` types from `@fal-ai/client`. A `?` marks an optional field. A `null` value is distinct from an omitted field. `InputRequestBase` defines shared fields within `AgentInputRequest`. It is not a separate package export. The declarations describe the SDK types. The [request limits](/docs/documentation/agent/sdk/responses#request-fields) define accepted request values. Generic JSON fields have no additional stable schema. Check their shape before reading product-specific data. ## AgentStatus ```typescript Definition theme={null} export type AgentStatus = | "queued" | "in_progress" | "completed" | "incomplete" | "failed" | "cancelled"; ``` ## AgentJson ```typescript Definition theme={null} export type AgentJson = | null | boolean | number | string | AgentJson[] | { [key: string]: AgentJson; }; ``` ## AgentFailure ```typescript Definition theme={null} export interface AgentFailure { code: string; message: string; } ``` ## AgentPlanStep ```typescript Definition theme={null} export type AgentPlanStep = { id: string; label: string; detail?: string; endpoint_id?: string; model_pinned?: boolean; requires_approval?: boolean; }; ``` ## AgentBlock ```typescript Definition theme={null} export interface AgentBlock { type: "fal.block"; id: string; kind: string; revision: number; fallback_text: string; data: AgentJson; } ``` Related: [AgentJson](/docs/documentation/agent/sdk/types#agentjson). ## AgentPlanBlock ```typescript Definition theme={null} export interface AgentPlanBlock extends Omit { kind: "plan"; data: { title?: string; steps: AgentPlanStep[]; }; } ``` Related: [AgentBlock](/docs/documentation/agent/sdk/types#agentblock), [AgentPlanStep](/docs/documentation/agent/sdk/types#agentplanstep). ## AgentText ```typescript Definition theme={null} export interface AgentText { type: "output_text"; text: string; annotations: AgentJson[]; } ``` Related: [AgentJson](/docs/documentation/agent/sdk/types#agentjson). ## AgentMessage ```typescript Definition theme={null} export interface AgentMessage { id: string; type: "message"; role: "assistant"; status: | "in_progress" | "completed" | "incomplete"; content: Array; } ``` Related: [AgentText](/docs/documentation/agent/sdk/types#agenttext), [AgentBlock](/docs/documentation/agent/sdk/types#agentblock). ## AgentOperation Generation operations use the run ID as `id`. Capability labels do not introduce additional client methods. See [runs](/docs/documentation/agent/sdk/queue). ```typescript Definition theme={null} export interface AgentOperation { id: string; type: "fal.operation"; kind: string; name: string; status: | "queued" | "in_progress" | "completed" | "failed" | "cancelled"; parent_id?: string; revision?: number; capabilities?: Array<"rename" | "move_after">; artifact_ids: string[]; error: AgentFailure | null; progress?: { completed: number; total?: number; message?: string; }; } ``` Related: [AgentFailure](/docs/documentation/agent/sdk/types#agentfailure). ## AgentArtifact Media artifacts use revision `1`. Read optional files before using their URLs. See [media](/docs/documentation/agent/sdk/media). ```typescript Definition theme={null} export interface AgentArtifact { id: string; type: "fal.artifact"; kind: "media" | "file" | "data" | "composition"; media_type?: "image" | "video" | "audio" | "3d"; revision: 1; produced_by?: string; files?: Array<{ role: string; url: string; mime_type: string; url_expires_at?: string | null; }>; data?: AgentJson; metadata?: Record; } ``` Related: [AgentJson](/docs/documentation/agent/sdk/types#agentjson). ## AgentQuestion ```typescript Definition theme={null} export interface AgentQuestion { id: string; text: string; multiple: boolean; options: Array<{ id: string; label: string; description?: string; }>; allow_text: boolean; } ``` ## InputRequestBase ```typescript Definition theme={null} interface InputRequestBase { id: string; type: "fal.input_request"; status: | "pending" | "answered" | "rejected" | "expired" | "cancelled"; prompt: string; expires_at?: string; } ``` ## AgentInputRequest ```typescript Definition theme={null} export type AgentInputRequest = InputRequestBase & ( | { kind: "clarification"; questions: AgentQuestion[]; } | { kind: "approval"; target: { item_id: string; revision: number; }; accepted_answers: Array< "approve" | "reject" >; } ); ``` Related: [AgentQuestion](/docs/documentation/agent/sdk/types#agentquestion). ## AgentAnswer ```typescript Definition theme={null} export type AgentAnswer = | { kind: "answers"; answers: Array<{ question_id: string; selected_option_ids: string[]; text?: string; }>; } | { kind: "approval"; decision: "approve" | "reject"; }; ``` ## AgentOutputItem ```typescript Definition theme={null} export type AgentOutputItem = | AgentMessage | AgentOperation | AgentArtifact | AgentInputRequest; ``` Related: [AgentMessage](/docs/documentation/agent/sdk/types#agentmessage), [AgentOperation](/docs/documentation/agent/sdk/types#agentoperation), [AgentArtifact](/docs/documentation/agent/sdk/types#agentartifact), [AgentInputRequest](/docs/documentation/agent/sdk/types#agentinputrequest). ## AgentActivity ```typescript Definition theme={null} export type AgentActivity = { id: string; turn_id: string; label: string; status: "running" | "completed"; started_at: number; ended_at?: number; duration_ms?: number; } & ( | { kind: "tool"; node: string; name?: string; arguments?: AgentJson; output?: AgentJson; } | { kind: "reasoning"; content: string; } ); ``` Related: [AgentJson](/docs/documentation/agent/sdk/types#agentjson). ## AgentResponse ```typescript Definition theme={null} export interface AgentResponse { id: string; status: AgentStatus; output: AgentOutputItem[]; error: AgentFailure | null; usage: { input_tokens?: number; output_tokens?: number; cost?: { currency: "USD"; estimated?: number | null; reserved?: number | null; settled?: number | null; }; } | null; fal: { model_usage?: { scope: "conversation_model"; input_tokens?: number; output_tokens?: number; } | null; pending_submission?: { input_request_id: string; action: "retry_input"; error: AgentFailure; }; conversation_id: string; phase: | "queued" | "running" | "waiting_for_input" | "cancelling" | "finished"; sequence_number: number; pending_input_ids: string[]; final_artifact_ids: string[]; activities?: AgentActivity[]; activated_skills?: string[]; }; } ``` Related: [AgentStatus](/docs/documentation/agent/sdk/types#agentstatus), [AgentOutputItem](/docs/documentation/agent/sdk/types#agentoutputitem), [AgentFailure](/docs/documentation/agent/sdk/types#agentfailure), [AgentActivity](/docs/documentation/agent/sdk/types#agentactivity). ## AgentResponseView ```typescript Definition theme={null} export interface AgentResponseView extends AgentResponse { readonly output_text: string; readonly artifacts: AgentArtifact[]; readonly final_artifacts: AgentArtifact[]; readonly pending_inputs: AgentInputRequest[]; } ``` Related: [AgentResponse](/docs/documentation/agent/sdk/types#agentresponse), [AgentArtifact](/docs/documentation/agent/sdk/types#agentartifact), [AgentInputRequest](/docs/documentation/agent/sdk/types#agentinputrequest). ## AgentInputContent Artifact references accept revision `1` or an omitted revision. File and image parts reference URLs without uploading content. ```typescript Definition theme={null} export type AgentInputContent = | { type: "input_text"; text: string; } | { type: "input_image"; image_url: string; } | { type: "input_file"; file_url: string; mime_type?: string; } | { type: "fal.input_artifact"; artifact_id: string; revision?: 1; }; ``` ## AgentRequest Use `fal.skills` to activate skills by name. See [request limits](/docs/documentation/agent/sdk/responses#request-fields) and [skills](/docs/documentation/agent/sdk/skills). ```typescript Definition theme={null} export type AgentRequest = { model?: string; input: | string | [ { role: "user"; content: AgentInputContent[]; }, ]; fal?: { generation_settings?: AgentGenerationSettings; generation_settings_overrides?: AgentGenerationSettingsOverrides; on_ambiguity?: "ask"; skills?: string[]; }; } & ( | { conversation?: string; previous_response_id?: never; } | { conversation?: never; previous_response_id?: string; } ); ``` Related: [AgentInputContent](/docs/documentation/agent/sdk/types#agentinputcontent), [AgentGenerationSettings](/docs/documentation/agent/sdk/types#agentgenerationsettings), [AgentGenerationSettingsOverrides](/docs/documentation/agent/sdk/types#agentgenerationsettingsoverrides). ## AgentRequestOptions ```typescript Definition theme={null} export interface AgentRequestOptions { signal?: AbortSignal; timeoutMs?: number; idempotencyKey?: string; } ``` ## AgentRunOptions ```typescript Definition theme={null} export interface AgentRunOptions extends AgentRequestOptions { pollIntervalMs?: number; onAccepted?: ( response: AgentResponseView, ) => void; } ``` Related: [AgentRequestOptions](/docs/documentation/agent/sdk/types#agentrequestoptions), [AgentResponseView](/docs/documentation/agent/sdk/types#agentresponseview). ## AgentStreamOptions ```typescript Definition theme={null} export interface AgentStreamOptions extends AgentRunOptions { maxReconnects?: number; reconnectDelayMs?: number; } ``` Related: [AgentRunOptions](/docs/documentation/agent/sdk/types#agentrunoptions). ## AgentPage ```typescript Definition theme={null} export interface AgentPage { data: T[]; next_cursor: string | null; } ``` ## AgentPageOptions ```typescript Definition theme={null} export interface AgentPageOptions extends AgentRequestOptions { cursor?: string; limit?: number; } ``` Related: [AgentRequestOptions](/docs/documentation/agent/sdk/types#agentrequestoptions). ## AgentConversation ```typescript Definition theme={null} export interface AgentConversation { id: string; title: string | null; active_response_ids: string[]; } ``` ## AgentConversationItem ```typescript Definition theme={null} export type AgentConversationItem = { id: string; response_id: string | null; sequence_number: number; } & ( | { type: "input"; input: AgentRequest["input"]; } | { type: "answer"; input_request_id: string; answer: AgentAnswer; } | { type: "output"; item: AgentOutputItem; } ); ``` Related: [AgentRequest](/docs/documentation/agent/sdk/types#agentrequest), [AgentAnswer](/docs/documentation/agent/sdk/types#agentanswer), [AgentOutputItem](/docs/documentation/agent/sdk/types#agentoutputitem). ## AgentPlanUpdate ```typescript Definition theme={null} export type AgentPlanUpdate = { conversation: string; expected_revision: number; title?: string; steps: Array<{ id?: string; label: string; endpoint_id?: string | null; model_pinned: boolean; requires_approval: boolean; }>; }; ``` ## AgentEvent This is a transport envelope. Public stream methods yield `AgentResponseView` snapshots, not `AgentEvent` objects. ```typescript Definition theme={null} export interface AgentEvent { type: string; sequence_number: number; response_id: string; response?: AgentResponse; } ``` Related: [AgentResponse](/docs/documentation/agent/sdk/types#agentresponse). ## AgentResourceOptions ```typescript Definition theme={null} export type AgentResourceOptions = Pick< AgentRequestOptions, "signal" | "timeoutMs" >; ``` Related: [AgentRequestOptions](/docs/documentation/agent/sdk/types#agentrequestoptions). ## AgentProject ```typescript Definition theme={null} export interface AgentProject { id: string; name: string; color: string; createdAt: string; } ``` ## AgentProjectSummary ```typescript Definition theme={null} export interface AgentProjectSummary extends AgentProject { chatCount: number; assetCount: number; attachedAssetCount: number; attachedCollectionCount: number; attachedCharacterCount: number; attachedResourceCount: number; assetsByType: { image: number; video: number; audio: number; "3d": number; }; updatedAt: string; coverMedia: Array<{ id: string; type: string; url: string; }>; } ``` Related: [AgentProject](/docs/documentation/agent/sdk/types#agentproject). ## AgentProjectConversation ```typescript Definition theme={null} export interface AgentProjectConversation { id: string; title: string | null; mediaCount: number; updatedAt: string; } ``` ## AgentProjectResources ```typescript Definition theme={null} export interface AgentProjectResources { attachedMedia: Array<{ id: string; assetId: string; vectorId: string | null; type: string; source: string; url: string; title: string | null; prompt: string | null; createdAt: string; }>; collections: Array>; characters: Array>; smartEntities: Array>; generatedMedia: Array>; } ``` Related: [AgentJson](/docs/documentation/agent/sdk/types#agentjson). ## AgentProjectDocumentInput ```typescript Definition theme={null} export interface AgentProjectDocumentInput { url: string; fileName: string; contentType: string; sizeBytes: number; text: string; pageCount?: number | null; truncated?: boolean; } ``` ## AgentProjectDocument ```typescript Definition theme={null} export interface AgentProjectDocument { id: string; assetId: string; fileName: string; slug: string; url: string; contentType: string; sizeBytes: number; charCount: number; pageCount: number | null; truncated: boolean; summary: string | null; status: string; error: string | null; chunkCount: number; createdAt: string; } ``` ## AgentMemoryKind ```typescript Definition theme={null} export type AgentMemoryKind = | "decision" | "fact" | "preference" | "style" | "entity"; ``` ## AgentProjectMemory ```typescript Definition theme={null} export interface AgentProjectMemory { primer: string | null; primerUpdatedAt: string | null; notes: Array<{ id: string; kind: AgentMemoryKind | null; content: string; pinned: boolean; sourceChatId: string | null; createdAt: string; }>; } ``` Related: [AgentMemoryKind](/docs/documentation/agent/sdk/types#agentmemorykind). ## AgentGenerationTask ```typescript Definition theme={null} export type AgentGenerationTask = | "text-to-image" | "text-to-video" | "image-to-video" | "music" | "text-to-speech" | "sound-effects" | "image-to-3d"; ``` ## AgentGenerationPreferences ```typescript Definition theme={null} export type AgentGenerationPreferences = { aspect_ratio?: | "1:1" | "16:9" | "9:16" | "4:3" | "3:4" | "3:2" | "2:3" | "21:9"; resolution?: "720p" | "1080p" | "2K" | "4K"; duration?: number; generate_audio?: boolean; }; ``` ## AgentGenerationDefaults A null override selects automatic behavior. Use `inherit` to restore inheritance. See [defaults](/docs/documentation/agent/sdk/settings#set-generation-defaults). ```typescript Definition theme={null} export type AgentGenerationDefaults = { preferences: { [K in keyof AgentGenerationPreferences]?: | AgentGenerationPreferences[K] | null; }; preferredModels: Partial< Record >; }; ``` Related: [AgentGenerationPreferences](/docs/documentation/agent/sdk/types#agentgenerationpreferences), [AgentGenerationTask](/docs/documentation/agent/sdk/types#agentgenerationtask). ## AgentGenerationSettings Read before updating and preserve unrelated fields. See [settings](/docs/documentation/agent/sdk/settings#change-generation-settings) for field meaning and revision handling. ```typescript Definition theme={null} export type AgentGenerationSettings = { version: 1; revision: number; groups: Partial< Record< AgentGenerationTask, { model?: string; fields: Record< string, { value: | string | number | boolean | string[] | { width: number; height: number; }; sourceEndpointId: string; label: string; } >; } > >; preferences?: AgentGenerationPreferences; preferredModels?: Partial< Record >; preferredModelOverrides?: AgentGenerationDefaults["preferredModels"]; defaults?: AgentGenerationDefaults; reviewBeforeGenerating: boolean; }; ``` Related: [AgentGenerationTask](/docs/documentation/agent/sdk/types#agentgenerationtask), [AgentGenerationPreferences](/docs/documentation/agent/sdk/types#agentgenerationpreferences), [AgentGenerationDefaults](/docs/documentation/agent/sdk/types#agentgenerationdefaults). ## AgentGenerationSettingsOverrides ```typescript Definition theme={null} export type AgentGenerationSettingsOverrides = { groups?: Partial< Record< AgentGenerationTask, { model?: string | null; fields?: Record< string, { value: | string | number | boolean | string[] | { width: number; height: number; }; sourceEndpointId: string; label: string; } | null >; } > >; preferences?: AgentGenerationDefaults["preferences"]; preferredModels?: AgentGenerationDefaults["preferredModels"]; reviewBeforeGenerating?: boolean; }; ``` Related: [AgentGenerationTask](/docs/documentation/agent/sdk/types#agentgenerationtask), [AgentGenerationDefaults](/docs/documentation/agent/sdk/types#agentgenerationdefaults). ## AgentDefaultsTarget ```typescript Definition theme={null} export type AgentDefaultsTarget = | { scope: "personal"; } | { scope: "project"; projectId: string; } | { scope: "chat"; chatId: string; }; ``` ## AgentDefaultsUpdate ```typescript Definition theme={null} export type AgentDefaultsUpdate = { changes?: AgentGenerationDefaults; inherit?: { preferences?: Array< keyof AgentGenerationPreferences >; preferredModels?: AgentGenerationTask[]; }; expectedLocal: AgentGenerationDefaults; }; ``` Related: [AgentGenerationDefaults](/docs/documentation/agent/sdk/types#agentgenerationdefaults), [AgentGenerationPreferences](/docs/documentation/agent/sdk/types#agentgenerationpreferences), [AgentGenerationTask](/docs/documentation/agent/sdk/types#agentgenerationtask). ## AgentDefaultsSource ```typescript Definition theme={null} export type AgentDefaultsSource = | "personal" | "project" | "chat" | "generation" | "auto"; ``` ## AgentDefaultsSources ```typescript Definition theme={null} export type AgentDefaultsSources = { preferences: Partial< Record< keyof AgentGenerationPreferences, AgentDefaultsSource > >; preferredModels: Partial< Record >; }; ``` Related: [AgentGenerationPreferences](/docs/documentation/agent/sdk/types#agentgenerationpreferences), [AgentDefaultsSource](/docs/documentation/agent/sdk/types#agentdefaultssource), [AgentGenerationTask](/docs/documentation/agent/sdk/types#agentgenerationtask). ## AgentDefaultsView ```typescript Definition theme={null} export type AgentDefaultsView = { local: AgentGenerationDefaults; inherited: AgentGenerationSettings; effective: AgentGenerationSettings; sources: AgentDefaultsSources; inheritedSources: AgentDefaultsSources; revision: number; projectId: string | null; }; ``` Related: [AgentGenerationDefaults](/docs/documentation/agent/sdk/types#agentgenerationdefaults), [AgentGenerationSettings](/docs/documentation/agent/sdk/types#agentgenerationsettings), [AgentDefaultsSources](/docs/documentation/agent/sdk/types#agentdefaultssources). ## AgentModel ```typescript Definition theme={null} export type AgentModel = { id: string; modelId: string; title: string; category: string; shortDescription: string; thumbnailUrl: string | null; modelLabId?: string; isFavorited: boolean; }; ``` ## AgentModelCapabilities ```typescript Definition theme={null} export type AgentModelCapabilities = { endpointId: string; label: string; category: string; modelLabId?: string; fields: Array<{ name: string; label: string; type: AgentJson; description: string; required: boolean; defaultValue?: string | number | boolean; [key: string]: AgentJson | undefined; }>; }; ``` Related: [AgentJson](/docs/documentation/agent/sdk/types#agentjson). ## AgentPreferences Update one section at a time. See [preferences](/docs/documentation/agent/sdk/settings#update-account-preferences) for meanings, defaults, and permissions. ```typescript Definition theme={null} export type AgentPreferences = { general: { preferredName: string; profession: | "product_management" | "engineering" | "human_resources" | "finance" | "marketing" | "sales" | "operations" | "data_science" | "design" | "legal" | "other" | null; defaultModel: string | null; liveVoice?: | "quartz" | "ripple" | "vesper" | "willow" | "stone" | "gleam" | "meridian" | "bossa" | "tempo" | "beacon" | "delta" | "cinder" | null; sequencerEnabled?: boolean; }; cost: { confirmImage: boolean; confirmVideo: boolean; confirmAudio: boolean; confirm3d: boolean; alwaysConfirmAudio: boolean; alwaysConfirm3d: boolean; safetyCapUsd: number; }; skills: { enabled: boolean; disabledPresetNames: string[]; disabledFalSkillIds: string[]; disabledSkillIds: string[]; }; notifications: { turnComplete: boolean; }; preferredModels?: Partial< Record >; generationPreferences?: AgentGenerationPreferences; }; ``` Related: [AgentGenerationTask](/docs/documentation/agent/sdk/types#agentgenerationtask), [AgentGenerationPreferences](/docs/documentation/agent/sdk/types#agentgenerationpreferences). ## AgentQueueItem ```typescript Definition theme={null} export type AgentQueueItem = { turnId: string; qlane: "user" | "drawer"; kind: "prompt" | "continuation"; prompt?: string; stepLabel?: string; position: number; requiresApproval: boolean; parked: boolean; halted: boolean; planStep?: { planBlockId: string; planExecutionId: string; planStepId: string; planStepOrder: number; }; }; ``` ## AgentQueueDispatch ```typescript Definition theme={null} export type AgentQueueDispatch = { promoted: boolean; turnId?: string; assistantMessageId?: string; requeued?: boolean; reason?: string; }; ``` ## AgentRunView ```typescript Definition theme={null} export type AgentRunView = { operation: AgentOperation; artifacts: AgentArtifact[]; input_requests: AgentInputRequest[]; }; ``` Related: [AgentOperation](/docs/documentation/agent/sdk/types#agentoperation), [AgentArtifact](/docs/documentation/agent/sdk/types#agentartifact), [AgentInputRequest](/docs/documentation/agent/sdk/types#agentinputrequest). ## AgentGenerationSummary ```typescript Definition theme={null} export type AgentGenerationSummary = { counts: { image: number; video: number; audio: number; model3d: number; }; costsNanoUsd: { image: number; video: number; audio: number; model3d: number; }; models: Array<{ endpointId: string; modality: | "image" | "video" | "audio" | "model3d" | null; count: number; costNanoUsd: number; title: string | null; modelLabId: string | null; }>; totalCount: number; totalCostNanoUsd: number; pricedRequestCount: number; unpricedRequestCount: number; }; ``` ## AgentLibraryMediaType ```typescript Definition theme={null} export type AgentLibraryMediaType = | "image" | "video" | "audio" | "3d"; ``` ## AgentLibraryEntityType ```typescript Definition theme={null} export type AgentLibraryEntityType = | "character" | "prop" | "environment" | "style" | "scene"; ``` ## AgentLibraryEntityReference ```typescript Definition theme={null} export interface AgentLibraryEntityReference { assetRecordId: string; url: string; } ``` ## AgentLibraryEntity All five entity types use this shape. The `references` array contains defining images, not the associated-media gallery. See [entities](/docs/documentation/agent/sdk/library#read-entity-metadata-and-references). ```typescript Definition theme={null} export interface AgentLibraryEntity { id: string; userId: string; type: AgentLibraryEntityType; name: string; handle: string | null; description: string | null; metadata: AgentJson; thumbnailAssetId: string | null; thumbnailUrl: string | null; isFavorited: boolean; references: AgentLibraryEntityReference[]; createdAt: string; updatedAt: string; } ``` Related: [AgentLibraryEntityType](/docs/documentation/agent/sdk/types#agentlibraryentitytype), [AgentJson](/docs/documentation/agent/sdk/types#agentjson), [AgentLibraryEntityReference](/docs/documentation/agent/sdk/types#agentlibraryentityreference). ## AgentLibraryEntityQuery ```typescript Definition theme={null} export interface AgentLibraryEntityQuery { types?: AgentLibraryEntityType[]; search?: string; limit?: number; offset?: number; } ``` Related: [AgentLibraryEntityType](/docs/documentation/agent/sdk/types#agentlibraryentitytype). ## AgentLibraryEntityInput Characters require a description and do not accept custom metadata. All types require one to twenty defining reference images. ```typescript Definition theme={null} export type AgentLibraryEntityInput = { name: string; handle?: string; referenceImages: string[]; coverImageUrl?: string | null; } & ( | { type: "character"; description: string; metadata?: never; } | { type: Exclude< AgentLibraryEntityType, "character" >; description?: string | null; metadata?: Record | null; } ); ``` Related: [AgentLibraryEntityType](/docs/documentation/agent/sdk/types#agentlibraryentitytype), [AgentJson](/docs/documentation/agent/sdk/types#agentjson). ## AgentLibraryEntityUpdate Omitted fields stay unchanged. A supplied reference list replaces the complete defining set. Types and character handles cannot change. Character metadata is managed automatically. ```typescript Definition theme={null} export interface AgentLibraryEntityUpdate { name?: string; handle?: string | null; description?: string | null; metadata?: Record | null; referenceImages?: string[]; coverImageUrl?: string | null; } ``` Related: [AgentJson](/docs/documentation/agent/sdk/types#agentjson). ## AgentLibraryTag ```typescript Definition theme={null} export interface AgentLibraryTag { id: string; name: string; color: string; createdAt: string; } ``` ## AgentCharacterInput ```typescript Definition theme={null} export interface AgentCharacterInput { name: string; description: string; referenceImages: string[]; coverImageUrl?: string | null; } ``` ## AgentCharacterReference ```typescript Definition theme={null} export interface AgentCharacterReference { assetRecordId: string | null; assetId: string | null; url: string; isCover?: boolean; } ``` ## AgentLibraryAsset Use `assetRecordId` for library writes. It can be absent or null. Other IDs are not substitutes. ```typescript Definition theme={null} export interface AgentLibraryAsset { assetRecordId?: string | null; assetId: string | null; vectorId: string; requestId: string | null; url: string | null; type: AgentLibraryMediaType; title: string; endpoint: string | null; createdAt: string | null; source: string | null; prompt: string | null; width: number | null; height: number | null; size?: number | null; contentType: string | null; isFavorited: boolean; collectionIds: string[]; tags?: Array<{ id: string; name: string; color: string | null; createdAt: string; }>; } ``` Related: [AgentLibraryMediaType](/docs/documentation/agent/sdk/types#agentlibrarymediatype). ## AgentLibraryAssetQuery ```typescript Definition theme={null} export interface AgentLibraryAssetQuery { q?: string; searchImageUrl?: string; searchVideoUrl?: string; mediaTypes?: AgentLibraryMediaType[]; sources?: Array<"upload" | "response">; section?: | "all-media" | "generated" | "uploads" | "favorites"; endpoints?: string[]; collectionId?: string | null; recursive?: boolean; characterSearchIdentifiers?: string[]; assetRecordIds?: string[]; tagIds?: string[]; tagMode?: "any" | "all"; sortOrder?: "newest" | "oldest"; cursor?: string | null; limit?: number; } ``` Related: [AgentLibraryMediaType](/docs/documentation/agent/sdk/types#agentlibrarymediatype). ## AgentCollectionFilter Semantic filters require exactly one query input. Filter depth cannot exceed three levels. See [smart collections](/docs/documentation/agent/sdk/library#create-a-smart-collection). ```typescript Definition theme={null} export type AgentCollectionFilter = | { and: AgentCollectionFilter[]; } | { or: AgentCollectionFilter[]; } | { field: | "endpoint" | "status" | "type" | "source" | "created_at"; op: | "eq" | "neq" | "in" | "gt" | "gte" | "lt" | "lte"; value: string | number | string[] | number[]; } | { semantic: { text?: string; image_url?: string; video_url?: string; min_similarity: number; }; }; ``` ## AgentCollectionInput ```typescript Definition theme={null} export interface AgentCollectionInput { name: string; description?: string; icon?: string; color?: string; coverImageUrl?: string; filters?: AgentCollectionFilter | null; parentCollectionId?: string | null; } ``` Related: [AgentCollectionFilter](/docs/documentation/agent/sdk/types#agentcollectionfilter). ## AgentLibraryCollection ```typescript Definition theme={null} export interface AgentLibraryCollection { id: string; type: "manual" | "smart" | AgentLibraryEntityType; name: string; description: string | null; icon: string | null; color: string | null; coverImageUrl: string | null; filters: AgentCollectionFilter | null; parentCollectionId: string | null; characterIdentifier: string | null; referenceImageUrls?: string[]; isFavorited: boolean; createdAt: string; updatedAt: string; assetCount: number | null; previewAssets: Array<{ id: string; type: string; url: string; createdAt: string; }>; } ``` Related: [AgentLibraryEntityType](/docs/documentation/agent/sdk/types#agentlibraryentitytype), [AgentCollectionFilter](/docs/documentation/agent/sdk/types#agentcollectionfilter). ## AgentSkillContent ```typescript Definition theme={null} export interface AgentSkillContent { name: string; description: string; body: string; references?: Record; } ``` ## AgentSkillSource ```typescript Definition theme={null} export interface AgentSkillSource { repoUrl: string; ref?: string; subpath?: string; } ``` ## AgentSkill ```typescript Definition theme={null} export interface AgentSkill extends AgentSkillContent { id: string; origin: "fal" | "user"; references: Record; assets: Record; disabled: boolean; shadowed: boolean; attribution: string | null; sourceRepo: string | null; sourceCommitSha: string | null; sourcePath: string | null; installedAt: string | null; updatedAt: string | null; } ``` Related: [AgentSkillContent](/docs/documentation/agent/sdk/types#agentskillcontent). ## AgentInstalledSkill ```typescript Definition theme={null} export interface AgentInstalledSkill extends AgentSkillContent { id: string; references: Record; assets: Record; metadata: Record; allowedTools: string[] | null; sourceRepo: string | null; sourceCommitSha: string | null; sourcePath: string | null; installedAt: string; updatedAt: string; } ``` Related: [AgentSkillContent](/docs/documentation/agent/sdk/types#agentskillcontent), [AgentJson](/docs/documentation/agent/sdk/types#agentjson). ## AgentSkillImportPreview ```typescript Definition theme={null} export interface AgentSkillImportPreview { name: string; description: string; license?: string; sourceRepo: string; sourceCommitSha: string; sourcePath: string; hasScripts: boolean; referenceCount: number; assetCount: number; totalBytes: number; warnings: string[]; nameClash: boolean; nameClashRepo: string | null; presetClash: boolean; } ``` ## AgentConversationSharePolicy ```typescript Definition theme={null} export type AgentConversationSharePolicy = { id: string; policy: { version: 1; accounts: ( | { id: string; allUsers: true; } | { id: string; emails: string[]; } )[]; emails: string[]; } | null; expiresAt: string | null; }; ``` ## AgentConversationSharingInput ```typescript Definition theme={null} export type AgentConversationSharingInput = { allowedAccountIds?: string[]; emails?: string[]; scopedAccountId?: string; scopedEmails?: string[]; expiresAt?: string | null; }; ``` ## AgentProjectDocumentImport ```typescript Definition theme={null} export interface AgentProjectDocumentImport { url: string; fileName: string; contentType?: string; } ``` # Settings Source: https://fal.ai/docs/documentation/agent/settings Every fal Agent preference: profile, default model, sequencer, notifications, skills, connectors, spending caps, and retention. Open **Settings** from the sidebar. Changes save with the **Save changes** button on each tab. ## General ### Profile | Setting | Effect | | :- | :- | | **What should fal Agent call you?** | The name the agent uses. Leave blank to use your account name | | **What best describes your work?** | Helps the agent tailor its responses. Options include Design, Marketing, Engineering, Product management, and others | ### Chat | Setting | Effect | | :- | :- | | **Default model** | The language model that powers the agent's reasoning. The recommended model is selected by default. Other options carry a **Recommended** or **Experimental** badge. Experimental models can be faster but less reliable on long tasks | | **Enable sequencer** | Turns on [video sequences](/docs/documentation/agent/tools/video-sequences). When off, the agent renders combined videos to a file instead | ### Chat retention Shown for enterprise accounts and teams under an organization. Sets how long prompts and generations stay in the workspace. See [Retention](/docs/documentation/agent/retention). ## Notifications **Notify me when a turn finishes.** A browser notification fires when a turn completes while the tab is hidden. Click it to jump back to the chat. On by default. ## Skills **Enable skills.** The master switch for [skills](/docs/documentation/agent/skills). When off, the agent ignores all skills, including fal's and yours. Manage individual skills on the Skills page. ## Connectors Connect and manage external apps. See [Connectors](/docs/documentation/agent/tools/connectors). This tab appears only for accounts with connector access. ## Spending caps **Confirm runs above** sets the safety cap in USD, and the media-type toggles decide which runs ask for confirmation. See [Spending caps](/docs/documentation/agent/spending-caps). # Custom skills Source: https://fal.ai/docs/documentation/agent/skills/custom-skills Write your own skill in the editor or install one from GitHub. Format, fields, references, updates, and limits. A custom skill is a `SKILL.md` file with YAML frontmatter and a Markdown body. fal Agent follows the open format from [agentskills.io](https://agentskills.io), so skills written for other agents work here too. ## Create a skill Open **Skills** and click **Install skill**. Two tabs: * **Create your own.** Write the skill from scratch, or paste a `SKILL.md` you already have. * **From GitHub.** Paste a URL to a public repository, or to a folder in one, that contains a `SKILL.md`. For example `https://github.com/owner/repo/tree/main/skill-name`. Changes apply as soon as you save. The agent uses the skill in new chats. ## Format ```markdown theme={null} --- name: brand-look description: Apply the Acme brand look to every image. Use when the user mentions Acme, the brand kit, or a campaign asset. --- ## Palette Teal #0F6E6E and rust #B4532A. Never pure black. ## Composition Product centered, 15% margin, soft top light. ## Delivery Always produce 1:1 and 4:5. Name runs `acme-`. ``` | Field | Required | Rule | | :- | :- | :- | | `name` | Yes | 1 to 64 characters. Lowercase letters, digits, and hyphens. Must start and end with a letter or digit. This is how the agent refers to the skill | | `description` | Yes | Up to 1,024 characters. Tells the agent when to reach for the skill. Write it as a trigger, not a summary | | `license`, `compatibility`, `metadata`, `allowed-tools` | No | Optional fields from the open format | The body is free Markdown. Keep it focused. A body over about 5,000 tokens shows a warning, because a long skill crowds out the rest of the context. ### References A skill can ship supporting files in a `references/` folder, such as example prompts or a style guide. The agent loads a reference file when the skill tells it to. Use the **References** field in the editor, or include the folder in the repository. * Text files only. Binary files are skipped. * Up to 1 MB of references and assets per skill. Files over the cap are skipped with a warning. * `scripts/` folders are not supported and are rejected on import. * `