# Deploy an AI agent API

> An agent loop behind HTTP: model API keys as secrets, long requests, streaming, cost and background jobs.

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](https://gregale.dev/docs/frameworks.md).

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 `/healthz` and point `hosting.health` at it.
- **Create the model client on first use,** not at import, so the app starts
  and answers `/healthz` even 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](https://gregale.dev/docs/quickstart.md)).
- **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`:

```text
# Procfile
web: uvicorn app.main:app --host 0.0.0.0 --port $PORT
```

```yaml
# 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:

```bash
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](https://gregale.dev/docs/secrets.md). 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](https://gregale.dev/docs/plans.md)):

```bash
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:

```python
@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](https://gregale.dev/docs/jobs.md) and return its ID,
then let the caller poll for the result or receive it by webhook. Scheduled
agents run as [cron jobs](https://gregale.dev/docs/crons.md). 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](https://gregale.dev/docs/postgres.md) 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](https://gregale.dev/docs/cost-controls.md))
  and a spending limit with your model provider.
- Rate-limit callers at Gregale's edge before requests reach the app; see
  [Edge rules](https://gregale.dev/docs/edge-rules.md).

## Example repository

[gregale-dev/ai-agent-api](https://github.com/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:

```bash
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](https://gregale.dev/docs/mcp-hosting.md).

Source: https://gregale.dev/docs/deploy-ai-agent
