Deploy an AI agent API
An agent loop behind HTTP: model API keys as secrets, long requests, streaming, cost and background jobs.
On this page
An AI agent behind an HTTP API is an ordinary web app on Gregale: a server that receives a request, runs the agent loop (call the model, run the tools it asks for, call it again) and returns or streams the answer. This page covers what is different about agents: secrets, long requests, streaming, cost, and work that outlives a request. The example is a FastAPI app on the Anthropic Python SDK; the same points apply to any framework or model provider. What every app shares is on Deploy a web framework.
An agent spends most of its life waiting for users. Gregale bills an app only while it handles requests and parks it in between, so an idle agent costs nothing to keep deployed; model tokens are billed by the model provider per request.
Prepare the app
- A health path that never calls the model. Health checks run often;
they shouldn't cost tokens. Add
/healthzand pointhosting.healthat it. - Create the model client on first use, not at import, so the app starts
and answers
/healthzeven before its API key is set. - Put a token in front of the model. Every request to the agent costs model tokens, so a public URL without authentication is an open bill. Check a bearer token in the app, or keep the app private and call it with a Gregale API key (see Quickstart).
- Validate tool input. Tool arguments come from the model; check them before acting on them, and return an error result instead of raising.
A FastAPI app with a Procfile deploys from source with no Dockerfile:
# Procfile
web: uvicorn app.main:app --host 0.0.0.0 --port $PORT
# gregale.yaml
access: public # the app checks its own bearer token
hosting:
health: /healthz
Set the secrets
Reserve the app, then set the model key and the caller token as secrets before the first deploy:
gregale deploy --create-only --name my-agent
gregale env set --app my-agent ANTHROPIC_API_KEY=sk-ant-...
gregale env set --app my-agent AGENT_TOKEN="$(openssl rand -hex 24)"
gregale deploy --name my-agent
They arrive as environment variables and are sealed at rest; see Secrets. Never put a key in the repository or the image.
Long requests and streaming
An agent can call the model several times before it answers. Gregale requires an app to start its response within 30 seconds unless you raise the app's request timeout, up to your plan's maximum (30 seconds on Free, 1 minute on Hobby, 5 on Pro, 15 on Scale; see Plans and pricing):
gregale app update my-agent --request-timeout 300
Streaming avoids the wait: send events as the agent works, with Server-Sent Events, and the response starts at once. With FastAPI:
@app.post("/v1/ask/stream")
async def ask_stream(body: Ask):
async def events():
async for event in agent.run(conversation(body)):
yield f"event: {event['type']}\ndata: {json.dumps(event)}\n\n"
return StreamingResponse(events(), media_type="text/event-stream")
An open stream is a running request, so the instance stays up, and is billed, until the stream ends. Cap the loop (for example at 8 model calls) so one request can't run up a large bill.
Work that outlives a request
For agent runs that take many minutes, research jobs, or batches, don't hold an HTTP request open: start the work as a job and return its ID, then let the caller poll for the result or receive it by webhook. Scheduled agents run as cron jobs. Anything left running in the background after a response stops when the app is parked.
Keep state outside the app
The filesystem is ephemeral and an app can run as several instances, so conversation history can't live in memory between requests. Either have the caller send the history with each request (the example does this), or store it in managed PostgreSQL keyed by a conversation ID.
Cost controls
- Cap the agent's model calls per request, and its output tokens.
- Use a low thinking effort for short answers; raise it only where answers need it.
- Set a spend cap on your Gregale account (Cost controls) and a spending limit with your model provider.
- Rate-limit callers at Gregale's edge before requests reach the app; see Edge rules.
Example repository
gregale-dev/ai-agent-api is a support agent on Claude: a tool-calling loop with a FAQ search tool, JSON and Server-Sent Events endpoints, a bearer token in front of the model, and validated tool input. It has no database, so it runs on every plan:
git clone https://github.com/gregale-dev/ai-agent-api
cd ai-agent-api
gregale deploy --create-only --name my-agent
gregale env set --app my-agent ANTHROPIC_API_KEY=sk-ant-...
gregale env set --app my-agent AGENT_TOKEN="$(openssl rand -hex 24)"
gregale deploy --name my-agent
For a remote MCP server instead of an HTTP API, see Host an MCP server.
Spotted a problem on this page? Tell us