The Agentic AI Codex
Ch 15 · Deployment & Observability
Chapter 15 · From notebook to production

Deploying & observing AI agents

Shipping an agent is shipping a probabilistic system. That means new requirements: traces over logs, evaluations over unit tests, cost budgets next to latency budgets. This chapter is the playbook to take an agent from a working notebook to a service your team can run on call.

15.1 · The production stack

Client (web / Slack / phone)→ API gateway→ Auth + rate limit→ Agent service
LLM provider(s) Vector DB Tools / MCP servers Object storage Telemetry

15.2 · Serving — FastAPI for code, Streamlit for screens

FastAPI is the de-facto choice for serving an agent. It's async, has clean typing, and plays well with streaming responses.

@app.post("/chat")
async def chat(req: ChatRequest, user: User = Depends(auth)):
    async for chunk in agent.stream(user, req.message):
        yield chunk

Streamlit, on the other hand, lets you produce a clickable UI in a single file — perfect for internal demos and prototypes.

15.3 · Delivery channels

  • Web — a chat surface or an embedded widget.
  • Slack / Teams / Discord — bot users; works inside threads.
  • Email — agents that triage and reply to a mailbox.
  • WhatsApp / Telegram — webhook-driven; popular in many markets.
  • Voice — STT → agent → TTS. Latency budget is brutal (~700 ms total).

15.4 · Observability — traces over logs

A request log doesn't help you debug an agent. You need traces: every model call, every tool call, every retrieval, with inputs, outputs, latency, token count, and cost — all stitched into one timeline per request.

ToolNotes
LangSmithLangChain ecosystem; deepest integration with LangGraph.
LangfuseOpen-source, self-hostable, framework-agnostic.
OpenLLMetry / OpenTelemetryVendor-neutral OTel attributes for LLM calls.
HeliconeDrop-in proxy for token + cost analytics.
Arize PhoenixStrong eval + drift dashboards.

15.5 · Evaluation — three tiers

  1. Unit-level: deterministic checks per skill (JSON schema, tool args, output length).
  2. Task-level: 20–200 frozen tasks with expected outcomes or rubrics scored by LLM-as-judge.
  3. System-level: real-traffic shadow testing, A/B between two agent versions.
@eval(suite="refunds")
def test_refund_intent_for_double_charge():
    out = agent.run("my card was charged twice for the same order")
    assert out.intent == "billing"
    assert "refund" in out.text.lower()
The single best agent habit
Run evals on every prompt or model change before merge. Treat your eval suite like a CI test: red → no deploy.
  1. Unit-level: deterministic checks per skill (JSON schema, tool args, output length).
  2. Task-level: 20–200 frozen tasks with expected outcomes or rubrics scored by LLM-as-judge.
  3. System-level: real-traffic shadow testing, A/B between two agent versions.
@eval(suite="refunds")
def test_refund_intent_for_double_charge():
    out = agent.run("my card was charged twice for the same order")
    assert out.intent == "billing"
    assert "refund" in out.text.lower()
The single best agent habit
Run evals on every prompt or model change before merge. Treat your eval suite like a CI test: red → no deploy.

15.6 · Cost & latency engineering

  • Prompt caching — keep stable prefix on top → 50–90% prefill cost savings.
  • Model cascade — try a small/cheap model first; fall back to a frontier model when it refuses or low-confidence.
  • Batching — for offline jobs, batch many requests through the provider's batch API for ~50% discount.
  • Streaming — show tokens as they generate; perceived latency drops dramatically.
  • Speculative decoding (on local / vLLM) — small draft + big verify → faster generation.
  • Token budgets — cap output length per agent step; reject runs over a token ceiling.

15.7 · Secrets, auth, multi-tenancy

  1. Never inline API keys — use a secret manager (AWS / GCP / Vault).
  2. OAuth / OIDC for user identity; pass scoped tokens to tools.
  3. Tenant isolation — every DB / vector query filters on tenant_id at the lowest layer.
  4. Per-tenant rate limits & budgets — a runaway agent can't blow your monthly bill.
  5. Audit logs — append-only record of every action an agent took on behalf of a user.

15.8 · Release safety

  • Feature flags — every new tool, prompt, or model behind a flag.
  • Canary deploys — 1% of traffic to the new version; auto-rollback if eval scores or error rates dip.
  • Shadow runs — for a week, run new agent in parallel without showing output; compare offline.
  • Kill switch — a single config that disables tool calls or the agent entirely.

15.9 · The agentic SRE checklist

  1. Provider outages handled (multi-provider fallback or graceful degrade).
  2. Vector DB has snapshots and re-index automation.
  3. Eval suite green on the deployed version.
  4. Dashboards: TPM, $/req, p95 latency, refusal rate, tool-error rate.
  5. Alerts: cost spike, eval drop, refusal spike, tool failure spike.
  6. Runbook for: prompt-injection incident, leaked PII, data deletion request.

15.10 · Self-check

Q1 · Why are traces more useful than logs for agents?
They're faster to write
They show the full causal chain per request
They are cheaper to store
They eliminate hallucinations
Q2 · You ship a prompt change. Best gate?
"It worked in the notebook"
Eval suite green in CI
PM approval over Slack
Feature flag only