Skip to content

Learn agents

A short guide to read before (or alongside) the labs. The README has setup, the file list and rules of thumb. This page explains how the pieces fit, which decisions matter, and where to go deeper.

1. What an agent is, and why it exists

An agent is a model that works towards a goal by choosing its own steps: call a tool, read the result, decide what next, and stop when the goal is done. You give it "quote 600 bolts and nuts for Bharat Builders, and order if their credit allows", not a script of calls.

The problem it solves is branching work. A quote request can hit an unknown SKU, an out-of-stock item, a credit shortfall or a buyer who changes their mind. Coding every path as a workflow gets brittle fast. An agent handles the path at run time, from what the tools return.

Analogy: a workflow is a train on fixed tracks; an agent is a delivery driver with a map, a fuel budget and a dispatcher. The driver picks the route and reroutes around a closed road, but has to call dispatch before leaving goods with a stranger (approval), keeps a logbook (trace), and comes back when the fuel runs low (budget).

When you need one: when the steps depend on tool results and there are too many paths to code. When the steps are always the same, a workflow is cheaper, faster and easier to test. One harness serves many goals: a new capability is usually a new tool, not a new workflow.

2. The mental model

The model decides the next step. The harness around it applies guards (budgets, loop detection, approval), acts through MCP, observes results into the trace and working memory, and checks the answer before it goes out. Every run ends as done, waiting_approval or stopped with a reason.

An agent is two parts:

  • The model chooses the next step. That's all it does.
  • The harness owns everything else: budgets, loop detection, retries, the approval gate, working memory, the answer check, the trace and the final status.

Analogy: a junior sales executive (the model) and the company's process (the harness). The executive is smart and quick, but the process decides the discount limits, who signs off orders, what goes in the CRM and when to escalate. You don't make the executive more reliable by giving a longer pep talk (a bigger prompt); you do it with a good process.

The one idea to hold on to: agent quality lives in the harness, not the prompt. Most failures you'll see in the labs (an invented total, a loop, an order placed twice) are fixed by code around the model, not by better wording.

In code: a complete run, with the trace (01_agent_loop.py):

from agent import AgentState, McpTools, catalog_server, connect, print_trace, run

async with connect(catalog=catalog_server("C-102")) as hub:            # the mcp-server catalog server
    state = await run(AgentState("Quote 600 M8 bolts and nuts; does credit cover it?"), McpTools(hub))
    print(state.status, state.answer)                                   # done | stopped | waiting_approval
    print_trace(state)                                                  # every step, timing, stop reason

Pausing for a human and resuming in a new process (06_pause_and_resume.py):

state = await run(AgentState(goal), tools)        # no approver: stops at place_order
state.save()                                      # checkpoints/<id>.json, status "waiting_approval"
# ... hours later, another process ...
state = AgentState.load(run_id).decide(approved=True)
state = await run(state, tools)                   # runs the order, then the model finishes

3. The labs in three stages

Stage 1: the agent and how it thinks (01–02)

ReAct decides one step at a time and adapts for free. Plan-then-act writes the plan as JSON first, reviews it in code, executes it and compares plan with trace; it re-plans on a surprise.

Script What you see Key takeaway
01_agent_loop.py A goal becomes search, stock, quote, credit, chosen by the model; a trace and a stop reason The run is a record you can read, test and audit
02_plan_then_act.py The same goal with and without a plan; plan vs trace Plans are reviewable data; they cost a call and go stale

Stage 2: making it trustworthy (03–05)

Script What you see Key takeaway
03_self_check.py A summed total fails the check and gets fixed via create_quote; a subtraction is held for review Arithmetic belongs in tools; check amounts and IDs in code
04_memory.py "Add helmets to that quote", "where's my order?" across trimmed history Facts in typed state, captured from tool results
05_budgets_and_recovery.py Flaky reads retried, a dead service reported, a write not retried, a budget stop Retry is a property of the tool; every stop has a reason

Stage 3: humans and frameworks (06–07)

Run 1 quotes, checks credit, reaches place_order, pauses at the gate and saves a checkpoint. Later, a manager decides; run 2 loads the checkpoint in a new process, runs or declines the call, and the model finishes. The HTTP server keeps the quote alive in between.

  • 06 Pause and resume. The agent stops at place_order, saves itself to a file and exits. approve <id> in a new process loads it and carries on. The approver sees lines and totals. The HTTP server matters: a checkpoint is useless if the system forgot the quote.
  • 07 LangGraph. The same agent as a graph. Checkpoints after every node, interrupt() and Command(resume=...), and a full history come for free. Tools, approval rules, retries and checks are still your code: 07 needed the same goal check as 06, added as a graph node.

4. Decisions your team will face

Decision Start with Change when
Agent or workflow A workflow, with the model only where language is needed Steps depend on tool results and paths multiply
Reasoning style ReAct Tasks are long, costly or need sign-off: plan first, re-plan on surprises
Budgets Turns 8, tool calls 12, a time cap, repeats 2 Traces show real tasks need more; set per use case, alert on budget stops
Retries Reads only, 2 retries with backoff A write must retry: add idempotency keys on the server first
Approval Every destructive tool, as a saved pause with full details Low-value, low-risk writes earn auto-approval under a limit (₹ amount, customer tier)
Memory Typed working memory plus trimmed history Sessions get long: summarise; customers return: add long-term memory per customer
Answer checks Code checks on amounts and IDs Quality issues code can't see: add an LLM judge, measured with evals (rnr)
Framework Hand-rolled, to learn the parts Durable pauses, branching, many agents, or a shared team standard: LangGraph or similar
Model Local qwen3:8b for learning Production quality and speed: a frontier model behind the same chat() signature

5. What the labs don't cover

The labs use one laptop, fake data and file checkpoints. Production adds:

  • Durable state. Checkpoints in Postgres or Firestore, row locks so two people can't approve the same run, expiry for stale runs.
  • Re-validation on resume. Prices, stock and credit can change while a run waits; re-check before acting.
  • Observability. Traces exported to a tracing tool (OpenTelemetry, LangSmith, Langfuse): one span per model call and tool call, with cost and latency.
  • Evals. A fixed set of goals with expected tool calls and outcomes, run on every prompt or model change (rnr).
  • Security. Prompt injection through tool results (a product description that says "ignore your instructions"), least-privilege tools per agent, and per-user identity on every call (mcp-server).
  • Cost control. Tokens per run, caching, smaller models for simple steps, alerts on budget stops.

Check yourself

Answer each in a sentence or two, without looking. If one is hard, reread the section in brackets.

  1. For which kind of Acme Build task would you build a fixed workflow instead of an agent, and why? (sections 1 and 4)
  2. The agent adds up a quote total itself and gets it wrong. Would you fix this with a better prompt or with code? Why? (section 2, lab 03)
  3. Why can the harness safely retry get_stock but not place_order? (section 3, lab 05)
  4. An order waits two hours for a manager's approval, then resumes. What could have changed in that time, and why does it matter? (section 3, lab 06; section 5)
  5. A teammate wants to move to LangGraph so the team can drop its own approval rules and answer checks. Would you agree? Why? (section 3, lab 07)

Same pattern, other industries

The labs use a B2B quote-and-order flow, but the harness carries across domains. What changes is what needs approval and what must be checked.

Industry Use case What changes
E-commerce (B2C) Returns and refunds agent: check order, policy, eligibility, issue refund Auto-approve small refunds under a limit; a person approves the rest. Check refund amount against the order in code
Banking Dispute triage: gather transactions, match merchant, draft the case No money moves without a human. Every step logged for audit; PII masked in traces
Logistics Exception handling for delayed shipments: track, re-route, notify Long pauses waiting for carriers; resume on an event (webhook), not a person
Healthcare admin Prior-authorisation paperwork: collect records, fill forms, submit Strict scope of tools; every submission approved; answers checked against source records
Manufacturing Maintenance planning: read sensor alerts, check spares, raise a work order Read-only on plant systems; work orders need a supervisor; plan-first, since steps are costly

Going deeper: advanced agent topics

Topic What it solves Search for
Reflection and self-critique Better answers on open-ended tasks "Reflexion agents", "self-refine LLM"
Tree search over plans Hard tasks where the first plan is often wrong "LATS language agent tree search", "tree of thoughts"
Context engineering Long sessions that overflow or confuse the model "context engineering agents", "agent context compaction"
Long-term memory Remembering a customer across sessions "agent long-term memory", "LangGraph store", "mem0"
Durable execution Runs that last days and survive crashes "durable execution agents", "Temporal AI agents"
Agent observability Seeing cost, latency and failures per step "OpenTelemetry GenAI semantic conventions", "Langfuse tracing"
Prompt injection defence Malicious text in tool results steering the agent "indirect prompt injection", "agent tool output sanitisation"
Computer-use and browser agents Systems with no API, only a UI "computer use agent", "browser agent"
Agent evaluation Knowing if a change made it better "agent trajectory evaluation", "tau-bench"

Before moving on, try this: add an auto-approval rule to 06: orders under ₹2,000 for gold customers run without a pause, everything else waits. Write a model-free test for both paths in test_agent.py, then set GOAL in 06 to 300 bolts, and then to 1,000 bolts.

Then practise: the exercises in PRACTICE.md: re-checking before an approved call runs, auto-approval under a limit, a trajectory eval, then build a returns agent yourself.

Next topic: multi-agent workflows. An RFQ-to-quote flow with separate intake, pricing and approval agents, built on this harness.