Most AI agent demos collapse plan, reason, and act into a single opaque loop—fine for a proof-of-concept, fragile in production. The difference between a chatbot that works on your laptop and an agent that runs reliably in a regulated environment is architecture: explicit phases, uniform controls, complete audit trails, and managed dependencies. This article walks through five core pillars of production agent design, from runtime stages to API orchestration.
Five-phase agent runtime
A production agent runtime separates the classic "sense-think-act" loop into discrete, testable phases. The canonical breakdown is five stages: plan, reason, act, observe, and reflect.
Plan receives a user goal and decomposes it into a high-level sequence of steps. This phase emits a task graph or checklist—an artifact you can inspect, version, and replay. Planning often involves a large language model (LLM) call with a structured output schema, constrained by a template or grammar.
Reason selects tools, queries knowledge, and decides on next actions for each step in the plan. Reasoning produces one or more candidate actions, each with a confidence score or rationale. This phase is where retrieval-augmented generation (RAG) hooks in—pulling context from vector databases, SQL stores, or enterprise APIs.
Act executes the chosen action—calling an external API, writing to a database, sending a notification. Actions should be idempotent or wrapped in compensating transactions; a production runtime must tolerate retries and partial failures.
Observe collects the result of the action, including success/failure signals, latency, cost, and any side effects. Observations feed back into the next reasoning cycle and populate the audit log.
Reflect periodically reviews recent trajectories—did the agent achieve the goal, did it waste tokens, did it hit guardrails? Reflection can trigger plan revisions, preference updates, or alerts. In a self-improving system, reflection generates training data for fine-tuning or reinforcement learning.
Think of these phases as a pipeline in a data engineering system: each stage has clear inputs, outputs, and contracts. You can unit-test reasoning logic against mocked observations or swap out the act layer to switch models.
You can unit-test reasoning logic against mocked observations, replay a failed plan with updated guardrails, or swap out the act layer to switch from OpenAI to a self-hosted model. Each phase becomes a testable, replaceable component.
Cross-cutting trust controls
Governance in an agent system means enforcing policy at every decision point, not just at the prompt boundary. A production architecture implements controls as middleware that wraps each phase.
Input validation checks that the user goal is within scope before planning begins. Use classifiers—fine-tuned BERT, zero-shot LLM, or rule engines—to reject out-of-domain requests, personally identifiable information (PII), or abusive language.
Budget guardrails track token usage, API calls, and wall-clock time. Each phase checks a shared budget counter; if the agent exceeds a threshold, the runtime halts and escalates. Budgets can be per-request, per-user, or per-tenant.
Action allow-lists maintain an explicit registry of permitted tools and APIs. Reasoning outputs candidate actions; the act phase validates each against the registry. A tool schema describes parameters, required permissions, and rate limits.
Output filtering scans responses before returning them, checking for hallucinated URLs, leaked credentials, or toxic content. Use a combination of regex, named entity recognition (NER), and a secondary LLM call tuned for safety.
Governance is not a feature you add at the end—it is middleware that wraps every stage of the agent loop, enforcing policy from plan to reflect.
These controls compose. A single middleware stack can apply role-based access control (RBAC), log every decision to an append-only audit trail, and inject telemetry spans for distributed tracing. Every execution path—happy, error, or timeout—flows through the same governance layer.
Production observability
An agent in production generates hundreds of events per request: LLM calls, database queries, API roundtrips, guardrail checks. Observability means capturing these events in a way that supports debugging, cost attribution, and compliance.
Audit trails write every phase transition to a structured log—JSON or Protocol Buffers—with a correlation ID linking all events in a single agent session. Include timestamps, user context, plan snapshots, tool invocations, and outcomes. Store trails in a tamper-evident log—AWS CloudTrail, Google Chronicle, or an append-only database—for regulatory audits.
Cost tracking monitors token consumption (input and output), compute (inference milliseconds), and external API quota. Tag every LLM call with a cost estimate; roll up costs by session, user, and tenant. Use OpenTelemetry attributes to annotate traces with token counts and model names. Surface per-request cost in dashboards and alert when anomalies appear.
Latency and error budgets treat each phase as a service in a microservice mesh. Measure p50, p99, and error rates for plan, reason, act, and reflect. Set service-level objectives (SLOs)—for example, "95 % of agent sessions complete within 10 seconds"—and page when you violate them.
Guardrail telemetry counts how often each control fires—how many requests fail input validation, how many hit budget caps, how many trigger output filters. A spike in guardrail rejections may indicate a new attack vector or a shift in user behavior.
A practical stack combines OpenTelemetry for tracing, Prometheus or Datadog for metrics, and a data warehouse—BigQuery, Snowflake—for long-term log retention. Export agent sessions to dashboards that show cost per user, tool usage frequency, and plan success rates.
| Metric | Source | Use case |
|---|---|---|
| Tokens per session | LLM provider API | Cost attribution, budget alerts |
| Plan success rate | Reflect phase logs | Detect when reasoning degrades |
| Guardrail rejection rate | Governance middleware | Security monitoring, policy tuning |
| Tool invocation latency | Act phase tracing | Performance optimization, SLA tracking |
| Knowledge retrieval | RAG subsystem metrics | Improve embedding quality, index coverage |
Knowledge and state architecture
Agents rely on two kinds of memory: short-term state (the current session) and long-term knowledge (facts, documents, tool schemas). A production system separates these concerns.
Short-term state lives in-process or in a fast key-value store—Redis, Memcached. Each session has a unique ID; the runtime appends plan steps, observations, and reflection summaries to the session record. State expires after a timeout (for example, one hour) or when the user explicitly ends the session. For multi-turn conversations, serialize the conversation history as a prompt context or a structured summary.
Long-term knowledge powers RAG. The architecture has three layers.
Embedding store: A vector database—Pinecone, Weaviate, pgvector—holds dense embeddings of documents, tool descriptions, and prior agent trajectories. During the reason phase, the agent queries the store with a semantic search, retrieves top-k candidates, and injects them into the LLM context.
Metadata index: A relational or document database—Postgres, Elasticsearch—stores structured metadata: document source, update timestamp, access control tags. The RAG pipeline joins vector results with metadata to enforce permissions and recency filters.
Grounding corpus: The raw documents, API schemas, and logs that embeddings reference. Stored in object storage—S3, Google Cloud Storage—versioned, and cached. When the agent cites a source, it can link back to the original artifact for human review.
Think of RAG as a compiler: the embedding store is an index, metadata is the symbol table, and grounding is the source code. Queries compile user goals into SQL-like operations before invoking the LLM.
Memory layers scale differently. Embeddings grow linearly with corpus size; you shard by tenant or topic. Metadata queries use standard relational optimizations—indexes, partitioning. Session state churn is high but short-lived; use a write-through cache and evict aggressively.
For compliance, tag embeddings with retention policies. A regulated agent may need to delete all user-specific knowledge within 30 days; the architecture must support selective purging without reindexing the entire corpus.
API gateway and orchestration
Production agents do not run as monolithic scripts. They compose managed services—LLM APIs, vector databases, observability backends—behind a gateway that handles routing, retries, rate limiting, and failover.
API gateway: An HTTP or gRPC layer fronts the agent runtime. Clients—web apps, Slack bots, CI pipelines—send goals to the gateway; it authenticates the request, assigns a session ID, and dispatches to the runtime. The gateway enforces per-user quotas, rewrites errors into client-friendly messages, and strips internal telemetry before returning responses. Use AWS API Gateway, Kong, or Envoy.
Orchestration: The agent runtime is a state machine—plan, reason, act, observe, reflect. Implement it as a workflow in a durable execution framework—Temporal, AWS Step Functions, Airflow. Each phase is a task or activity; the orchestrator handles retries, timeouts, and compensation. Workflows persist state across failures; if the LLM API times out during reasoning, the orchestrator retries the same step without re-planning.
Model routing: Route requests to different LLMs based on task type, latency budget, or cost constraints. Use a lightweight router—a JSON config or a feature flag service—to map "high-stakes reasoning" to GPT-4 and "simple classification" to a fine-tuned Llama model. The router can also implement A/B tests, sending 10 % of traffic to a candidate model and comparing outcomes.
Tool adapters: Each external API the agent calls—a CRM, a payment gateway, a knowledge base—gets an adapter that normalizes inputs, outputs, and errors. Adapters translate HTTP 429 (rate limit) into a budget exhaustion signal, convert REST pagination into a stream, and redact secrets from logs. Adapters are the boundary between agent logic and the messy reality of third-party integrations.
A typical stack: API Gateway handles ingress, Temporal orchestrates the five-phase loop, OpenTelemetry collectors push traces to Datadog, and a vector database—pgvector—serves RAG. The agent code is Python or TypeScript, deployed as a containerized service on Kubernetes, with model calls proxied through a cost-tracking sidecar.
What this means for builders
If you are moving an agent from prototype to production, start by decomposing the runtime into testable phases. Write unit tests for each phase in isolation—mock the LLM responses, simulate guardrail failures, replay observations. Treat the agent as a distributed system, not a script; instrument it with traces and metrics from day one.
Implement governance early. A single PII leak or runaway API bill will kill trust faster than any technical achievement. Use schema validation, budget caps, and output filters as default middleware, not optional add-ons.
Design your knowledge architecture for scale and compliance. Embeddings need versioning, metadata needs RBAC, and session state needs time-to-live policies. If your agent will serve regulated industries, build deletion and audit hooks before you load the first document.
Lean on managed services for orchestration and observability. A durable workflow engine—Temporal, Step Functions—buys you retries, compensation, and visibility into long-running agent sessions. OpenTelemetry and a metrics backend—Prometheus, Datadog—are cheaper than building your own distributed tracing stack.
Separate model inference from agent logic. Use API gateways and adapters to isolate vendor-specific quirks. Switching from OpenAI to Anthropic or a self-hosted model should be a configuration change, not a rewrite.
Conclusion
Production AI agents demand the same rigor as any distributed system: modularity, observability, and fault tolerance. The architecture presented here—five-phase runtime, cross-cutting governance, structured observability, layered knowledge, and managed orchestration—reflects patterns from teams running agents in finance, healthcare, and enterprise support, where failures have compliance and cost consequences. As agents become infrastructure, the engineering discipline shifts from prompt tuning to systems design. The builders who treat agents as stateful, auditable, policy-enforced services will ship the ones that last.
