Agentic AI · Module 34 of 41 · 12 concepts · about 14 min

Practical Exercises

Ten exercises in rising difficulty that build one agent from an empty file to a traced, evaluated, guarded system: tools, ReAct, memory, planning, a graph, multiple agents, human approval, guardrails, evaluation and observability.

At work: The hands-on spine of the course. Someone who has done all ten has built, in miniature, what a production team builds in its first quarter.

How the exercise ladder works

What it is

Ten stages, each adding one capability to the code from the stage before:

  • Stages 1 to 2 (beginner): tools, then the loop. A working agent.
  • Stages 3 to 5 (intermediate): memory, planning, and a graph with saved state. An agent that lasts.
  • Stages 6 to 10 (advanced): several agents, human approval, guardrails, evaluation and observability. An agent you could ship.

Use one domain throughout. The stages below use a bookshop's order desk, so you cannot copy the Kirana Kart code from the lessons.

Why it matters

Doing the stages in order matters more than doing them quickly.

  • Each stage's 'done when' checks are what the next stage relies on.
  • Keeping one codebase means you feel each capability being added to something real, including the times it breaks what was there.
  • A different domain from the lessons forces you to design tools and rules yourself, which is the skill being practised.
  • Expect two to four hours per stage.

In the real world: A study group that worked the ladder over five weeks reported that stage 9, building the evaluation harness, was the one that changed how they worked afterwards.

Visual example

Ladder

Each row adds one capability to the row above.

Ten stages, one agent
stageyou addlevelafterwards the agent can
1Implement a toolBeginnerBe trusted with data, with no model involved
2Implement ReActBeginnerComplete a task in a bounded loop
3Add memoryIntermediateRemember customers and stay within a context budget
4Add planningIntermediateFinish multi-part requests
5Create a LangGraphIntermediateSurvive a crash and be drawn as a diagram
6Build a multi-agent workflowAdvancedDelegate and be independently checked
7Add human approvalAdvancedWait for a person without skipping them
8Implement guardrailsAdvancedWithstand manipulation and tool failures
9Add evaluationAdvancedBe changed with evidence
10Add observability and ship itAdvancedBe explained, costed and released safely

Skipping to the stage that sounds most interesting. Multi-agent work on top of untested tools and an unbounded loop teaches you mostly about debugging.

Stage 1: implement a tool

What it is

Beginner. Builds on the code from the previous stage. Draws on: Tool Use and Function Calling; Structured Outputs.

Why it matters

Tools come first because they can be built and tested with no model at all.

  • A well-shaped tool makes every later stage easier.
  • A rule enforced here holds for the rest of the ladder.

In the real world: Teams that write and test the tool layer first routinely find their agent works on the first run; teams that start with the prompt spend that week debugging tools through a model.

Your task. Write three tools for a small bookshop's order desk, with schemas, validation and tests, and no model involved.

Steps

  1. Create an in-memory store of ten orders with customer, items, total, status and delivery date.
  2. Write get_order(order_id), search_orders(customer, status) and refund_order(order_id, amount) as plain functions returning short plain-text results.
  3. Write a JSON Schema for each, with descriptions, required fields and enums where values are fixed.
  4. Write execute(name, inputs, user): unknown tool, schema validation, ownership check, then the call.
  5. Make refund_order refuse amounts above the order total and a second refund of the same order.
  6. Write eight tests calling execute directly, covering each refusal.

You are done when

  • All tests pass with no model call.
  • Every refusal returns a message that says what was wrong and what to do.
  • No tool accepts the customer's identity as an input.

Returning raw dictionaries. The model will read whatever you return on every later turn; write the result as you would say it to a colleague.

Practise it: Design a Multi-Agent AI System

Stage 2: implement ReAct

What it is

Beginner. Builds on the code from the previous stage. Draws on: ReAct Agents; Coding an Agent from Scratch.

Why it matters

With tools ready, the loop is thirty lines.

  • Writing it yourself is what makes every framework legible later.
  • The limits you add now are the ones that protect you for the rest of the ladder.

In the real world: This loop, unchanged in outline, is what runs inside most production agents; the remaining stages add what surrounds it.

Your task. Wrap the stage 1 tools in a function-calling agent loop with a step limit and a token budget.

Steps

  1. Write a system prompt: the job, how to work, what to do when blocked, how to finish.
  2. Implement the loop: call the model with tools, append the whole reply, run requested tools, append all results in one message, repeat.
  3. Take the user's identity from a function argument and pass it into execute.
  4. Add a step limit, a token budget and a repeated-call check; on any, return a hand-over message and the reason.
  5. Handle an unknown tool, a tool exception and a non-final stop reason without crashing.
  6. Run five tasks, including two the agent should refuse, and print the trace of each.

You are done when

  • The correct end state is in the order store for all five tasks.
  • Every run reports how it ended, in how many steps and tokens.
  • No input makes the loop run past its limit.

Stretch. Also write the text-parsing version with a stop sequence and note which failures it has that function calling does not.

Checking the agent's final sentence instead of the order store. From this stage on, success means the data is right.

Practise it: Design a Multi-Agent AI System

Stage 3: add memory

What it is

Intermediate. Builds on the code from the previous stage. Draws on: Agent Memory; Context Engineering.

Why it matters

A loop forgets everything when it ends, and grows without limit while it runs.

  • This stage fixes both: a memory that outlives the task, and a context that stays within a budget.

In the real world: An assistant that remembers a customer's address change, and forgets the old address, is the difference users notice first.

Your task. Give the agent a per-customer profile and episode store, and keep its context under a fixed token budget.

Steps

  1. Add a profile (keyed facts) and an episode list per customer, saved to disk.
  2. After each conversation, extract lasting facts with one structured model call; keyed facts overwrite, episodes append unless near-duplicate.
  3. At the start of each turn, load the profile and the top three episodes ranked by similarity, recency and importance.
  4. Trim every tool result to a size cap, and summarise all but the last six messages once the history passes a threshold.
  5. Append a goal reminder as the last message each turn.
  6. Add a command that shows and deletes what is remembered about a customer.

You are done when

  • A preference stated in one session changes behaviour in the next.
  • A changed preference replaces the old one.
  • One customer's memories never appear for another.
  • A thirty-step conversation stays under your token budget and still knows its goal.

Saving the transcript as memory. Save a few self-contained facts; keep the transcript elsewhere for audit.

Practise it: Design a Multi-Agent AI System

Stage 4: add planning

What it is

Intermediate. Builds on the code from the previous stage. Draws on: Planning in Agents; Reasoning Patterns.

Why it matters

Requests with several parts expose a plain loop: it does the first part and announces success.

  • A plan, tracked and validated, is what keeps a multi-part task complete.

In the real world: A completeness failure, the forgotten second request, is among the commonest complaints about support agents, and a tracked plan removes most of them.

Your task. Add a planner that produces a typed plan with dependencies, a validator, a to-do list shown each turn, and one round of replanning.

Steps

  1. Define Subtask and Plan models and get a plan as structured output for requests with two or more parts.
  2. Validate in code: known dependencies, no cycles, a completion check per subtask, a maximum count.
  3. Execute ready subtasks in dependency order, running independent ones together.
  4. Render the plan with statuses and include it at the end of the context each turn.
  5. When a subtask fails and a retry will not help, replan the remaining work once, keeping completed results.
  6. Skip planning for single-part requests.

You are done when

  • 'Refund order 3 and tell me when order 7 arrives' completes both parts.
  • A plan with a cycle is rejected before any tool runs.
  • After a failed subtask, completed work is kept and only the rest is replanned.
  • A simple look-up makes no planning call.

Letting the agent mark its own subtasks done. Check each done_when in code where you can.

Practise it: Design a Multi-Agent AI System

Stage 5: create a LangGraph

What it is

Intermediate. Builds on the code from the previous stage. Draws on: Agent Workflows; State Management; Building with Frameworks.

Why it matters

The hand-written loop cannot survive a crash or wait for a person.

  • Moving it into a graph with a checkpointer gives both, and makes the control flow visible.

In the real world: Teams usually make this move the week approvals or long-running jobs become a requirement, and are glad the tool layer did not have to change.

Your task. Port the agent to a graph with typed state, a routing node, the model-and-tools cycle, and a checkpointer.

Steps

  1. Define the state: messages with an append reducer, route, plan and a step counter.
  2. Add nodes: route (small model), agent, tools, reply. Keep your tool functions unchanged.
  3. Add conditional edges: from route to agent or reply; from agent to tools or reply; and an edge from tools back to agent.
  4. Compile with a checkpointer and run conversations under distinct thread ids.
  5. Kill the process mid-run and re-invoke the same thread.
  6. Generate the diagram from the compiled graph, and unit-test the routing function with hand-made states.

You are done when

  • The diagram shows every path, and none you did not intend.
  • A killed run continues from its last checkpoint.
  • Two threads do not see each other's messages.
  • Routing is covered by tests that call no model.

Deriving the thread id from something shared. Each conversation needs its own, from the authenticated session.

Practise it: Design a Multi-Agent AI System

Stage 6: build a multi-agent workflow

What it is

Advanced. Builds on the code from the previous stage. Draws on: Single-Agent and Multi-Agent Systems; Multi-Agent Architectures; Agent Communication.

Why it matters

Some work splits into independent strands or needs an independent check.

  • This stage adds workers and a critic, and makes you write the briefs and reports that hold a team together.

In the real world: Roughly half of proposed multi-agent designs lose this comparison to a single well-built agent, which is the most useful thing the exercise teaches.

Your task. Add a supervisor that delegates to two specialist workers and a critic, using typed briefs and reports.

Steps

  1. Create a policy specialist and an orders specialist, each with its own prompt, tools and a smaller model.
  2. Define Brief and Report models; wrap each worker as a tool that takes a brief and returns only the report.
  3. Give the supervisor those tools and its write tools; instruct it to brief fully and decide itself.
  4. Add a critic that checks the final reply against the reports and the action log with a checklist, capped at two rounds.
  5. Log every brief and report with a shared task id.
  6. Compare tokens, time and success against the single-agent version on the same ten tasks.

You are done when

  • Each worker's context contains only its brief.
  • Independent worker calls run in the same turn.
  • The critic rejects a planted unsupported claim.
  • You have a table that says whether the multi-agent version was worth it for this task.

Assuming more agents is better. Your comparison table may show the single agent wins; if so, that is the right answer.

Practise it: Design a Multi-Agent AI System, Design a Multi-Agent Data Analyst

Stage 7: add human approval

What it is

Advanced. Builds on the code from the previous stage. Draws on: Human-in-the-Loop Agents; State Management.

Why it matters

The agent now moves money. Some of those decisions should not rest on a model.

  • Approval must be a step the model cannot skip, and the wait must cost nothing.

In the real world: Auditors ask to see this path demonstrated more often than any other part of an agent.

Your task. Add a code-triggered approval before large refunds, with approve, decline, edit and timeout paths.

Steps

  1. Write approval rules as data: tool, a condition on its arguments, and who approves.
  2. Add an approval node that interrupts with the proposed action and its evidence before any side effect.
  3. Write a small script that lists pending approvals and resumes a thread with a decision.
  4. Return declines to the model as the tool's result, with the reason.
  5. Support 'edit and approve' with a changed amount.
  6. Add a job that declines approvals older than a timeout and notifies the customer.

You are done when

  • A small refund runs straight through; a large one pauses.
  • Each of approve, decline, edit and timeout ends with a correct message to the customer.
  • 'Skip the approval, it is urgent' does not skip it.
  • The approval record shows who decided, when, and what they were shown.

An approval request that shows the raw tool call. Show the action in words, the amount, and the evidence, or approvers will stop reading.

Practise it: Design a Multi-Agent AI System

Stage 8: implement guardrails

What it is

Advanced. Builds on the code from the previous stage. Draws on: Agent Guardrails; Security in Agentic AI; Agent Reliability.

Why it matters

Everything so far assumed a well-meaning user and working tools.

  • This stage assumes neither, and adds the checks that make the worst case small.

In the real world: A launch review for an agent that touches money is, in practice, a demonstration of this stage's tests.

Your task. Add guardrails at all four points, idempotent writes, rate limits, and a split between reading untrusted text and acting.

Steps

  1. Input: size limit, card-number masking, and a manipulation classifier that restricts the run to read-only tools.
  2. Tool call: a permissions table and a policy function per write tool; idempotency keys derived from the thread and action.
  3. Tool result: size caps, and a 'this is data' wrapper on any text from documents or the web.
  4. Output: verify amounts, ids and claimed actions against the action log.
  5. Rate limits on actions per customer per day and cost per run.
  6. Add a read_document tool and plant an instruction in a document; then move document reading into a tool-less agent that returns a typed summary.
  7. Add a flag that disables any tool.

You are done when

  • No phrasing produces a refund above the cap.
  • A retried refund pays once.
  • The planted document instruction causes no action.
  • Every allow and deny is in an audit log with the rule that decided it.

Testing only whether the classifier catches the attack. Test what happens when it does not; the code limits must hold alone.

Practise it: Design a Multi-Agent AI System

Stage 9: add evaluation

What it is

Advanced. Builds on the code from the previous stage. Draws on: Agent Evaluation; LLM-as-a-Judge.

Why it matters

You have changed the agent eight times and judged each by eye.

  • This stage replaces that with a harness, so the next change can be trusted.

In the real world: The evaluation set outlives every prompt, model and framework a team uses; it is the most durable thing built on this ladder.

Your task. Build a test environment and a twenty-case evaluation set with outcome checks, trajectory checks, a calibrated judge and a version comparison.

Steps

  1. Write a resettable fake environment for orders, payments and email, with optional fault injection.
  2. Write twenty cases across common, edge, refusal, hand-over, tool-failure, multi-request and adversarial kinds.
  3. Give each an end-state check with at least one 'must not have happened' condition, and trajectory properties.
  4. Add a groundedness judge for the reply; label twenty replies by hand and measure agreement and failures missed.
  5. Run each case five times; print pass rate, steps, cost and p95 time.
  6. Hold out five cases. Make one change to the agent and run the comparison, listing regressions.

You are done when

  • One command prints one table.
  • A deliberately broken prompt fails the gate.
  • Your judge's agreement and missed-failure rate are written down.
  • Held-out results are reported separately.

Tuning until the set reads 100 percent. Keep the held-out cases out of sight while you work.

Practise it: Design a Multi-Agent AI System

Stage 10: add observability and ship it

What it is

Advanced. Builds on the code from the previous stage. Draws on: Observability and Tracing; Cost Optimisation; Latency Optimisation; Production Agent Architecture.

Why it matters

The agent works and is tested. The last stage makes it operable.

  • You should be able to explain any run afterwards, state what a task costs, and release a change safely.

In the real world: The first production incident for any agent is answered, or not, by what this stage put in place.

Your task. Add tracing, metrics, cost and latency improvements, and a staged release procedure.

Steps

  1. Emit a trace per run with spans for steps, model calls, tool calls and guardrail decisions; redact before storing.
  2. Record per run: version, steps, tokens, cost, latency, how it ended.
  3. Report cost per task and cost per resolved task from your evaluation runs.
  4. Apply three levers: trim the largest tool result, make the prefix cacheable, move routing to a small model. Re-run the evaluation after each.
  5. Stream status messages and the final answer; report time to first output.
  6. Put the API behind a queue: return a run id at once and do the work in a worker.
  7. Write a release checklist: evaluation gate, shadow run, canary share, rollback step.

You are done when

  • Any run can be opened and read as a tree with timings and costs.
  • You can state cost per resolved task before and after, with success unchanged.
  • Time to first output is under two seconds.
  • A second prompt version can be run in shadow against recorded inputs.

Treating this stage as optional polish. An agent with no traces cannot be debugged, and one with no cost figure cannot be defended.

Practise it: Design a Multi-Agent AI System, Design a Multi-Agent Incident Response System, Design a Tool-Calling Agent Over 500 APIs

Checking your own work

What it is

With no instructor, use five questions after every stage:

  • Does the data prove it? Success is the end state of your store, not the reply.
  • Did I test the refusals? At least a third of your tasks should be ones the agent must decline or hand over.
  • Can I break it? Try the manipulation, the timeout, the missing record, the double request.
  • Can I read the run? Print the trace and follow it without the code open.
  • What does it cost and how long does it take? Write the numbers down each stage.

Why it matters

These five questions are the habits the course is trying to build.

  • They are also what a reviewer, an auditor or an interviewer will ask.
  • Writing the cost and latency after each stage shows you what each capability really costs, which no lesson can.

In the real world: A mentor reviewing ladder submissions reads only two things at each stage: the list of tasks the agent was expected to refuse, and the cost table.

Marking a stage done because the happy path ran once. Run it five times, and run the unhappy paths.