AI Agents: The Complete Guide
Agent Architecture Overview
ReAct Pattern: Reasoning and Acting
Tool Use Architecture
A Minimal Agent Loop You Can Run
Everything else in this lesson refines one loop: read the goal, choose an action, execute it, and record what happened until the goal is reached or a budget runs out. Writing it out in a few lines removes the abstraction. The conversation carries the instruction and the history, the model replies with either a tool call or a final answer, and the loop exits only when there is nothing left to call. The two details that decide whether this survives contact with real traffic are the step budget and the tool result appended back into the history, because without the budget the loop never ends and without the result the model repeats the same call.
def run_agent(goal, tools, max_steps=8):
history = [{"role": "user", "content": goal}]
for step in range(max_steps):
reply = model.chat(history, tools=[t.schema for t in tools])
if not reply.tool_calls:
return reply.text, step + 1
for call in reply.tool_calls:
try:
result = tools[call.name].run(**call.args)
except Exception as exc:
result = {"error": type(exc).__name__, "detail": str(exc)}
history.append(call.as_message())
history.append({"role": "tool", "name": call.name,
"content": str(result)})
return "stopped at step budget", max_steps
Memory Systems
Rules for Tool Definitions
The model sees nothing about a tool except what you write for it, so the description is the interface. Five rules cover most failures seen in production. Name the outcome rather than the system, because search_orders that returns orders for a customer id beats a generic orders_api. State units, formats, and time zones explicitly, since a parameter documented only as "date" receives three different shapes in a single afternoon. Keep required arguments under five, because a tool needing more than that is two tools and the agent misroutes the wider one. Say when not to call it, so the model has an alternative path instead of forcing a call it should skip. Return structured errors the model can act on: a message naming what was searched invites a reformulation, while a raw stack trace invites an invented workaround.
{
"name": "search_orders",
"description": "Returns orders for one customer. Use when the task mentions an order, shipment, or refund. Do not use for catalogue questions.",
"parameters": {
"type": "object",
"properties": {
"customer_id": {
"type": "string",
"description": "Numeric account id, digits only"
},
"since_days": {
"type": "integer",
"minimum": 1,
"maximum": 365,
"default": 90
}
},
"required": ["customer_id"]
}
}
Multi-Agent Systems
Debugging a Failing Agent Run
Most agent bugs are not model failures. They are loops without budgets, tools without contracts, and memory that grows faster than the window. Before changing models, replay a trace: the full message list, every tool name with its arguments and result, the token count per step, and the exit reason. Four questions then answer nearly every incident. Did the agent have the information it needed inside the window? Did a tool return something the model could not parse? Did the loop repeat the same call twice with the same arguments? Did the step or time budget cut the task short before it finished? Persisting that trace is part of the feature rather than optional observability, because an agent you cannot replay is an agent you cannot debug.
Common Mistakes
Exposing every tool to the agent from the first step
Fix: Reveal tools by task stage so routing stays unambiguous and the prompt stays short
Treating a tool exception as the end of the run
Fix: Return a structured error the model can read, allow one reformulation, then escalate to a human
Judging an agent only on the final answer
Fix: Also score step count, tool-call accuracy, and recovery rate, because cost and reliability live there
Interview Q&A
Q1: What is the difference between an AI agent and a simple LLM call?
Answer: A simple LLM call takes input and returns output in one step. An AI agent operates in a loop: it perceives the environment, reasons about what to do, takes actions using tools, observes results, and iterates until the task is complete. Agents have memory, can use external tools, and make autonomous decisions about how to accomplish goals.
Q2: Explain the ReAct pattern and why it improves agent performance.
Answer: ReAct (Reasoning + Acting) alternates between thinking (Thought) and doing (Action). The agent first reasons about what information it needs, then uses a tool to get that information, observes the result, and repeats. This grounds the LLM in real-world data, reducing hallucinations and improving accuracy compared to pure chain-of-thought reasoning.
Q3: How do you handle the context window limitation in AI agents?
Answer: Use a tiered memory system: short-term memory (current context window), long-term memory (vector store for semantic search), and episodic memory (experience logs). Implement summarization to compress old messages, use retrieval-augmented generation to fetch relevant context, and implement sliding window strategies to manage token usage.
Q4: What are the key considerations when designing tool use for agents?
Answer: Tool definitions should have clear descriptions and parameter schemas. Implement input validation before calling tools. Handle errors gracefully with retries and fallbacks. Use structured outputs (JSON) for reliable parsing. Consider rate limiting and caching. Provide tools incrementally rather than all at once to avoid overwhelming the agent.
Q5: Compare supervisor vs pipeline multi-agent patterns.
Answer: Supervisor pattern uses a coordinator that routes tasks to specialist agents and aggregates results. Best for dynamic task decomposition. Pipeline pattern chains agents sequentially where each processes the output of the previous. Best for linear workflows like ETL. Supervisor is more flexible; pipeline is simpler to implement and debug.
Q6: How do you evaluate AI agent performance?
Answer: Measure task completion rate, number of steps taken, tool call accuracy, error recovery rate, and time to completion. Use human evaluation for quality assessment. Track hallucination rates and factual accuracy. Benchmark against established datasets (HotpotQA, WebArena). Monitor cost per task and latency metrics.
Q7: What is reflection in AI agents and why is it important?
Answer: Reflection is the agent evaluating its own output quality, detecting errors or hallucinations, and iterating to improve. It's important because LLMs can generate plausible but incorrect responses. Reflection catches these errors before presenting results to users, improving reliability and trustworthiness.
Q8: Explain the trade-offs between different memory systems.
Answer: Short-term memory is fast but limited by context window. Long-term memory (vector store) provides unlimited storage but requires retrieval overhead. Episodic memory learns from experience but needs careful curation. The optimal system combines all three: use short-term for current task, long-term for knowledge, episodic for learning from past successes/failures.
KnowledgeCheck
Key Takeaways
- An agent is a bounded loop over perceive, reason, act, and observe, and the budget on that loop is what keeps it production-safe
- Tool descriptions are the interface: outcome-focused names, explicit units, and structured errors are what the model actually navigates by
- Memory tiers solve different problems, and the window is a hard constraint that summarisation and retrieval exist to respect
- Supervisor and pipeline patterns trade flexibility for debuggability, so pick by whether the workflow is dynamic or linear
- Replayable traces turn agent failures into diagnosable ones, and step count and tool accuracy matter as much as final-answer quality