Notes
All notes

AI Agents (AI Engg #11)

A RAG chatbot answers questions. An agent does things. Ask “Where is my order A42, and if it is late, refund the shipping” and the model must look up the order, decide whether it is late, call a refund tool, and report back. No single prompt can do that reliably, because the steps depend on what the tools return. An agent is a loop that decides the next step until the goal is met.

This chapter builds agents from the raw loop upward: the ReAct pattern, function calling, tools, multi-agent designs, and the frameworks of 2026. The theme throughout is restraint — an agent is powerful precisely because it is dangerous, and most of the engineering is bounding it.

What makes something an agent

The distinction is the control flow. A chain runs a fixed sequence you wrote. An agent chooses the sequence at runtime based on observations. That choice is the source of both capability and risk.

\[ a_t = \pi(\text{goal}, h_{<t}, \mathcal{T}), \qquad \text{stop when goal reached or budget exhausted} \]

An agent without a stopping condition and a step budget is an infinite loop with a credit card. Build both from the first line.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.1cm, minimum height=0.72cm, font=\rmfamily\small, align=center},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (t) at (0,0) {thought};
  \node[b, fill=orange!16] (ac) at (3.0,0) {action\\tool(...)};
  \node[b, fill=green!12] (o) at (3.0,-1.6) {observation};
  \node[b, fill=gray!12] (d) at (0,-1.6) {done?};
  \draw[a] (t) -- (ac); \draw[a] (ac) -- (o); \draw[a] (o) -- (d); \draw[a] (d) -- (t);
  \node[font=\rmfamily\small, text=black!60, anchor=west] at (0.5,-2.3) {repeat until done or budget hit};
\end{tikzpicture}

ReAct: reason, act, observe

ReAct (Reason + Act) is the canonical agent pattern and the mental model behind almost every framework. The model alternates:

Thought:  I need the order status. I'll call get_order.
Action:   get_order({"id": "A42"})
Observation: {"status": "shipped", "eta": "2026-06-14", "promised": "2026-06-10"}
Thought:  It is late by 4 days. The user asked for a shipping refund. Call refund_shipping.
Action:   refund_shipping({"id": "A42", "amount": 9.99})
Observation: {"ok": true}
Thought:  Done. I can answer now.
Answer:   Order A42 is late by 4 days; I refunded the $9.99 shipping.

Two things to notice. First, the model does not execute the tool; your runtime does, and feeds back the observation. Second, the trace is the product: if it fails, this transcript is how you debug it.

Tools and function calling

Modern models do ReAct natively via function calling: you describe tools as JSON-Schema functions, the model returns a structured call, your code runs it, and the result goes back as a message. No text parsing.

from openai import OpenAI
import json

client = OpenAI()

def get_order(order_id):        # the real implementation
    return {"status": "shipped", "eta": "2026-06-14", "promised": "2026-06-10"}

def refund_shipping(order_id, amount):
    return {"ok": True, "refunded": amount}

TOOLS = [
    {"type": "function", "function": {
        "name": "get_order", "description": "Get status of an order by ID.",
        "parameters": {"type": "object",
                       "properties": {"order_id": {"type": "string"}},
                       "required": ["order_id"]}}},
    {"type": "function", "function": {
        "name": "refund_shipping", "description": "Refund shipping for a late order.",
        "parameters": {"type": "object",
                       "properties": {"order_id": {"type": "string"},
                                      "amount": {"type": "number"}},
                       "required": ["order_id", "amount"]}}},
]
REGISTRY = {"get_order": get_order, "refund_shipping": refund_shipping}

def run_agent(goal, max_steps=8):
    msgs = [{"role": "user", "content": goal}]
    for step in range(max_steps):
        r = client.chat.completions.create(
            model="gpt-4o-mini", messages=msgs, tools=TOOLS, temperature=0)
        m = r.choices[0].message
        msgs.append(m)
        if not m.tool_calls:                 # no tool call => final answer
            return m.content
        for call in m.tool_calls:
            fn = REGISTRY[call.function.name]
            args = json.loads(call.function.arguments)
            result = fn(**args)
            msgs.append({"role": "tool", "tool_call_id": call.id,
                         "content": json.dumps(result)})
    return "Stopped: step budget exhausted."

print(run_agent("Where is order A42? Refund shipping if it's late."))

That loop is the whole agent. Every framework is ergonomics around it plus memory, retries, and tracing. Build it by hand once so that when a framework surprises you, you know what it is doing.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=1.7cm, minimum height=0.62cm, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=gray!10] (u) at (-3.4,0) {"Where is A42?"};
  \node[b, fill=blue!10] (m) at (-1.4,0) {LLM};
  \node[b, fill=orange!16] (f) at (0.6,0) {tool call};
  \node[b, fill=green!12] (o) at (2.6,0) {observation};
  \node[b, fill=yellow!22] (a2) at (4.4,0) {answer};
  \draw[a] (u) -- (m); \draw[a] (m) -- (f); \draw[a] (f) -- (o); \draw[a] (o) -- (m);
  \draw[a] (m) -- (a2);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0.6,-0.55) {your runtime executes; model never touches prod};
\end{tikzpicture}

Designing tools well

Tool design is the highest-leverage agent work, and it is mostly API design.

def refund_shipping(order_id, amount, idempotency_key):
    if seen(idempotency_key):
        return {"ok": True, "deduped": True}
    # ... perform refund, record idempotency_key ...
    return {"ok": True}

Multi-agent systems

When one agent’s context gets crowded (Chapter 4), split the work. The healthy patterns:

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.3cm, minimum height=0.72cm, font=\rmfamily\small, align=center},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (s) at (0,0) {supervisor};
  \node[b, fill=green!12] (w1) at (-2.6,-1.5) {worker: research};
  \node[b, fill=green!12] (w2) at (0,-1.5) {worker: data};
  \node[b, fill=green!12] (w3) at (2.6,-1.5) {worker: write};
  \draw[a] (s) -- (w1); \draw[a] (s) -- (w2); \draw[a] (s) -- (w3);
  \draw[a, dashed] (w1) -- (s); \draw[a, dashed] (w2) -- (s); \draw[a, dashed] (w3) -- (s);
  \node[font=\rmfamily\small, text=black!60, anchor=north] at (0,-2.15) {structured handoffs, isolated contexts};
\end{tikzpicture}

The anti-pattern is “agents chatting freely,” where every agent sees every token and contexts collapse. Pass typed summaries across boundaries, not transcripts.

Frameworks in 2026

You rarely hand-roll the loop in production anymore. The landscape:

Framework Shape Good for
OpenAI Agents SDK lightweight, function-calling native OpenAI-first apps
Claude Agent SDK tool-use, computer use Anthropic-first apps
LangGraph / LangChain create_agent graph orchestration branching, human-in-the-loop
LlamaIndex (ReAct / FunctionCalling agents) retrieval-centric RAG-heavy agents
Google ADK GCP-native runtime Google Cloud stacks
CrewAI role-based teams quick multi-agent prototypes

Pick based on your stack and tracing needs, not hype. What matters is that whichever you choose, you keep the safe loop semantics: step budget, tool validation, idempotency, traces.

Bounding the agent (the safety chapter preview)

def guard(state):
    if state.steps >= 8: return "stop"
    if state.last_action() == state.prev_action(): return "escalate"
    if state.cost > 0.50: return "stop"
    if state.action.is_write and not state.confirmed: return "confirm"
    return "continue"

Pitfalls

QQuestionSelf-check

What single property separates an agent from a chain? What four guardrails must exist before an agent touches production?

ASolution

The agent chooses its own next step at runtime based on observations; a chain’s steps are fixed in code. Before production: a step/timeout budget, loop detection, cost caps, and human confirmation plus idempotency for writes — plus traces throughout.

Next: MCP (AI Engg #12) — the standard plug that lets any agent reach any tool.