Skip to main content
Agency Swarm supports serving your agencies and tools as production-ready HTTP APIs using FastAPI. This enables you to interact with your agents and tools over HTTP, integrate with other services, or connect it to web frontends.

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 the run_fastapi() function.

Example: Create an API endpoint for a single agency

  • 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 when enable_agui=True)
    • /your_agency_name/get_metadata (GET)
    • /get_logs (GET; when enable_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.
Non-streaming (/get_response):
Streaming (/get_response_stream):
Cancel (/cancel_response_stream):
Metadata (/get_metadata):
Conversation starters appear under data.conversationStarters, and quick-reply phrases appear under data.quickReplies when configured. See Agent Overview.Tool (/tool/<name>):
Responses include a 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):
If you’re using LiteLLM models and want usage in streaming responses, keep 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 by app_token_env (default APP_TOKEN) to require Authorization: Bearer <token> on every endpoint. When the variable is absent, authentication is disabled.

Implementation reference

Endpoints follow the reference above; tool schemas mirror the definitions of example_tool and test_tool.

API Usage Example

You can interact with your agents and tools using HTTP requests:

How user_context is applied

  • Merges with any user_context set 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_keys to 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 for litellm/... models.
    • Map provider_nameapi_key.
    • Example: {"anthropic": "...", "gemini": "..."}
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 the run_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.

Serving Standalone Tools

Expose tools as simple HTTP endpoints for external systems, webhooks, or other agents to call directly without agency orchestration.
This creates:
  • POST /tool/Address — execute the tool
  • GET /openapi.json — full OpenAPI schema
  • GET /docs — interactive Swagger UI
Use ToolFactory.get_openapi_schema() to generate the OpenAPI spec programmatically:

File Attachments

Attach files to agency requests using file_ids or file_urls in the payload:
For inline Responses attachments that should not be uploaded through the Files API, pass a structured message:
With manual 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:
When 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
To support passing local filepaths in the file_urls field, set allowed_local_file_dirs on run_fastapi:
Then pass absolute file paths in file_urls:
Invalid paths return an 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.