Installation
FastAPI integration is an optional installation. To install all required dependencies, run:Setting Up FastAPI Endpoints
You can expose your agencies and tools as API endpoints using therun_fastapi() function.
Example: Create an API endpoint for a single agency
run_fastapi parameters
run_fastapi parameters
Endpoint reference
Endpoint reference
- Agencies are served at:
/your_agency_name/get_response(POST)/your_agency_name/get_response_stream(POST, streaming responses)/your_agency_name/cancel_response_stream(POST; not registered whenenable_agui=True)/your_agency_name/get_metadata(GET)/your_agency_name/realtime(WebSocket; whenenable_realtime=True)/get_logs(GET; whenenable_logging=True)
- Tools registered via
tools=[...]are available at/tool/ToolClassName(BaseTools) or/tool/function_name(function tools). - OpenAPI and interactive docs:
/openapi.json,/docs,/redoc.
Response format
Response format
Non-streaming (Streaming (Cancel (Metadata (Conversation starters appear under
/get_response):/get_response_stream):/cancel_response_stream):/get_metadata):data.conversationStarters, and quick-reply phrases appear under data.quickReplies when configured. See Agent Overview.Tool (/tool/<name>):Usage tracking
Usage tracking
Responses include a If you’re using LiteLLM models and want usage in streaming responses, keep
usage object with token counts and cost by default. For streaming, the final event: messages payload includes the same usage object.To understand what’s inside usage, see Observability.Usage tracking is configured on the agent (not on FastAPI):include_usage=True.Stream cancellation uses an in-memory registry per process. Use single-worker deployments (e.g., uvicorn
workers=1) or sticky routing so cancel requests reach the same worker.Authentication
Set the environment variable named byapp_token_env (default APP_TOKEN) to require Authorization: Bearer <token> on every endpoint. When the variable is absent, authentication is disabled.
Implementation reference
Example: Serving Multiple Agencies and Tools
Example: Serving Multiple Agencies and Tools
example_tool and test_tool.API Usage Example
You can interact with your agents and tools using HTTP requests:Request payload
Request payload
How user_context is applied
- Merges with any
user_contextset on the agency instance. - Useful for structured data (ids, preferences, feature flags) you do not want in the prompt.
- Accessible within tools for the duration of the run. See Agency Context.
How client_config is applied
- Applies only to OpenAI models (no prefix or
openai/...) and LiteLLM models (litellm/...). - Custom Model subclasses are not modified; the request still runs, but the override is skipped.
- For LiteLLM, you can provide
litellm_keysto pass different keys per provider. Requires LiteLLM installed.
client_config fields
base_url(string, optional): Override the API base URL for this request.api_key(string, optional): Override the API key for this request.litellm_keys(object, optional): Only forlitellm/...models.- Map
provider_name→api_key. - Example:
{"anthropic": "...", "gemini": "..."}
- Map
client_config examples
client_config examples
OpenAI model override (gpt-4o):LiteLLM mixed providers (requires
openai-agents[litellm]):Cancelling Active Streams
The streaming endpoint supports cancellation via two methods:1. Automatic Cancellation on Disconnect
When a client disconnects (tab close, refresh, network failure), the stream is automatically cancelled to preserve token costs.2. Cancel Endpoint
Call the cancel endpoint with therun_id received from the first event of the streaming response.
This will allow you to retrieve intermediate results that were generated before the run cancellation.
Optionally include cancel_mode (defaults to immediate):
immediate— stop right away and return messages that were fully generated; the in-progress message is discarded.after_turn— finish the current turn, then stop.
OAuth-enabled agencies
Provide a trusted FastAPI dependency that authenticates the request and returns a stable, non-secret user ID:MCPServerOAuth, run_fastapi automatically:
- Adds
/auth/callbackand/auth/status/{state}routes - Defers OAuth MCP discovery until the model explicitly invokes
authenticate_mcp_server(server_name)(so startup never forces auth) - Emits deterministic OAuth stream events on
/get_response_stream:event: oauth_redirectwith{state, server, auth_url}event: oauth_statuswith{state, server, status}wherestatusispending,authorized,error:<reason>, ortimeout- SSE keepalive comments every 15 seconds while OAuth is pending:
: keepalive <timestamp>
- Uses the authenticated ID from
oauth_user_id_dependencyto store tokens per user - Keeps OAuth callback state in an in-process registry. For multi-worker deployments, an external
oauth_registryshares callback state only; token files must also use a shared persistentoauth_token_path. Otherwise, use sticky routing or a single worker. - Requires streaming:
POST /{agency}/get_responsereturns400when OAuth-enabled MCP servers are present. UsePOST /{agency}/get_response_stream(orenable_agui=True) and buffer the stream if you need a single final response. - Applies a 10-minute OAuth wait timeout per request. On timeout, the stream emits
oauth_status=timeoutand closes cleanly.
oauth_user_id_dependency is required for OAuth-enabled agencies. Do not trust a user ID read directly from a request header or body. FastAPI wiring remains request-scoped and carries the OAuth prompts automatically.
Binding the callback to a user
The provider redirects the browser to/auth/callback as a plain navigation, so it carries no bearer token. By default the callback therefore matches the authorization code to its pending flow by the state parameter alone. state is 32 bytes of URL-safe randomness, and /auth/status/{state} is already restricted to the user who owns the flow.
If your deployment authenticates browsers with a cookie or session, set verify_oauth_callback_user=True and make oauth_user_id_dependency resolve that session. The callback then rejects a code whose pending flow belongs to a different user, which closes the remaining session-fixation gap for anyone who learns a victim’s pending state. Leave it off when the dependency only reads a bearer token: the redirect would fail authentication and every OAuth flow would break.
For HostedMCPTool, FastAPI cannot infer whether a remote MCP server is public or OAuth-protected. To enable hosted OAuth, wrap only the protected tool with enable_hosted_mcp_tool_oauth(...) and leave tool_config.authorization empty. The tool is withheld until the model invokes authenticate_mcp_server(server_name), so unrelated messages do not start OAuth. run_fastapi(...) creates an in-memory callback-state registry by default. For multiple workers, an external oauth_registry shares callback state only; configure each Agency with an oauth_token_path on shared persistent storage as well. Otherwise, use sticky routing or a single worker. Public hosted MCP servers should stay unwrapped.
For OAuth-protected FastMCP servers, schema discovery (
list_tools) is auth-protected. Discovery is deferred until the model invokes authenticate_mcp_server(server_name), so startup does not force OAuth.Set
redirect_uri on MCPServerOAuth to the publicly reachable URL that forwards to the FastAPI /auth/callback route (for example, your ingress hostname plus /auth/callback). You can also set OAUTH_CALLBACK_URL or <SERVER>_REDIRECT_URI as a fallback. If you do not override it, MCPServerOAuth defaults to http://localhost:8000/auth/callback for local development. In production, you must expose and route the callback path back to the issuing pod (sticky routing or shared state), or the OAuth flow will time out.Serving Standalone Tools
Expose tools as simple HTTP endpoints for external systems, webhooks, or other agents to call directly without agency orchestration.POST /tool/Address— execute the toolGET /openapi.json— full OpenAPI schemaGET /docs— interactive Swagger UI
Generate OpenAPI schema programmatically
Generate OpenAPI schema programmatically
Use
ToolFactory.get_openapi_schema() to generate the OpenAPI spec programmatically:File Attachments
Attach files to agency requests usingfile_ids or file_urls in the payload:
message:
chat_history, clients can keep structured attachment parts in history so follow-up turns work without reattaching. This may resend inline attachment content or references; it does not reuse server-managed state, previous_response_id, Conversations, or file_id values.
The response includes file_ids_map with the uploaded file IDs:
file_urls is used, Agency Swarm also prepends a system message for that turn that records the original source string for each attached file. That system message is included in new_messages, so if your client persists new_messages as chat history, later turns will keep the original attachment source URL or local path in model context.
Supported filetypes: .pdf, .jpeg, .jpg, .gif, .png, .c, .cs, .cpp, .csv, .html, .java, .json, .php, .py, .rb, .css, .js, .sh, .ts, .pkl, .tar, .xlsx, .xml, .zip, .doc, .docx, .md, .pptx, .tex, .txt
Local file paths
Local file paths
To support passing local filepaths in the Then pass absolute file paths in Invalid paths return an
file_urls field, set allowed_local_file_dirs on run_fastapi:file_urls:error field in the response body.allowed_local_file_dirs uses strict request-time validation for invalid entries: if an entry exists but is not a directory, local file_urls requests fail with an error. Missing directories are skipped and can be created later. The /get_metadata field allowed_local_file_dirs lists only currently usable directory entries.