agent-doctor Python SDK
The agent-doctor SDK records every LLM call your agent makes and sends the trace to agent-doctor. When you run an experiment from the dashboard, the SDK applies your prompt, model, and parameter changes to the matching calls, with no change to your agent's code.
You add two things to your service: agent_doctor.init() at startup, and
agent_doctor.run_context() around each run.
Keys and settings
Everything your service needs comes from one page: open your project, then Settings in the sidebar. The rail on the right of that page (or Setup and snippets at the top, on a narrower screen) shows a checklist of what is left and the environment variables to copy.
| Value | Where in Settings | Env var in your service | Direction | Needed for |
|---|---|---|---|---|
API key (sk-proj-...) | SDK access → Create API key | AGENT_DOCTOR_API_KEY | Your service → agent-doctor | Sending traces. Required. |
| Webhook URL | Connection to your agent → Webhook URL | none (you enter your URL) | agent-doctor → your service | Starting runs. Required. |
| Agent Doctor token | Connection to your agent → Generate token | AGENT_DOCTOR_SECRET | agent-doctor → your service | Proving a request came from agent-doctor. Strongly recommended. |
| LLM endpoint URL | Your LLM endpoint → LLM endpoint URL | none (you enter your URL) | agent-doctor → your service | Probe, playground, consistency checks, prompt optimizer. |
| Harness model | Your LLM endpoint → Harness model → Save & verify | none | n/a | The model Probe and the consistency check judge reason with. |
API key
Your agent uses the API key to send traces. The SDK sends it as
Authorization: Bearer <api_key> on every export to /v1/traces, and
agent-doctor uses it to file the spans under your project.
- Create one per environment (give it a label such as
prodorstaging), so you can revoke one without touching the others. - The full key is shown once, in the API key created dialog. Copy it then. Afterwards the list shows only its label and creation date.
- Revoke stops it at once: agents using it stop sending traces, and the revoke can't be undone.
- Treat it as a secret. Anyone holding it can write traces into your project.
Agent Doctor token
The token runs the other way. agent-doctor sends it as
Authorization: Bearer <token> on every call it makes to your service: the run
webhook and the three LLM endpoint routes. Your service compares it and rejects
any request without it (see Authenticate the webhook).
- It is generated by agent-doctor, one per project, and shared by the webhook and the LLM endpoint.
- The full value is shown once, when it is generated or rotated. Afterwards the page shows a masked form.
- Without a token, webhook calls go out unauthenticated, so anyone who learns the URL can trigger your agent.
- Rotate stops the old token at once, for both the webhook and the LLM endpoint. Runs fail until you deploy the new value and restart.
Webhook URL and LLM endpoint URL
These are your URLs, not keys. The webhook URL is the full path of the route
that starts a run (https://my-agent.example.com/hook/my-pipeline). The LLM
endpoint URL is the base URL only (https://my-agent.example.com);
agent-doctor appends /agent-doctor/health, /agent-doctor/available-llms and
/agent-doctor/inference. Saving it runs a health check, and Test connection
runs it again.
Your provider keys
Your OpenAI, Anthropic, or Google keys stay in your service. agent-doctor never asks for them: every LLM call it needs goes through your LLM endpoint.
Environment
AGENT_DOCTOR_API_KEY=sk-proj-... # SDK access → Create API key
AGENT_DOCTOR_SECRET=... # Connection to your agent → Agent Doctor tokenQuickstart
You need an API key from Settings → SDK access → Create API key (see Keys and settings), and a service agent-doctor can reach over HTTPS.
1. Install
pip install agent-doctor2. Initialize once at startup
import os
import agent_doctor
agent_doctor.init(
api_key=os.environ["AGENT_DOCTOR_API_KEY"],
app_name="support-agent",
)Call init() before you create any LLM client. It instruments the OpenAI,
Anthropic, and Google GenAI SDKs (and the others listed in
Supported providers) in place.
3. Receive the run webhook
When you trigger a run, agent-doctor sends a POST to your webhook URL. Return
202 right away, then run your agent inside run_context:
import asyncio
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import agent_doctor
app = FastAPI()
background_runs: set[asyncio.Task] = set()
@app.post("/hook/support-agent")
async def receive_run(request: Request):
run_request = await request.json()
run_task = asyncio.create_task(execute_run(run_request))
background_runs.add(run_task)
run_task.add_done_callback(background_runs.discard)
return JSONResponse(status_code=202, content={"accepted": True})
async def execute_run(run_request: dict):
with agent_doctor.run_context(run_request["run_id"], overrides=run_request["overrides"]):
await answer_ticket(run_request["inputs"])answer_ticket is your agent. Nothing inside it needs to change.
4. Point the project at your service
In Settings → Connection to your agent → Webhook URL, enter
https://<your-service>/hook/support-agent. Then press Generate token and
deploy the value as AGENT_DOCTOR_SECRET.
Create an experiment with inputs, press Run, and the trace appears in the run
view once your agent finishes.
Note: The webhook must answer
202within 10 seconds. Any other status, or a timeout, marks the runFAILED. Never run the agent before returning.
How it works
Dashboard: Run ──► agent-doctor ──POST webhook──► your service
│ 202 Accepted
▼
run_context(run_id, overrides)
│
your agent calls OpenAI / Anthropic / Gemini
│
SDK applies matching overrides, records each call
│
OTLP spans ──► POST /v1/traces (Bearer <api_key>) ──► run viewinit()sets up OpenTelemetry tracing through Traceloop (LLMetry), with an exporter that sends spans to agent-doctor using your API key.run_context()puts the run ID and the overrides in context variables. Every span started inside the block is tagged with the run ID, including spans fromasynciotasks andThreadPoolExecutorworkers started inside it.- Before each OpenAI, Anthropic, or Google GenAI call is sent, the SDK computes the call's identity, finds the override that targets it, and rewrites the request arguments.
- When the root span arrives, agent-doctor marks the run
COMPLETED.
Spans are exported one by one as they end, so a run shows progress while it is still executing.
Concepts
Experiment and run
An experiment holds fixed inputs, a JSON object you define when you create
it. Each run of the experiment sends the same inputs with a different set of
overrides. The first run has no overrides and is the original run.
Node
A node is one step in the trace. The SDK names it from, in order:
- a Traceloop decorator:
@workflow(name="triage"),@task(name="classify") agent_doctor.node("classify")- the call site, for undecorated code:
support_agent.answer_ticket:42 < handle(module, function, line, calling function)
Name the steps you plan to tune. Line-number names change when you edit the file, and overrides built from an old trace then miss.
Call identity
A node can make several LLM calls. Each call gets an identity so an override can target exactly one of them:
| Field | Meaning |
|---|---|
path | The enclosing node name |
label | The name set with agent_doctor.node(...) |
sig_strict | Hash of model, system prompt, tools, and response format |
sig_loose | Same, without the system prompt |
site | Hash of the call chain inside your code, with lines relative to each function |
occurrence | The nth call in this run with the same path, label, sig_loose, and site |
The user message and sampling parameters are not part of the identity: the first changes per input, the second is what overrides change.
You never write identities by hand. When you click a node in the dashboard and save an override, agent-doctor picks the fewest fields that single out that call.
Override
An override is the set of changes for one call. You build it in the dashboard; the SDK receives it in the webhook. See Override object.
Guides
Name your steps
from traceloop.sdk.decorators import task, workflow
@task(name="classify_ticket")
async def classify_ticket(ticket_text: str) -> str:
response = await openai_client.chat.completions.create(
model="gpt-4.1",
messages=[
{"role": "system", "content": "Classify the ticket as billing, bug, or other."},
{"role": "user", "content": ticket_text},
],
)
return response.choices[0].message.content
@workflow(name="answer_ticket")
async def answer_ticket(inputs: dict) -> str:
category = await classify_ticket(inputs["ticket_text"])
...Use agent_doctor.node() when calls can't be told apart automatically, such as
identical requests in parallel or a retry loop:
for draft_number in range(MAX_DRAFTS):
with agent_doctor.node("critique"):
critique = await openai_client.chat.completions.create(...)Outside any decorated function, node() also opens a span named after the
label, which becomes the node.
Async and threads
run_context uses contextvars, so it follows your code across:
awaitandasyncio.create_task/asyncio.gatherstarted inside the blockasyncio.to_threadThreadPoolExecutor.submit(the SDK patches it while a run is active; turn this off withinit(..., propagate_threads=False))
It does not follow work handed to a separate process, a task queue (Celery,
RQ), or a thread you start with threading.Thread directly. For those, pass
run_id and overrides along with the job and open run_context again in the
worker:
@celery_app.task
def summarize_ticket_job(run_id: str, overrides: list, ticket_text: str):
with agent_doctor.run_context(run_id, overrides=overrides):
summarize_ticket(ticket_text)Keep the webhook fast
The platform waits 10 seconds for 202. Validate the body, schedule the run,
and return. In FastAPI use asyncio.create_task and keep a reference to the
task (as in the Quickstart); BackgroundTasks
also works. In Flask or Django, hand the run to a thread pool or a task queue.
Use async provider clients (AsyncOpenAI, AsyncAnthropic,
genai.Client().aio) created once at startup. A sync client inside an
async def handler blocks the event loop and every other run with it.
Authenticate the webhook
Once you generate the Agent Doctor token, every
webhook request carries Authorization: Bearer <token>. Check it in constant time:
import hmac
def is_platform_request(request) -> bool:
expected_header = f"Bearer {os.environ['AGENT_DOCTOR_SECRET']}"
received_header = request.headers.get("authorization", "")
return hmac.compare_digest(received_header.encode(), expected_header.encode())Host the LLM endpoints
Probe, the prompt playground, consistency checks, and the prompt optimizer make
LLM calls on your behalf. They run on your infrastructure, with your provider
keys: agent-doctor never holds a provider key. Your service exposes three
routes under <base_url>/agent-doctor/:
| Route | Returns |
|---|---|
GET /agent-doctor/health | {"status": "ok", "contract": 1} |
GET /agent-doctor/available-llms | The models you serve and the params each accepts |
POST /agent-doctor/inference | One completion, in a normalized shape |
Enter the base URL in Settings → Your LLM endpoint → LLM endpoint URL and
press Save. The routes check the same Agent Doctor token as the webhook
(AGENT_DOCTOR_SECRET). When the health check passes, pick a Harness model
and press Save & verify: agent-doctor runs a short smoke test through your
inference route before Probe will use it.
The platform sends up to 10 inference calls at once, so write these handlers
async. The agent-doctor-endpoints skill has a
complete FastAPI template for OpenAI, Anthropic, and Google, and the full error
contract.
Wrap the original prompt
An override's prompt or user_prompt can contain {original}, which the SDK
replaces with the text your code sent. Use it to add instructions without
copying a dynamic prompt:
{"prompt": "{original}\n\nAnswer in at most three sentences."}Turn off content capture
Prompts and completions are recorded by default. To record only timings, models, and token counts:
export TRACELOOP_TRACE_CONTENT=falseThe trace view then shows no text, and the playground can't replay a node's input.
API reference
agent_doctor.init()
agent_doctor.init(api_key, endpoint=None, app_name=None, propagate_threads=True)Call once per process, at startup, before creating LLM clients.
| Parameter | Type | Default | Description |
|---|---|---|---|
api_key | str | required | Project API key. Sent as Authorization: Bearer <api_key> on every export. |
endpoint | str | https://api.theagentdoctor.com/v1/traces | Trace ingest URL. Set it when you self-host, or to the ingest_url from the webhook. |
app_name | str | "agent-doctor-app" | Service name on the exported spans. |
propagate_threads | bool | True | Carry the active run into ThreadPoolExecutor workers. |
On startup, the SDK logs one warning listing installed provider packages it can't capture.
agent_doctor.run_context()
with agent_doctor.run_context(run_id, overrides=None):
...| Parameter | Type | Description |
|---|---|---|
run_id | str or UUID | The run_id from the webhook. Every span in the block is tagged with it. |
overrides | list[dict], dict, or None | The overrides from the webhook, passed as-is. |
When the block exits, the SDK logs a warning for each override that changed no
call, or a different number of calls than its expected_matches.
Context manager, sync only. It works inside async def: use with, not async with.
agent_doctor.node()
with agent_doctor.node(label):
...Sets label on every LLM call in the block. Opens a span named label when no
span is active.
Webhook payload
{
"experiment_id": "7f0c1e7a-…",
"run_id": "b3a9d2c4-…",
"ingest_url": "https://api.theagentdoctor.com/v1/traces",
"inputs": {"ticket_text": "I was charged twice this month."},
"overrides": []
}| Field | Description |
|---|---|
experiment_id | The experiment this run belongs to. |
run_id | Pass to run_context. |
ingest_url | Where traces go. Matches the endpoint you pass to init(). |
inputs | The experiment's inputs, a JSON object you defined. Same for every run of the experiment. Keep it under 1 MB; pass URLs for large files. |
overrides | [] for the original run, otherwise a list of override objects. |
Respond 202. The body is ignored.
Override object
{
"target": {"path": "classify_ticket", "sig_loose": "9c1e…"},
"expected_matches": 1,
"prompt": "Classify the ticket as billing, bug, refund, or other.",
"model": "gpt-4.1-mini",
"temperature": 0.2
}| Field | Type | Description |
|---|---|---|
target | object | Identity fields the call must match. The most specific matching override wins. |
expected_matches | int | How many calls the override should change in this run. A mismatch is logged. |
prompt | string | Replaces the system prompt (OpenAI first system message, Anthropic system, Responses instructions, Gemini system_instruction). |
user_prompt | string | Replaces the last user message. |
model | string | Replaces the model. |
temperature | number | Replaces the temperature. |
top_p | number | Replaces top_p. |
max_tokens | int | Replaces the output token limit, under the provider's own name. |
Only the fields present are changed. If the installed provider SDK doesn't
accept a field (for example, temperature on some reasoning models), the SDK
drops it and the run view reports which fields were dropped.
Span attributes
Every span carries run_id and agent_doctor.sdk.version. Each LLM call also
carries agent_doctor.call.<field> for its identity and, when an override
changed it, agent_doctor.override.index. These appear in the run view; you
don't need to read them yourself.
Supported providers and frameworks
Overrides apply only to calls made through these SDKs, sync and async, including streaming:
| SDK | Methods |
|---|---|
openai | chat.completions.create, .parse, .stream; responses.create, .parse |
anthropic | messages.create, messages.stream |
google-genai | models.generate_content, generate_content_stream |
OpenAI-compatible gateways (Azure OpenAI, OpenRouter, vLLM, a LiteLLM proxy)
go through the openai SDK and are overridable.
Capture only (traced, not overridable): Bedrock, SageMaker, Vertex AI SDK, Cohere, Groq, Ollama, Replicate, Aleph Alpha, Writer, Hugging Face Transformers.
Frameworks: calls made through LangChain, LangGraph, LiteLLM, LlamaIndex, Haystack, CrewAI, OpenAI Agents, and Strands are captured, and overridable when the framework calls one of the three SDKs above underneath. CrewAI tools and Strands agents and tools get their own steps.
Vector databases: queries and returned items are recorded for Qdrant, Chroma, LanceDB, Weaviate 4, and Pinecone, so retriever steps show what was asked and what came back.
Not captured (the upstream instrumentation doesn't support the current
package version): mistralai 1.x, together 2.x, ibm-watsonx-ai, and
huggingface_hub. Wrap those calls in @task to see them as steps.
Troubleshooting
Run stays PENDING, then FAILED.
The webhook didn't return 202 within 10 seconds. Check that the URL is
reachable from the internet, that the handler returns 202 (not 200), and
that it doesn't run the agent before responding.
Run is RUNNING but never completes.
The root span never arrived. Make sure the whole pipeline is inside
run_context, and that the agent didn't crash in the background task: an
exception in an asyncio.create_task coroutine is only logged when the task
is collected, so log errors inside execute_run.
Trace is empty, or some steps are missing.
Spans outside run_context are dropped. Work started in a task queue, a
separate process, or a raw threading.Thread loses the run; open
run_context again there (see Async and threads). Also
check that init() ran before the LLM client was created.
agent-doctor: override ... matched no LLM call in this run.
The call's identity changed since the original run: its node was renamed, the
model or tools changed, or it's an undecorated call whose line moved. Name the
step with @task or agent_doctor.node(), start a new original run, and rebuild the
override.
override ... changed N LLM calls, expected M.
The target matches more or fewer calls than in the original run, often because a
loop ran a different number of times. Label the calls with agent_doctor.node()
to tell them apart.
Override saved, but the dashboard says the provider isn't supported.
The step calls a capture-only provider. Route it through the openai,
anthropic, or google-genai SDK to make it overridable.
401 from /v1/traces.
The API key is wrong or revoked. Create a new one in Settings → SDK access → Create API key.
Test connection shows unauthorized.
The Agent Doctor token isn't deployed, or it was rotated. Set
AGENT_DOCTOR_SECRET to the current token and restart. If you no longer have
the full value, rotate it in Settings → Connection to your agent and deploy
the new one.
Skills for coding agents
These skill files teach a coding agent (Claude Code, Cursor, Codex) to write agent-doctor integrations the way this page describes.
| Skill | Use it to |
|---|---|
agent-doctor-endpoints | Create the run webhook and the three LLM endpoints as async FastAPI handlers, with auth, concurrency limits, timeouts, and the error contract. Includes Anthropic and Google translations. |
Copy both files into your repository at the paths shown. If your agent keeps
skills somewhere else, replace .claude/skills/ with its skills directory.
---
name: agent-doctor-endpoints
description: Build the HTTP endpoints an agent service needs to work with agent-doctor, as fast async handlers. Use when creating or editing the run webhook (POST that receives run_id, inputs, overrides), the LLM endpoints (GET /agent-doctor/health, GET /agent-doctor/available-llms, POST /agent-doctor/inference), or any async LLM-calling route in FastAPI, Starlette, or aiohttp. Covers bearer auth, returning 202 before the pipeline runs, shared async provider clients, concurrency limits, timeouts, the error contract, and replay-fidelity rules for params.
---
# agent-doctor endpoints
An agent service exposes four routes to agent-doctor:
| Route | Called when | Must |
|---|---|---|
| `POST <webhook_url>` | A run is triggered | Return `202` within 10 s, then run the pipeline in the background |
| `GET /agent-doctor/health` | URL saved, "Test connection" | Return `{"status": "ok", "contract": 1}` |
| `GET /agent-doctor/available-llms` | URL saved, "Refresh models" | List the models and their param specs |
| `POST /agent-doctor/inference` | Probe, playground, consistency checks, GEPA | Make one LLM call and return the normalized result |
The platform sends up to 10 `inference` calls at once per project (a consistency
check fires 10 in parallel). A blocking handler serializes them, so a 3 s model call
turns into 30 s. Every rule below exists to keep those calls parallel.
## Values the service needs
All come from the project's **Settings** page in the agent-doctor dashboard.
| Env var | Where | What it is |
|---|---|---|
| `AGENT_DOCTOR_API_KEY` | **SDK access → Create API key** | `sk-proj-...` key the SDK sends when exporting traces. Shown once. |
| `AGENT_DOCTOR_SECRET` | **Connection to your agent → Generate token** | The Agent Doctor token. agent-doctor sends it as `Authorization: Bearer <token>` on the webhook and on all three LLM endpoint routes. Shown once; rotating it breaks the old value at once. |
The user enters the webhook URL and the LLM endpoint base URL on the same page.
Provider keys (OpenAI, Anthropic, Google) stay in the service and are never
given to agent-doctor. If an env var is missing, ask the user for it; never
hard-code a key.
## Rules
1. **Async all the way down.** Handlers are `async def`. Provider clients are
the async ones: `AsyncOpenAI`, `AsyncAnthropic`, `genai.Client(...).aio`.
Never call a sync SDK, `requests`, or `time.sleep` inside an async handler.
If a dependency is sync only, wrap it in `await asyncio.to_thread(...)`.
2. **One client per process.** Create provider clients once in the app's
lifespan and reuse them. A client per request opens a new connection pool
and TLS handshake every call.
3. **Size the connection pool for the platform's concurrency.** At least 10
connections per provider; more if your own traffic shares the client.
4. **Bound every call.** Read `timeout_ms` from the request and pass it to the
provider client. Map a timeout to `504 timeout`.
5. **Cap concurrency yourself** with an `asyncio.Semaphore` if your provider
rate limit is lower than the platform's 10. Return `429 rate_limited` with
`retryable: true` rather than letting calls queue past `timeout_ms`.
6. **Webhook returns first, works later.** Validate, schedule the run with
`asyncio.create_task`, return `202`. Anything other than `202` within 10 s
marks the run `FAILED`. Keep a reference to the task so it isn't garbage
collected mid-run.
7. **Run the pipeline inside `agent_doctor.run_context(run_id, overrides)`.**
Enter it inside the background task, not in the request handler.
Contextvars carry into `asyncio.create_task` and `asyncio.to_thread`
spawned within it, so nested calls are tagged.
8. **Compare the bearer secret in constant time** with
`hmac.compare_digest`. Reject a missing or wrong secret with `401`.
9. **Replay fidelity.** Pass only the `params` keys you received. Don't fill in
`temperature: 0` or any default of your own; an absent key means
"provider default".
10. **Translate param names at the edge.** The contract uses
`max_output_tokens`; OpenAI chat wants `max_completion_tokens`, Anthropic
wants `max_tokens`, Google wants `max_output_tokens` inside `config`.
11. **Every non-2xx body is the error envelope**:
`{"error": {"code": "...", "message": "...", "retryable": bool}}`.
The codes and statuses are in the table below.
12. **Use model names your code uses.** Replays match `model_name` against the
`gen_ai.request.model` captured in traces. If your code calls
`gpt-4.1`, list `gpt-4.1`, not a display name.
## Error contract
| Status | `code` | `retryable` | When |
|---|---|---|---|
| 401 | `unauthorized` | false | Missing or wrong bearer secret |
| 400 | `bad_request` | false | Body doesn't parse or misses `model_name` / `messages` |
| 400 | `invalid_params` | false | A `params` value the model rejects |
| 404 | `unknown_model` | false | `model_name` not in `available-llms` |
| 422 | `unsupported_feature` | false | `tools` sent to a model without tool support |
| 426 | `contract_mismatch` | false | `X-AgentDoctor-Contract` is not `1` |
| 429 | `rate_limited` | true | Your limit or the provider's |
| 502 | `provider_error` | true | The provider call failed |
| 504 | `timeout` | true | Exceeded `timeout_ms` |
The platform retries once when `retryable` is true.
## Template: FastAPI, OpenAI
Start from this file. For Anthropic or Google, keep everything and replace
`call_model`; see `references/providers.md` in this skill.
```python
import asyncio
import hmac
import os
import time
from contextlib import asynccontextmanager
import agent_doctor
import openai
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
AGENT_DOCTOR_API_KEY = os.environ["AGENT_DOCTOR_API_KEY"]
ENDPOINT_SECRET = os.environ["AGENT_DOCTOR_SECRET"]
SUPPORTED_CONTRACT_VERSION = "1"
MAX_CONCURRENT_PROVIDER_CALLS = 10
DEFAULT_TIMEOUT_MS = 60_000
MILLISECONDS_PER_SECOND = 1000
SERVED_MODELS = {
"gpt-4.1": {
"provider": "openai",
"params": {
"temperature": {"type": "float", "min": 0, "max": 2, "default": 1},
"top_p": {"type": "float", "min": 0, "max": 1},
"max_output_tokens": {"type": "int", "min": 1, "max": 32768},
},
"supports": {"tools": True, "json_output": True},
},
}
# Contract param name -> OpenAI chat-completions kwarg.
OPENAI_PARAM_NAMES = {"max_output_tokens": "max_completion_tokens"}
background_runs: set[asyncio.Task] = set()
@asynccontextmanager
async def lifespan(app: FastAPI):
agent_doctor.init(api_key=AGENT_DOCTOR_API_KEY, app_name="my-agent")
app.state.openai_client = openai.AsyncOpenAI(max_retries=0)
app.state.provider_slots = asyncio.Semaphore(MAX_CONCURRENT_PROVIDER_CALLS)
yield
await app.state.openai_client.close()
app = FastAPI(lifespan=lifespan)
class EndpointError(Exception):
def __init__(self, status_code: int, code: str, message: str, is_retryable: bool = False):
super().__init__(message)
self.status_code = status_code
self.code = code
self.message = message
self.is_retryable = is_retryable
@app.exception_handler(EndpointError)
async def render_endpoint_error(request: Request, endpoint_error: EndpointError):
return JSONResponse(
status_code=endpoint_error.status_code,
content={"error": {
"code": endpoint_error.code,
"message": endpoint_error.message,
"retryable": endpoint_error.is_retryable,
}},
)
def require_platform_caller(request: Request) -> None:
expected_header = f"Bearer {ENDPOINT_SECRET}"
received_header = request.headers.get("authorization", "")
if not hmac.compare_digest(received_header.encode(), expected_header.encode()):
raise EndpointError(401, "unauthorized", "missing or wrong bearer secret")
contract_version = request.headers.get("x-agentdoctor-contract")
if contract_version and contract_version != SUPPORTED_CONTRACT_VERSION:
raise EndpointError(426, "contract_mismatch", f"contract {contract_version} not supported")
# ── Run webhook ───────────────────────────────────────────────────────────────
@app.post("/hook/my-agent")
async def receive_run(request: Request):
require_platform_caller(request)
run_request = await request.json()
run_task = asyncio.create_task(execute_run(run_request))
background_runs.add(run_task)
run_task.add_done_callback(background_runs.discard)
return JSONResponse(status_code=202, content={"accepted": True})
async def execute_run(run_request: dict) -> None:
with agent_doctor.run_context(run_request["run_id"], overrides=run_request.get("overrides")):
await run_pipeline(run_request["inputs"])
async def run_pipeline(inputs: dict) -> None:
... # your agent; every OpenAI / Anthropic / google-genai call in here is traced
# ── LLM endpoints ─────────────────────────────────────────────────────────────
@app.get("/agent-doctor/health")
async def report_health(request: Request):
require_platform_caller(request)
return {"status": "ok", "contract": int(SUPPORTED_CONTRACT_VERSION)}
@app.get("/agent-doctor/available-llms")
async def list_available_llms(request: Request):
require_platform_caller(request)
return {"models": [{"model_name": model_name, **model_spec} for model_name, model_spec in SERVED_MODELS.items()]}
@app.post("/agent-doctor/inference")
async def run_inference(request: Request):
require_platform_caller(request)
try:
inference_request = await request.json()
model_name = inference_request["model_name"]
messages = inference_request["messages"]
except (ValueError, KeyError) as parse_error:
raise EndpointError(400, "bad_request", f"malformed body: {parse_error}")
model_spec = SERVED_MODELS.get(model_name)
if model_spec is None:
raise EndpointError(404, "unknown_model", model_name)
tools = inference_request.get("tools")
if tools and not model_spec["supports"]["tools"]:
raise EndpointError(422, "unsupported_feature", f"{model_name} does not take tools")
timeout_seconds = inference_request.get("timeout_ms", DEFAULT_TIMEOUT_MS) / MILLISECONDS_PER_SECOND
started_at = time.monotonic()
async with request.app.state.provider_slots:
inference_result = await call_model(
request.app.state.openai_client, model_name, messages, tools,
inference_request.get("params") or {}, timeout_seconds,
)
inference_result["latency_ms"] = int((time.monotonic() - started_at) * MILLISECONDS_PER_SECOND)
return inference_result
async def call_model(openai_client, model_name, messages, tools, params, timeout_seconds) -> dict:
provider_kwargs = {OPENAI_PARAM_NAMES.get(param_name, param_name): param_value
for param_name, param_value in params.items()}
if tools:
provider_kwargs["tools"] = tools
try:
completion = await openai_client.chat.completions.create(
model=model_name, messages=messages, timeout=timeout_seconds, **provider_kwargs,
)
except openai.APITimeoutError as timeout_error:
raise EndpointError(504, "timeout", str(timeout_error), is_retryable=True)
except openai.RateLimitError as rate_limit_error:
raise EndpointError(429, "rate_limited", str(rate_limit_error), is_retryable=True)
except openai.BadRequestError as bad_request_error:
raise EndpointError(400, "invalid_params", str(bad_request_error))
except openai.APIError as provider_failure:
raise EndpointError(502, "provider_error", str(provider_failure), is_retryable=True)
choice = completion.choices[0]
usage = completion.usage
return {
"output": choice.message.content or "",
"tool_calls": [tool_call.model_dump() for tool_call in choice.message.tool_calls or []],
"finish_reason": choice.finish_reason,
"model_name": completion.model,
"tokens": {
"input": usage.prompt_tokens,
"output": usage.completion_tokens,
"thinking": getattr(usage.completion_tokens_details, "reasoning_tokens", 0) or 0,
"cached": getattr(usage.prompt_tokens_details, "cached_tokens", 0) or 0,
},
}
```
`max_retries=0` on the client is deliberate: the platform already retries once
on `retryable` errors, and stacked retries push the call past `timeout_ms`.
## Adding a new async LLM route of your own
The same rules apply to any route that calls a model:
- Take the shared client from `request.app.state`, never build one inline.
- Fan out independent calls with `asyncio.gather` (or `asyncio.TaskGroup`
on Python 3.11+), not a `for` loop of `await`s.
- Put a semaphore around the fan-out when it can exceed your rate limit.
- Pass an explicit timeout to every provider call.
- Stream to the browser with `StreamingResponse` over the provider's async
stream; never collect the full response first if the user is waiting.
- If the route runs inside a run, the calls are traced and overridable with
no extra code. Use `agent_doctor.node("name")` when two calls in one
function need to be told apart.
## Checklist before you finish
- [ ] `grep -nE "requests\.|time\.sleep|OpenAI\(|Anthropic\(" ` finds nothing
inside async handlers (sync clients and blocking calls).
- [ ] Provider clients are created once, in lifespan.
- [ ] Webhook returns `202` before any model call; the task is kept in a set.
- [ ] `run_context` wraps the whole pipeline, inside the background task.
- [ ] Every route checks the bearer secret with `hmac.compare_digest`.
- [ ] `params` passes through untouched except for the name map.
- [ ] Every error path returns the envelope with the right status and `retryable`.
- [ ] `curl` each route with and without the secret; 10 parallel `inference`
calls finish in about the time of one.
```bash
SECRET=...; BASE=http://localhost:8001
curl -s -H "Authorization: Bearer $SECRET" $BASE/agent-doctor/health
seq 10 | xargs -P10 -I{} curl -s -o /dev/null -w "%{time_total}\n" \
-H "Authorization: Bearer $SECRET" -H "Content-Type: application/json" \
-d '{"model_name":"gpt-4.1","messages":[{"role":"user","content":"Say hi"}]}' \
$BASE/agent-doctor/inference
```
# `call_model` for other providers
The inference request always arrives in the OpenAI chat shape. These versions of
`call_model` translate it for Anthropic and Google. Everything else in the
template stays the same. Create the client once in lifespan, as with OpenAI.
## Anthropic (`AsyncAnthropic`)
Translation:
- The first `system` message becomes the top-level `system` argument.
- An assistant message with `tool_calls` becomes `tool_use` content blocks.
- A `tool` role message becomes a `user` message with a `tool_result` block.
- OpenAI `tools` (`{"type": "function", "function": {...}}`) become
`{"name", "description", "input_schema"}`.
- `max_output_tokens` becomes `max_tokens`, which Anthropic requires. Declare
it `"required": true` in the model's param spec so the platform always sends it.
- `thinking_budget` becomes `thinking={"type": "enabled", "budget_tokens": n}`.
```python
import json
import anthropic
ANTHROPIC_PARAM_NAMES = {"max_output_tokens": "max_tokens"}
ANTHROPIC_FINISH_REASONS = {
"end_turn": "stop", "stop_sequence": "stop", "max_tokens": "length",
"tool_use": "tool_calls", "refusal": "content_filter",
}
def to_anthropic_messages(messages: list[dict]) -> tuple[str | None, list[dict]]:
system_prompt = None
anthropic_messages = []
for message in messages:
role = message["role"]
if role == "system" and system_prompt is None:
system_prompt = message["content"]
elif role == "tool":
anthropic_messages.append({"role": "user", "content": [{
"type": "tool_result",
"tool_use_id": message["tool_call_id"],
"content": message["content"],
}]})
elif role == "assistant" and message.get("tool_calls"):
content_blocks = [{"type": "text", "text": message["content"]}] if message.get("content") else []
for tool_call in message["tool_calls"]:
content_blocks.append({
"type": "tool_use",
"id": tool_call["id"],
"name": tool_call["function"]["name"],
"input": json.loads(tool_call["function"]["arguments"] or "{}"),
})
anthropic_messages.append({"role": "assistant", "content": content_blocks})
else:
anthropic_messages.append({"role": role, "content": message["content"]})
return system_prompt, anthropic_messages
def to_anthropic_tools(tools: list[dict]) -> list[dict]:
return [{
"name": tool["function"]["name"],
"description": tool["function"].get("description", ""),
"input_schema": tool["function"].get("parameters") or {"type": "object", "properties": {}},
} for tool in tools]
async def call_model(anthropic_client, model_name, messages, tools, params, timeout_seconds) -> dict:
system_prompt, anthropic_messages = to_anthropic_messages(messages)
provider_kwargs = {ANTHROPIC_PARAM_NAMES.get(param_name, param_name): param_value
for param_name, param_value in params.items()
if param_name not in ("thinking_budget", "reasoning_effort")}
if "thinking_budget" in params:
provider_kwargs["thinking"] = {"type": "enabled", "budget_tokens": params["thinking_budget"]}
if system_prompt is not None:
provider_kwargs["system"] = system_prompt
if tools:
provider_kwargs["tools"] = to_anthropic_tools(tools)
try:
response = await anthropic_client.messages.create(
model=model_name, messages=anthropic_messages, timeout=timeout_seconds, **provider_kwargs,
)
except anthropic.APITimeoutError as timeout_error:
raise EndpointError(504, "timeout", str(timeout_error), is_retryable=True)
except anthropic.RateLimitError as rate_limit_error:
raise EndpointError(429, "rate_limited", str(rate_limit_error), is_retryable=True)
except anthropic.BadRequestError as bad_request_error:
raise EndpointError(400, "invalid_params", str(bad_request_error))
except anthropic.APIError as provider_failure:
raise EndpointError(502, "provider_error", str(provider_failure), is_retryable=True)
output_text = "".join(block.text for block in response.content if block.type == "text")
tool_calls = [{
"id": block.id,
"type": "function",
"function": {"name": block.name, "arguments": json.dumps(block.input)},
} for block in response.content if block.type == "tool_use"]
usage = response.usage
cache_read_tokens = getattr(usage, "cache_read_input_tokens", 0) or 0
cache_write_tokens = getattr(usage, "cache_creation_input_tokens", 0) or 0
return {
"output": output_text,
"tool_calls": tool_calls,
"finish_reason": ANTHROPIC_FINISH_REASONS.get(response.stop_reason, "stop"),
"model_name": response.model,
"tokens": {
# Anthropic reports cached tokens outside input_tokens; the contract counts them inside.
"input": usage.input_tokens + cache_read_tokens + cache_write_tokens,
"output": usage.output_tokens,
"cached": cache_read_tokens,
},
}
```
## Google (`genai.Client().aio`)
- The first `system` message becomes `config.system_instruction`.
- `assistant` becomes role `model`. `tool` messages become `function_response` parts.
- All sampling params go inside `config`; `max_output_tokens` keeps its name.
- Use `client.aio.models.generate_content`. `client.models` is the sync API and
blocks the event loop.
```python
from google import genai
from google.genai import errors as genai_errors
from google.genai import types as genai_types
GOOGLE_FINISH_REASONS = {"STOP": "stop", "MAX_TOKENS": "length", "SAFETY": "content_filter"}
def to_google_contents(messages: list[dict]) -> tuple[str | None, list[genai_types.Content]]:
system_instruction = None
contents = []
tool_names_by_call_id = {}
for message in messages:
role = message["role"]
if role == "system" and system_instruction is None:
system_instruction = message["content"]
elif role == "tool":
contents.append(genai_types.Content(role="user", parts=[genai_types.Part.from_function_response(
name=tool_names_by_call_id.get(message["tool_call_id"], "tool"),
response={"result": message["content"]},
)]))
elif role == "assistant" and message.get("tool_calls"):
parts = [genai_types.Part.from_text(text=message["content"])] if message.get("content") else []
for tool_call in message["tool_calls"]:
tool_names_by_call_id[tool_call["id"]] = tool_call["function"]["name"]
parts.append(genai_types.Part.from_function_call(
name=tool_call["function"]["name"],
args=json.loads(tool_call["function"]["arguments"] or "{}"),
))
contents.append(genai_types.Content(role="model", parts=parts))
else:
google_role = "model" if role == "assistant" else "user"
contents.append(genai_types.Content(role=google_role, parts=[genai_types.Part.from_text(text=message["content"])]))
return system_instruction, contents
async def call_model(google_client, model_name, messages, tools, params, timeout_seconds) -> dict:
system_instruction, contents = to_google_contents(messages)
config_fields = dict(params)
if system_instruction is not None:
config_fields["system_instruction"] = system_instruction
if tools:
config_fields["tools"] = [genai_types.Tool(function_declarations=[
genai_types.FunctionDeclaration(
name=tool["function"]["name"],
description=tool["function"].get("description", ""),
parameters=tool["function"].get("parameters"),
) for tool in tools
])]
try:
response = await asyncio.wait_for(
google_client.aio.models.generate_content(
model=model_name, contents=contents, config=genai_types.GenerateContentConfig(**config_fields),
),
timeout=timeout_seconds,
)
except TimeoutError as timeout_error:
raise EndpointError(504, "timeout", str(timeout_error), is_retryable=True)
except genai_errors.ClientError as client_error:
if client_error.code == 429:
raise EndpointError(429, "rate_limited", str(client_error), is_retryable=True)
raise EndpointError(400, "invalid_params", str(client_error))
except genai_errors.APIError as provider_failure:
raise EndpointError(502, "provider_error", str(provider_failure), is_retryable=True)
candidate = response.candidates[0]
tool_calls = [{
"id": f"call_{index}",
"type": "function",
"function": {"name": part.function_call.name, "arguments": json.dumps(part.function_call.args or {})},
} for index, part in enumerate((candidate.content and candidate.content.parts) or []) if part.function_call]
usage = response.usage_metadata
return {
"output": response.text or "",
"tool_calls": tool_calls,
"finish_reason": "tool_calls" if tool_calls else GOOGLE_FINISH_REASONS.get(getattr(candidate.finish_reason, "name", "STOP"), "stop"),
"model_name": response.model_version or model_name,
"tokens": {
"input": usage.prompt_token_count or 0,
# Google reports thinking tokens outside candidates; the contract counts them inside output.
"output": (usage.candidates_token_count or 0) + (usage.thoughts_token_count or 0),
"thinking": usage.thoughts_token_count or 0,
"cached": usage.cached_content_token_count or 0,
},
}
```
Add `import asyncio` and `import json` at the top of the file for the Google version.
## OpenAI-compatible gateways (Azure, OpenRouter, vLLM, LiteLLM proxy)
Use the OpenAI template unchanged and point the client elsewhere:
```python
app.state.openai_client = openai.AsyncOpenAI(base_url=os.environ["LLM_GATEWAY_URL"], max_retries=0)
```
For Azure, use `openai.AsyncAzureOpenAI` and list deployment names as `model_name`.
Then ask your agent: "Add agent-doctor endpoints to this service."