ai-query library is designed for “Write Once, Run Anywhere”. You can deploy the exact same agent code to a long-running server, a CLI tool, or a serverless function.
Serverless Adapters
Serverless platforms (like AWS Lambda, Vercel, Cloud Run) are stateless. Each request spins up a fresh environment. TheAgent class handles this lifecycle automatically via handle_request().
To avoid boilerplate, we provide Adapters that bridge platform-specific request objects to the agent.
FastAPI (AgentRouter)
The AgentRouter allows you to mount agents directly into a FastAPI application. It supports both single agents and multi-agent registries.
[!NOTE]
To use this adapter, install the optional dependencies:
pip install "ai-query[fastapi]"
Single Agent:
Vercel / Next.js (handle_vercel)
For Vercel’s standard Python runtime (which uses http.server.BaseHTTPRequestHandler), use the handle_vercel helper.
AWS Lambda (handle_lambda)
For AWS Lambda functions triggered by API Gateway (v1 or v2), use handle_lambda.
Lifecycle Management
In serverless environments, the lifecycle is:- Initialize: Agent is instantiated (cheap).
- Load State:
handle_requestloads state fromStorage. - Execute: Agent processes the message.
- Save State:
handle_requestsaves state toStorage. - Respond: Response is returned to the client.
MemoryStorage for serverless deployments.
Agent Registry
TheAgentRegistry allows you to route requests to different agent implementations based on the Agent ID. This is useful for:
- Multi-Agent Systems: Serving different types of agents from one endpoint.
- Hybrid Deployments: Routing some IDs to local agents and others to remote URLs.