AI Agent Development Architecture, Tools & Security

Most teams that set out to build an AI agent don’t fail at the demo stage. The demo works. The model picks the right tool, drafts a sensible reply, and everyone is impressed. The trouble starts in week three of production, when the agent calls the same search tool eleven times in a row, invents a parameter that your API rejects, or follows an instruction hidden inside a customer’s email.
Table of contents
This guide is about that gap. It covers what an agent actually is at the code level, how to choose the simplest architecture that solves your problem, how the major frameworks differ, and what it takes to run an agent safely: guardrails, human approval, evaluation and cost control. It is written for developers, technical product managers and engineering leads making real build decisions.
Key Takeaways
- An agent is a loop, not a personality. A model repeatedly chooses an action, your code executes it through tools, and the result feeds back into state until a goal is met or a stop condition fires.
- Use the least agency that solves the problem. Move from prompt chain to router to tool-using agent to stateful graph to multi-agent only when the simpler level has failed on your real data.
- Multi-agent is a cost, not an upgrade. It adds latency, token usage and coordination failures. It pays off only when subtasks need different tools, permissions or conflicting prompts.
- Reliability comes from the surrounding system. Schemas, code-level validation, persisted state, step limits and logging do more for production behavior than a better prompt.
- Indirect prompt injection is the main security risk. Defend structurally with least-privilege tools, separated trust levels and validated arguments, because a stronger system prompt can’t reliably stop it.
- Gate irreversible actions. Classify tools by consequence and require human approval for payments, deletions, database writes and customer-facing messages.
- Write your evaluation set before the agent. Measure goal completion, trajectory quality, argument correctness, safety behavior, and cost per task, and turn every production failure into a regression test.
What Actually Makes Something an Agent
The word “agent” is stretched to cover everything from a chatbot with a system prompt to a fleet of cooperating services. A more useful definition is architectural:
An AI agent is a program in which a language model repeatedly decides what to do next, executes that decision through tools, observes the result, and updates its state until a goal is met or a stop condition fires.
The key phrase is repeatedly decided. In a fixed pipeline (retrieve documents, then summarize, then answer), the developer decides the control flow in advance. In an agent, the model chooses the next step at runtime, and your code enforces the boundaries around that choice.
One misconception is worth correcting early. Agents don’t “think” or “choose” in a human sense. Under the hood, an agent is a stateful loop. The model completes text, which your code parses into a structured tool call; your code executes it, feeds back the result, and branches on conditional logic. That framing matters because it tells you where reliability comes from: the loop, the schemas, the state and the guardrails, not the model’s “intelligence” alone.
Andrew Ng has argued that much of the recent performance gain from LLMs comes from agentic workflows (reflection, tool use, planning, multi-agent collaboration) wrapped around a model, rather than from waiting for a larger model (see Sources). This is the practical reason agent development has become its own engineering discipline.
The Four Building Blocks
Every agent, regardless of framework, is some combination of:
- A reasoning model that interprets the goal and picks actions.
- Tools that let it act: APIs, databases, code execution, search.
- Memory and state, covering what it knows about the current run and past interactions.
- A control loop that decides when to continue, escalate, or stop.
The Agent Spectrum Use The Simplest Thing That Works
The most valuable decision you will make is how much agency to give the system. More agency means more flexibility and also more latency, cost and Failure modes.
| Level | Pattern | Who controls the flow | Typical latency and cost | Good for | Main risk |
|---|---|---|---|---|---|
| 1 | Prompt chain | Developer (fixed steps) | Low | Extract → transform → format tasks | Brittle if inputs vary |
| 2 | Router | Model picks one branch; developer defines branches | Low | Triage: "billing vs. technical vs. sales" | Misrouting on ambiguous input |
| 3 | Tool-using agent (ReAct loop) | Model decides steps within a loop | Medium to high | Open-ended tasks needing several tool calls | Loops, wrong tool arguments |
| 4 | Stateful graph agent | Developer defines nodes and transitions; model decides within nodes | Medium to high | Long-running workflows needing approval, retries, resumption | Design complexity |
| 5 | Multi-agent system | Multiple specialized agents coordinate | Highest | Tasks that genuinely decompose into distinct roles | Compounding errors, token cost |
A practical rule: move down the table only when the level above has demonstrably failed on your real data. A router in front of three deterministic workflows beats a “general agent” for many support use cases. It is cheaper, faster, easier to test and easier to explain to a compliance reviewer.
Multi-agent designs deserve particular skepticism. They add latency, token consumption and coordination failure points. If one agent with well-defined tools can do the job, splitting it into several usually makes it worse. Multi-agent setups earn their place when roles need different tools, different permissions or different prompts that would conflict inside one context window.
Core Architecture How the Pieces Interact
The execution loop looks like this:
User input → state initialization → model reasoning/planning → tool selection → safety or human-approval check → tool execution → observation → state update → goal evaluation → (loop again or return a response)
Planning and reasoning Patterns
Three patterns cover most of what you will encounter:
- ReAct (Reasoning and Acting): the model alternates between a thought, an action and an observation. It is flexible and the default for tool-using agents, but it re-plans every step, which can cost tokens.
- Plan-and-Solve: The model writes a plan first, then executes the steps. This is more predictable and easier to show to a human for approval, but less adaptive when a step fails.
- Reflection: The Model reviews an earlier output and produces a revision, using its own assessment or feedback from an evaluator. This can help with tasks such as code generation, writing, and structured problem-solving, but improvement is not guaranteed. Repeated revisions can increase latency and cost without improving the result. Set a maximum number of attempts and define a measurable stopping condition, such as passing a test suite or meeting a specified quality threshold.
Memory More than “RAG”
A frequent confusion is treating retrieval-augmented generation (RAG) as agent memory. Simple RAG is passive retrieval: fetch relevant chunks, add them to the prompt. Agent memory involves active management: deciding what to store, summarizing, updating and discarding.
| Memory type | What it holds | Typical implementation | Watch out for |
|---|---|---|---|
| Scratchpad | Intermediate reasoning and tool results for the current run | In-state fields | Growing until it floods the context window |
| Short-term context | Recent conversation turns | Message history, trimmed or summarized | Silent truncation losing key constraints |
| Long-term semantic memory | Facts and preferences across sessions | Vector store with metadata | Stale or contradictory entries |
| Graph memory | Entities and relationships | Knowledge graph | Higher build and maintenance cost |
Start with scratchpad plus short-term context. Add long-term memory only when you can name a user-visible behavior that needs it, and decide up front how entries expire or get corrected.
Tools, Structured Outputs and the Model Context Protocol
AI agents interact with external systems through tools such as APIs, databases, search services, and application functions. In a typical implementation, developers define the available tools and their input schemas. The model can request a tool call, but the application remains responsible for validating the request, executing the action, and returning the result.
Function calling and structured outputs serve different purposes. Function calling allows a model to request an application action through a defined tool interface. Structured outputs constrain a model's response to a specified data format. Both can improve consistency, but neither guarantees that the requested action is correct, authorized, or appropriate.
For example, a tool might accept an order_id as a valid string. That does not prove that the order exists or belongs to the authenticated customer. Application code must check those conditions before returning order details or performing an action.
A reliable tool-execution layer should:
- Validate arguments against the expected schema.
- Check business rules, resource ownership, and permissions independently of the model.
- Restrict tools to the resources and actions required for the task.
- Handle timeouts, rejected requests, and unavailable services.
- Record tool calls, authorization decisions, and outcomes for debugging and evaluation.
The Model Context Protocol (MCP) is an open protocol for connecting AI Applications with external tools and data sources through a standardized client-server interface. It can reduce the need to build a separate integration for every compatible client and service. However, protocol compatibility does not automatically provide security. Each integration still needs appropriate authentication, access controls, and review of the capabilities it exposes.
The key design principle is to let the model propose actions while the application controls which actions are permitted to execute.
Example Designing a Safe Order-Status Agent
Consider an AI agent that answers customer questions about order status and refund eligibility. The agent should retrieve verified information and explain the result, but it should not bypass customer permissions or independently approve restricted actions.
A basic implementation can follow this sequence:
- Receive the request: Identify the customer's question and obtain the authenticated user context from the application.
- Call the lookup tool: Allow the model to request an order-status lookup using a defined input schema.
- Validate access: Check in application code that the requested order belongs to the authenticated customer.
- Apply business rules: Evaluate refund eligibility using the application's authoritative policy and order data rather than relying solely on the model's judgment.
- Handle exceptions: Return a clear explanation for ineligible requests or escalate cases that require human review.
- Record the outcome: Log the relevant tool calls, authorization decision, result, and any escalation needed.
The evaluation set should include successful lookups, nonexistent order IDs, unauthorized access attempts, ambiguous refund requests, and cases that require approval.
A test passes only when the agent returns an appropriate result, respects access restrictions, and follows the required action policy. This example describes a proposed design; production reliability must be established through implementation and testing.
State management and Persistence
Long-running agents get interrupted: a human takes hours to approve something, an API times out, a process restarts. If the state lives only in memory, the run is lost.
Graph-based frameworks address this by modeling the workflow as a directed graph. Nodes are actions or model calls, edges are transitions, and a shared state object is updated at each step, with checkpoints saved so a run can pause, resume or be replayed. LangGraph’s documentation describes this approach, including persistence, human-in-the-loop support and “time-travel” debugging of past states. When several nodes write to the same field (for example, a list of messages), you define a reducer that specifies how updates merge, so parallel branches don’t overwrite each other.
Framework Comparison
Frameworks change quickly, so choose based on the paradigm you need rather than popularity, and check current documentation before committing.
| Framework | Paradigm | Best fit | State handling | Learning curve |
|---|---|---|---|---|
| LangGraph | Cyclic state machine (graph) | Production workflows needing fine-grained control and approvals | Explicit state schema with persistence | Moderate to high |
| CrewAI | Role-based teams | Fast prototypes of multi-role tasks (research → draft → review) | Implicit, passed between tasks | Low to moderate |
| AutoGen (legacy) | Conversational multi-agent | Understanding or maintaining existing AutoGen implementations | The official repository is archived and no longer maintained; evaluate migration options before selecting it for a new production system | Depends on the existing implementation |
| Semantic Kernel (Microsoft) | Plugin/skill architecture | Adding LLM capabilities to existing C#, Java or Python enterprise apps | Native application context and telemetry | Moderate |
How to choose, in practice:
- If you need a pause/resume, approval gates and an audit trail, a graph-based approach like LangGraph gives you the most explicit control, at the cost of more upfront design.
- If your problem naturally reads as “a researcher, a writer and an editor,” CrewAI gets you to a working prototype fastest. Expect to do more work later if you need fine-grained control over state and failure handling.
- If you are exploring conversational multi-agent systems, first evaluate actively maintained frameworks that fit your requirements. Microsoft's AutoGen repository is archived and no longer maintained, so teams considering it for new projects should review Microsoft's current Agent Framework documentation and migration guidance before making a decision.
- If you are inside a .NET or Java enterprise codebase with existing governance and telemetry requirements, Semantic Kernel is designed to slot into it.
You can also build without a Framework. For a router or a single tool-using agent, a plain loop around a provider SDK is often clearer and easier to debug than a framework abstraction. Adopt a framework when you need what it provides (persistence, orchestration, observability), not by default.
Production Realities
Security Design for Indirect Prompt Injection
Indirect prompt injection occurs when an agent encounters untrusted content, such as an email, webpage, or support ticket, that contains instructions intended to influence its behavior. The risk increases when the same agent can read external content and execute sensitive actions.
Prompt instructions alone cannot guarantee that an agent will ignore malicious content. Security must be enforced by the surrounding application.
Use the following controls:
- Least privilege: Give each agent only the tools and resource permissions required for its task. An agent that summarizes emails should not automatically have permission to send them.
- Trust separation: Treat retrieved documents and tool responses as untrusted input. Their contents must not grant permissions or override application-level policies.
- Independent authorization: Check the authenticated user's identity, resource ownership, and action permissions in application code before executing a tool.
- Constrained execution: Validate arguments, restrict database roles, allow only approved destinations where appropriate, and use narrowly scoped API credentials.
- Human approval: Require explicit review for sensitive or irreversible actions. Show the reviewer the exact proposed action, its arguments, and the relevant target before execution.
- Auditability: Record tool calls, authorization decisions, errors, and approval outcomes while protecting sensitive information in logs.
- These controls reduce exposure but do not eliminate every attack. Test the system against malicious inputs, unauthorized access attempts, and unexpected tool requests before expanding its permissions.
Human in the Loop for High-Risk Actions
Not every tool call needs a human. Classify tools by consequence:
| Risk tier | Examples | Recommended policy |
|---|---|---|
| Read-only | Search public documentation, retrieve an authorized order status | Allow execution within defined access permissions and log relevant activity |
| Low-risk write | Create a draft, prepare an email, generate a proposed ticket | Allow within defined limits; validate the output and review where appropriate |
| Sensitive or consequential action | Send a customer email, modify account information, issue a refund | Require authorization checks and approval when the action's impact or policy requires it |
| High-impact or difficult-to-reverse action | Delete production records, execute privileged database writes, transfer funds | Require explicit authorization, human approval where appropriate, and safeguards against duplicate execution |
In a graph-based design, the approval step is an interrupt placed before the sensitive node. The run saves (checkpoints) its state, waits for minutes or even days, and resumes only when a reviewer approves, edits or rejects the proposed action. Because the state is saved, the agent doesn’t lose its progress while it waits, and the reviewer sees exactly what the agent intended to do.
A concrete scenario: an analytics agent that can query a Production database. Let it generate the SQL freely, run it automatically against a read-only replica, and require human approval for anything that touches a write-enabled connection.
Evaluating Nondeterministic Agents
You can’t unit-test an agent with one expected string. Evaluate behavior at several levels:
- Goal completion: did the run achieve the outcome? Define this per task, ideally with a checkable end state (the ticket exists, the refund amount is correct).
- Trajectory quality: did it take a reasonable path? Check tool selection accuracy, redundant calls and unnecessary steps.
- Argument correctness: were tool parameters valid and right?
- Safety behavior: does it refuse or escalate on injection attempts and out-of-scope requests?
- Cost and latency per task: tokens, number of steps, wall-clock time.
Build a regression set from realistic task examples, including previous failures, adversarial inputs, and out-of-scope requests. Each test should define the expected outcome, permitted actions, prohibited actions, and measurable pass/fail criteria.
For example, an order-status agent should return the correct status for an authorized order and must not reveal another customer's order details. A refund-related test should verify both the eligibility decision and whether the agent followed the required approval process.
Run tests multiple times when model variability can affect the result. Track pass rates, failure categories, tool-call accuracy, safety violations, latency, and cost. Choose the number of runs according to the task's risk, observed variability, and evaluation budget rather than treating one sample size as universally sufficient.
Tools such as Ragas, Braintrust, and DeepEval can support parts of an evaluation workflow. Verify their current capabilities and supplement them with application-specific checks for business rules, permissions, and task outcomes.
Cost and Latency Control
Agent loops multiply model calls, so costs can surprise you. Practical controls:
- Hard limits: maximum steps, maximum tokens and a timeout per run, with a defined fallback (escalate to a human or return a partial result).
- Hybrid model routing: use a small, fast model for routing and simple extraction and reserve a frontier model for complex planning. Measure quality per task before and after, since savings only count if accuracy holds.
- Context pruning: summarize or drop old tool outputs rather than carrying everything forward.
- Caching: use prompt caching where your provider supports it, and cache deterministic tool results.
Failure Modes to Expect
| Failure | What it looks like | Mitigation |
|---|---|---|
| Infinite reflection or tool loops | Same call repeated, tokens burn | Step caps, loop detection, forced exit path |
| Hallucinated tool arguments | Valid schema, nonexistent ID | Code-level validation, informative errors |
| Context flooding | Quality degrades as tool outputs pile up | Pruning, summarization, retrieval of only what’s needed |
| Tool overload | Agent picks wrong tool among dozens | Fewer, clearer tools; routers to narrow the set |
| Over-delegation to multi-agent | Latency and cost up, accuracy flat | Return to a single agent unless roles truly differ |
Early autonomous-loop experiments such as AutoGPT and BabyAGI showed the concept but are poor references for production design. They were prone to getting stuck. Today’s approach favors constrained state machines and structured function calling.
Conclusion
Reliable AI agent development starts with a clear task, not with the most autonomous architecture. A fixed workflow or router may be sufficient for a predictable problem, while tasks that require dynamic tool selection, persistent state, or approval checkpoints may justify a more capable orchestration design.
Before deployment, define what success means, restrict the agent's tools, validate actions in application code, and establish limits for execution time and cost. For sensitive operations, enforce authorization independently of the model and require approval where the consequences justify it.
Evaluation should guide every decision to add complexity. Build a representative test set, measure task completion and failure behavior, and turn production incidents into regression tests. Select frameworks based on their verified capabilities and maintenance status rather than popularity alone.
A practical first step is to choose one narrow task, document its permitted and prohibited actions, and build the smallest implementation that can be evaluated against those requirements. Expand its capabilities only when the evidence supports doing so.


