Agent Architecture Engineering: 7 Key Pillars
A practical breakdown of what really determines AI agent reliability: why upgrading the model is usually the wrong first move, how to keep a stable perceive–decide–act–feedback core loop, how to budget the context window, how to write tool contracts that the model can actually choose from correctly, how to structure short-term, long-term, and structured state memory, when multi-agent topologies are justified, and how evaluation, tracing, and safety make the system measurable and reproducible. Includes a deployment checklist that ranks framework clarity, tool contract accuracy, context and memory restraint, and rigorous evaluation above model upgrades.
1. Why “swap in a stronger model” is usually not the best fix
In the engineering practice of agent systems, one judgment keeps proving itself: replacing the model with a more expensive, larger version usually raises the success rate less than expected. What really decides the outcome is the execution layer wrapped around the model (commonly called a harness in the industry), together with the quality of verification and testing.
The reason is not mysterious. The large majority of agent failures are not a lack of reasoning ability but a problem in the information and action channels: the context that should have been visible was never seen, the tool that should have been called was not called correctly, the intermediate result that should have been validated was never checked, and the failing trace cannot be reproduced. These problems do not disappear because the model got stronger, and a more “confident” model can actually make them harder to expose.
From this follows an engineering priority: fix the harness and the verification first, then talk about swapping the model. A suggested order:
complete observability → tighten tool contracts → build a regression-capable evaluation set → optimize the context budget → and only then evaluate the marginal return of a model upgrade.
2. Control flow: one stable core loop beats a complex state machine
Strip away every peripheral capability and an agent’s main loop can be abstracted into less than twenty lines of pseudocode:
messages = [{"role": "user", "content": user_input}]while True:resp = client.create(model=MODEL, tools=tool_defs, messages=messages)if resp.stop_reason == "tool_use":results = run_tools_concurrently(resp.tool_calls) # run in parallelmessages.append({"role": "assistant", "content": resp.content})messages.append({"role": "user", "content": results})else:return extract_text(resp.content)
The corresponding control flow keeps cycling through four phases — perceive → decide → act → feedback — until the model outputs plain text.
The stability of this loop is worth emphasizing. Going from a minimal implementation to support for sub-agents, context compaction, and on-demand skill loading requires almost no change to the main loop; new capabilities are all layered on outside the loop. There are only three legitimate paths for adding a capability:
- Extend the tool set and the corresponding handler functions;
- Adjust the structure and layering of the system prompt;
- Externalize state into a file, a database, or object storage.
The anti-pattern is to write the loop body as one giant state machine and stuff business state, retry policy, and permission checks inside the loop. The correct division of labor: the model handles reasoning, external systems handle state and boundaries. Once that division is fixed, the core loop rarely needs to change, and the maintainability of the system stabilizes with it.
Three engineering details are worth standardizing: tool calls should support parallel execution to compress end-to-end latency; every turn needs an explicit termination condition and a maximum turn limit to avoid infinite loops that burn budget; and feedback content must be structured tool results rather than natural-language paraphrases.
3. Context engineering: treat the limited window as a budget
Context is the agent’s only working memory, and its quality directly determines the quality of decisions. The goal of context engineering is not to pack in as much as possible, but to maximize the density of critical information within a limited budget.
A workable allocation approach:
| Component | Suggested share | Notes |
|---|---|---|
| System prompt and rules | 10%–15% | Stable, concise, loadable in layers |
| Tool definitions | 15%–25% | Expose only the tools the current scenario needs |
| Retrieved external knowledge | 25%–35% | Tagged with source and freshness |
| Conversation and tool traces | 25%–35% | Keep the basis for decisions, compress redundant output |
Three common techniques: layered loading (start with a summary and a table of contents, expand details only when needed), compression and summarization (fold a long trace into conclusions plus key evidence), and externalized memory (write large blocks of state to external storage and keep only a pointer in the context). The test is simple: if removing a piece of content does not change the model’s decisions, it should not consume budget.
4. Tool design: most “wrong tool” choices are actually inaccurate descriptions
When debugging abnormal agent behavior, the first stop should be the tool definitions, not the model or the prompt. In practice, the vast majority of tool-selection errors trace back to inaccurate descriptions: vague names, unclear parameter semantics, missing boundary conditions, unstable return structures.
A sound tool contract should include:
- Name: verb–object structure, semantically unique, avoiding duplicate near-synonyms;
- Description: explain “when to use” and “when not to use”, not just “what it does”;
- Parameters: type, whether required, allowed values, default, and unit all specified;
- Return: fixed structure with self-explanatory fields, errors returned in structured form rather than thrown as exceptions;
- Boundaries: idempotency, whether it can be retried, the scope of side effects (write operations in particular need to be confirmable).
The number of tools also needs to be controlled. Tools of the same kind should be merged into a single tool with a mode parameter, so the model does not waver among a dozen near-identical options. For write operations, consider adding a second confirmation step or a dry-run mode, keeping irreversible risk out in front of execution.
5. Memory: distinguish three types and define write and forget policies
Memory is not “store all history”, but layered management:
- Short-term memory: the trace of the current task, reclaimed when the session ends;
- Long-term memory: user preferences and project conventions that span sessions, requiring explicit writes and de-duplication;
- Structured state: task progress and intermediate artifacts, externalized to a database or files so they can be queried and rolled back.
The critical design is writing and forgetting: writes need a trigger condition and a confidence threshold so noise does not accumulate; forgetting needs expiry and conflict-resolution policies so old conclusions do not override new facts. Memory entries should ideally carry a source and a timestamp, which makes it possible to settle conflicts by freshness.
6. Multi-agent organization: first ask whether you actually need it
Multi-agent systems are not an amplifier of capability, but a tool for context isolation and parallelism. It is only worth introducing them when the task can be clearly partitioned, the subtasks are loosely coupled, and a single agent’s context genuinely cannot hold the work.
There are three common topologies: orchestrator–executor (a lead agent decomposes the task and aggregates results), pipeline (serial stages that pass artifacts along), and peer collaboration (rare, hard to converge, use with caution). Key practices: sub-agents should return only structured conclusions rather than the entire process; set a maximum nesting depth and an overall budget; and avoid multiple agents writing the same state simultaneously.
7. Evaluation, tracing, and safety: make the system measurable, reproducible, and convergent
Evaluation is the central nervous system of the whole architecture. The case set should cover the happy path, boundaries, and adversarial inputs. Metrics should go beyond final-answer accuracy to include tool-selection accuracy, average number of turns, latency, and cost. Run a regression on every change so you do not “fix one thing and break three”.
A trap that is easy to overlook: problems in the evaluation system itself are harder to detect than problems in the agent. A case set that is too narrow, pass criteria that are too lenient, or reference answers that are themselves wrong will all inflate the metrics. If you have been tuning the agent code repeatedly for a long time with no movement in the numbers, go back and audit the evaluation criteria and the quality of the data.
Tracing requires every run to be replayable: record the full trace, tool inputs and outputs, context snapshots, and version numbers, so that online failures can be turned into reproducible offline cases.
Safety needs multiple lines of defense: filter prompt injection on the input side, follow least privilege on the permission side with tiered authorization for write operations, mask sensitive data on the data side, set cost limits and circuit breakers on the runtime side, and force human confirmation for high-risk actions on the output side. These capabilities can be built on general-purpose cloud platform offerings such as logging, monitoring and alerting, key management, and access control, without binding to any particular vendor’s interface.
8. Bringing the principles together: a pre-launch checklist
- Does the main loop keep the simple perceive–decide–act–feedback structure, with new capabilities only layered on the periphery?
- Does the context have an explicit budget, keeping only content that affects decisions?
- Does every tool description state where it applies and where it does not, and are returns structured?
- Is memory layered, with a write threshold and a forgetting policy?
- Are multi-agents really necessary, and do sub-agents return only conclusions?
- Does the evaluation set cover boundaries and adversarial samples, and have the pass criteria been audited?
- Is every run traceable and replayable, and do write operations have confirmation and circuit breakers?
The conclusion returns to the original judgment: the engineering returns of an agent come mainly from the clarity of the harness, the accuracy of tool contracts, the restraint applied to context and memory, and the rigor of evaluation and tracing. A model upgrade is the final marginal optimization, not the first-resort lifeline.
