Agent Architecture in Practice: Control Flow, Context, Evaluation, and More
Building an agent that shines in a demo is easy; keeping one stable and iterable in production is hard. This article breaks down the dimensions that matter most for production agent systems: control flow, context engineering, tool design, memory, multi-agent organization, evaluation and tracing, and security, ending with a reference implementation that ties the principles together. Readers will learn how to structure deterministic workflows with model-driven decisions, keep context windows clean, design tool interfaces that models can use reliably, and build measurable evaluation loops that take an agent from demo to production.
Agent Architecture in Practice: Control Flow, Context, Evaluation, and More
Building an agent that dazzles in a demo is easy. Building one that runs reliably in production and keeps improving is hard. The difference usually isn’t model capability—it’s architecture. This article focuses on the dimensions that most affect real-world agent deployments: control flow, context engineering, tool design, memory, multi-agent organization, evaluation and tracing, and security. It closes with an open-source-style reference implementation that ties all of these principles together.
1. Control Flow: From “Let the Model Improvise” to Bounded Orchestration
Control flow answers the question: who decides what happens next?
A common beginner approach is to hand full control to the model and let it decide which tools to call and when to stop. This works for simple cases, but as workflows get longer and more branching, excessive freedom leads to unreproducible behavior and failures that are hard to debug.
The more robust engineering approach is layered:
- Framework-level control: define the main flow explicitly with a state machine or DAG, where nodes are discrete steps and edges are governed transitions.
- Model-level decisions: within the boundaries the framework allows, let the model make local decisions, such as selecting a tool or extracting parameters.
Illustrative pseudocode:
graph = StateGraph()graph.add_node("understand", parse_intent)graph.add_node("plan", make_plan)graph.add_node("execute", run_tools)graph.add_node("reflect", check_result)graph.add_edge("understand", "plan")graph.add_conditional_edge("reflect", "execute", condition=retry_needed)
This “deterministic skeleton with probabilistic joints” pattern preserves the agent’s flexibility while giving the system the testability of traditional software.
2. Context Engineering: More Important Than Prompt Engineering
The core task of context engineering is: within a limited window, include the information most relevant to the current task. It is not about feeding everything to the model—it’s about making trade-offs.
In practice, this reduces to a few primitive operations:
- Write: add tool results and intermediate conclusions to the context.
- Select: dynamically decide which information stays in the window based on the current task.
- Compress: summarize conversation history, preserving key decisions and dropping redundant detail.
- Isolate: give independent subtasks their own context spaces to avoid cross-contamination.
A common failure mode is “context rot”: long-running conversations accumulate stale information and repeated tool outputs, attention gets diluted, and output quality degrades as turns increase. The remedy is to maintain a structured task state (the plan, completed steps, current conclusions) and assemble context by “rewriting rather than appending.”
3. Tool Design: Interfaces Are Constraints
Tools are the boundary between the agent and the outside world, and their design directly caps the agent’s capabilities.
Several proven principles:
- Descriptions are documentation: tool names, parameter names, and parameter descriptions should be immediately understandable to the model. Vague descriptions cause frequent call errors.
- Fewer is better: once a toolset exceeds roughly twenty tools, selection accuracy drops noticeably. Group and expose tools by task domain.
- Return structured, trimmed output: tool outputs should be pruned to return only the fields the model needs, not raw HTML or giant JSON blobs.
- Failures should be informative: error messages should tell the model what went wrong and how to fix it—for example, “Date format should be YYYY-MM-DD; you passed …”—giving the model a chance to self-correct.
@tooldef query_order(order_id: str, date_range: str = "recent 7 days"):"""Query order status. order_id is an order number such as ORD123456.date_range supports 'recent 7 days' / 'recent 30 days'."""
4. Memory: From Within a Session to Across Sessions
Agent memory typically has three layers:
- Short-term memory: the current context window, limited in length and requiring compression strategies.
- Session memory: complete interaction history persisted to external storage (a database or object storage), enabling replay and audit.
- Long-term memory: user preferences and factual knowledge distilled from historical interactions, retrieved for later sessions.
The key to long-term memory is not storing but retrieving: on write, deduplicate and resolve conflicts (new facts override old ones); on read, use vector or keyword retrieval to recall precisely. More memory is not better—injecting irrelevant memories pollutes the context too.
5. Multi-Agent Organization: When to Split and How to Collaborate
When a single agent carries too many responsibilities, tool-selection conflicts and interfering instructions intensify. Splitting into multiple agents is a common solution, but it’s not free: communication overhead and state synchronization are new sources of complexity.
Common organizational patterns:
- Orchestrator-worker: a Planner decomposes tasks and integrates results, while Workers each hold their own dedicated toolsets.
- Pipeline: agents run in stages, such as “retrieve → draft → review.”
- Debate/review: multiple agents critique the same output, suitable for high-reliability scenarios.
Split by responsibility domain, not by conversation turn. Keep each sub-agent’s context independent, passing only the information needed via messages.
6. Evaluation and Tracing: Without Measurement There Is No Iteration
The speed at which an agent system improves depends on the quality of its evaluation. Build three layers:
- Unit level: assertion-based tests for tool calls and parameter extraction, run against a fixed regression suite.
- Trajectory level: don’t just look at the final answer—examine whether intermediate steps were reasonable. Did the agent take detours, call the same tool repeatedly, or retry correctly after failure?
- End-to-end: evaluate overall success rate on realistic task sets, using LLM-as-a-judge for semantic scoring.
The tracing system should record every step’s inputs, outputs, latency, and token consumption, integrated with logging, monitoring, and alerting. This lets you pinpoint a production failure to a specific step within minutes.
7. Security: Permissions, Injection, and Audit
The core security risk for agents is that models can be manipulated by external content while holding real tool permissions.
- Least privilege: give each agent only the minimum toolset needed for its task; sensitive operations (deletion, payment) require human confirmation.
- Prompt injection defense: mark content from untrusted sources such as web pages and documents as isolated, and never concatenate it directly into instruction-bearing context.
- End-to-end auditing: log all tool calls to an audit trail that is traceable and replayable.
8. Reference Implementation: Seeing the Principles Together
Consider an open-source-style general-purpose agent framework (the “reference implementation”). You can observe the principles above taking shape: it uses a deterministic main loop with model-decision nodes for control flow; its context management supports filesystem-style read/write isolation and summary compression; tools use a unified registry with strict schema validation; the memory layer is decoupled from the session layer and can plug into different storage backends; multi-agent scenarios provide an orchestrator component and a message bus; and it ships with built-in trajectory tracing and evaluation hooks.
The value of studying such a reference implementation is not copying its code, but validating a conclusion: a great agent system = clear control-flow boundaries + careful context trade-offs + constrained tool interfaces + a measurable evaluation loop.
Conclusion
Agent engineering is evolving from “prompt tricks” into “systems engineering.” Control flow, context, tools, memory, multi-agent design, evaluation, and security are seven interdependent dimensions that jointly determine a system’s floor and ceiling. Understanding these principles and refining them in your own scenarios is the real path from demo to production.
