Agents and Tool Use

Session 6 - 3 hours - Lecture + live-coding lab

Lambert Fatoux

Agents and Tool Use

Session 6 - 3 hours

From one LLM call to a model that decides what to do next — the trailer of your 30-hour agents course

Learning outcomes (today)

  1. Tell a workflow from an agent, and choose the simplest one that works
  2. Implement the ReAct loop: thought → action → observation, with tool dispatch
  3. Add planning and explicit termination conditions (final-answer tool, max iterations, budget)
  4. Place today’s tools on a map: frameworks, coding agents, MCP, n8n, ComfyUI…
  5. Name the limits of agents and protect data privacy with open-source alternatives

Produced: a research-assistant agent evaluated on 15 questions: success rate, iterations, hallucinated-tool-call rate

Warm-up quiz 1/3: hybrid retrieval

Your RAG over the ECB archive never finds the chunks about TLTRO or MREL, although they are in the corpus. What is the most likely fix?

  • A. Use a bigger embedding model
  • B. Add BM25 and fuse it with the dense results (RRF)
  • C. Make the chunks bigger
  • D. Raise the temperature of the generator

✅ Answer: B

Dense embeddings capture meaning but blur rare acronyms and codes; BM25 matches the exact tokens. Hybrid retrieval fuses both rankings with RRF, which only needs ranks, so the two kinds of scores never have to be comparable.

Warm-up quiz 2/3: comparing vectors

You normalise every embedding to length 1 at indexing time. Which ranking changes?

  • A. The cosine ranking
  • B. The dot-product ranking
  • C. The L2-distance ranking
  • D. None: all three give the same ranking

✅ Answer: D

With unit vectors, cosine = dot product and \(\lVert u - v\rVert^2 = 2 - 2\cos(u,v)\), so the three metrics rank the chunks in the same order. Normalise once, then use the cheapest one: a dot product (a single matrix product over the whole index).

Warm-up quiz 3/3: building the prompt

The reranker returns 20 chunks for a question. What do you put in the prompt?

  • A. All 20, in retrieval order: more context is always better
  • B. The 5 best, the best first and the second best last, as numbered sources
  • C. Only the single best chunk
  • D. All 20, shuffled to avoid position bias

✅ Answer: B

Models use the start and end of the context best (“lost in the middle”). Five good chunks beat twenty mediocre ones: less noise, fewer tokens. Numbered sources let the model cite [n], or abstain when the answer is not there.

Recap: where Session 5 left us

  • RAG: retrieve evidence, answer from it, cite it
  • Hybrid retrieval + reranking; Recall@5, faithfulness, cost per answer
  • A retrieved document can carry a prompt injection (the leaked memo)

Today’s question: what if the model could decide to search again, compute, check, and only then answer?

RAG: question → retrieve → answer. You fix the path.

Agent: question → think → search → read → compute → … → final answer. The model picks the path.

Your Session 5 retriever becomes the agent’s first tool.

Why Session 6 exists (practice)

“Agentic” is the most used, and most abused, word in AI right now

  • “Can an agent handle our refunds end to end?” → tools, permissions, termination
  • “Why did the agent loop 40 times and cost €12?” → max iterations, budgets
  • “It called a tool that doesn’t exist.” → hallucinated tool calls
  • “Can we use it on client data?” → privacy, self-hosting, open-weight models
  • “Should we buy n8n, build with LangGraph, or just prompt better?” → the landscape

Today = the vocabulary, the loop and the judgement. Course on agentic workflow will give you a concrete usage of them

What is an agent?

A working definition

An agent is an LLM that runs in a loop, choosing actions (tool calls) based on observations, until it decides the goal is reached.

Ingredients

  • A goal (task, question)
  • A model that reasons and decides
  • Tools to act on the world
  • Memory: the conversation so far (+ long-term stores)
  • A stop condition

Not an agent

  • A single LLM call (Sessions 1–4)
  • A fixed RAG pipeline (Session 5)
  • A chain of LLM calls whose order you wrote

→ those are workflows, often the better choice

The autonomy ladder

Workflows first

Start with the simplest pattern that works: add agentic complexity only when it measurably helps.

A short history of agents

2022 → 2024: from papers to products

The early days

  • ReAct (2022) interleaved reasoning traces and actions: the loop almost every agent still runs
  • Toolformer (2023) taught a model to decide by itself when to call a calculator, a search engine or a calendar
  • AutoGPT (March 2023) passed 100,000 GitHub stars within weeks: give it a goal, watch it loop… and often burn your API credits going in circles

🎲 first projects

  • ChaosGPT (April 2023): someone gave AutoGPT the goal “destroy humanity”. It mostly searched the web for nuclear weapons and tweeted. Agents are only as dangerous as the tools you give them
  • Generative Agents (2023): 25 simulated characters in a Sims-like town; one was told to throw a Valentine’s Day party, and the others spread invitations and showed up on their own

2025 → 2026: agents go mainstream

Your first agent

smolagents logo

from smolagents import ToolCallingAgent, tool

@tool
def class_list() -> list[str]:
    """All students enrolled in the course."""
    return read_csv("students.csv")

@tool
def qr_scans_today() -> list[str]:
    """Students who scanned today's QR code."""
    return attendance_app.scans(today)

@tool
def send_email(to: str, text: str) -> str:
    """Email a message to a student."""
    return mailbox.send(to, text)

agent = ToolCallingAgent(model=llm,       # any LLM
    tools=[class_list, qr_scans_today, send_email])
agent.run("Who has not scanned the QR code today? "
          "Send them a friendly reminder.")
  1. Tools: plain functions; the docstring tells the model what each one does
  2. Agent: a model + its tools
  3. Task: one sentence, no steps given

The agent decides alone: read both lists, compare them, email each missing student.

How does it decide? That loop is the rest of this session.

The ReAct loop

Thought → Action → Observation

A ReAct trace

Question: By how many percentage points did the ECB deposit rate rise between July 2022 and its 2023 peak?
Thought 1: I need the deposit rate after the July 2022 decision.
Action 1: search("ECB deposit facility rate July 2022")
Observation 1: "...the deposit facility rate rises to 0.00%..."
Thought 2: Now the 2023 peak.
Action 2: search("ECB deposit facility rate peak 2023")
Observation 2: "...September 2023... the deposit rate reaches 4.00%..."
Thought 3: 4.00 − 0.00 = 4.00 points. Let me compute to be safe.
Action 3: calculator("4.00 - 0.00")
Observation 3: 4.0
Action 4: final_answer("4 points: 0.00% (Jul 2022) → 4.00% (Sep 2023)", sources=["pr-2022-07-21", "pr-2023-09-14"])
  • Each Thought is generated text; each Action is a structured tool call; each Observation is appended to the context; final_answer ends the loop
  • The context grows at every step: cost and latency grow too

Live demo: an agent run, step by step

Today’s lab agent, live, on a local llama3.1:8b served by Ollama:

How many days passed between the ECB’s first rate hike in July 2022 and its first rate cut in June 2024?

Watch for:

  1. Two searches, one per date
  2. A call to days_between instead of mental arithmetic
  3. The stop on final_answer, with its sources, and the context bar growing at each step

Tools: the agent’s hands

A tool = name + description + JSON schema of arguments (Session 4: tool calling is structured output).

  • Read-only: web search, RAG retriever, SQL SELECT, file read → low risk
  • Compute: calculator, Python sandbox, code execution → medium risk, sandbox it
  • Write / act: send email, create ticket, git push, payment → high risk: human approval
  • Control: final_answer, ask_human, handoff_to_agent → steer the loop itself

Tool design matters as much as prompts: clear names, precise descriptions, few well-scoped tools, errors that tell the model how to recover.

Tool dispatch: the loop in code

TOOLS = [SEARCH_TOOL, CALCULATOR_TOOL, FINAL_ANSWER_TOOL]  # JSON schemas

def run_agent(question, max_iterations=8):
    messages = [{"role": "user", "content": question}]
    for step in range(1, max_iterations + 1):
        response = client.messages.create(
            model="claude-opus-5-5", max_tokens=4096,
            system=SYSTEM, tools=TOOLS, messages=messages)
        messages.append(
            {"role": "assistant", "content": response.content})
        calls = [b for b in response.content if b.type == "tool_use"]
        final = next((c for c in calls if c.name == "final_answer"), None)
        if final:                                     # explicit stop
            return {"status": "done", "steps": step, "answer": final.input}
        results = [dispatch(c) for c in calls]        # next slide
        messages.append({"role": "user", "content": results
                         or "Call a tool or final_answer."})
    return {"status": "max_iterations", "steps": max_iterations,
            "answer": None}

Tool dispatch: one tool call

REGISTRY = {"search": search, "calculator": calculator}  # name → function

def dispatch(call):
    if call.name not in REGISTRY:                    # hallucinated tool
        output = f"Unknown tool '{call.name}'. Available: {list(REGISTRY)}"
        error = True
    else:
        try:
            output, error = REGISTRY[call.name](**call.input), False
        except Exception as exc:                     # bad args, API down…
            output, error = f"Tool error: {exc}", True
    return {"type": "tool_result", "tool_use_id": call.id,
            "content": str(output), "is_error": error}
  • Unknown tool or tool error: never crash, send the problem back as an observation (is_error)
  • The model reads the error at its next step and can recover: another tool, fixed arguments, or final_answer

Two ways to call a tool

Native tool use (the code above)

{"type": "tool_use",
 "name": "search",
 "input": {"query": "ECB rate July 2022"}}
  • The API returns a structured block, checked against your JSON schema
  • Frontier models, recent open models (Llama 3.1, Qwen 2.5)

Text ReAct (today’s lab)

Thought: I need the July 2022 rate.
Action: search[ECB rate July 2022]
  • The model writes plain text; your regex turns it into a call
  • Works with any model, but the model can write anything

Same loop either way. With text ReAct and a small model, malformed and invented calls are frequent: that is the hallucinated-tool-call rate you will measure in the lab.

Dispatch rules that save you

Before the call →

Validate the arguments Prevents: malformed calls

Schema first (strict: true), then your business rules

get_rate("last summer") → rejected, never run

While it runs →

Timeouts and retries Prevents: waiting forever on an API

Bounded retries, then the failure becomes an observation

Parallel calls Prevents: one turn per lookup

Independent calls run concurrently, results returned together

After: back to the model

Errors are observations Prevents: a crashed run

Return it with a hint; the model fixes it next step

is_error: true, “date must be YYYY-MM-DD”

Log every step Prevents: runs you cannot audit

Thought, tool, arguments, output, tokens, latency

Hallucinated tool calls

They come in three flavours:

  1. A tool that does not exist: common with local models parsing free text
  2. A real tool with invented or malformed arguments: caught by schema validation
  3. A tool result the model pretends to have received, without calling the tool: caught by checking the trace

Count them in your evaluation:

hallucinated-tool-call rate = invalid calls ÷ all calls

Planning

Task: “How did the ECB’s tone on inflation change between its first hike (July 2022) and its first cut (June 2024)?”

The plan the agent writes first

done 1. Find the July 2022 press conference

failed 2. Find the June 2024 press conference: no transcript in the index

re-plan 2′. Use the 6 June 2024 monetary policy statement instead

next 3. Compare the wording on inflation, answer with sources

  • ReAct: no plan, one step at a time → short tasks
  • Plan-and-execute: this list, kept in the agent’s state and updated on failure → longer tasks; coding agents show you exactly this to-do list
  • Orchestrator + sub-agents: steps 1 and 2 go to two workers with fresh contexts, in parallel → research, large codebases

Reasoning models (Session 4) already plan inside their thinking tokens; a written plan adds what they lack: progress that survives 50 steps.

Termination conditions

An agent without a stop condition is a cost leak.

Goal reached model calls final_answer done

Step limit max_iterations, e.g. 8 max_iterations

Budget tokens, €, seconds budget_exceeded

Repeated call same tool, same arguments → warn, then stop stuck

Needs a human ask_human tool, low confidence escalated

Always report why it stopped: max_iterations is a failure, not an answer

Memory and context engineering

The context window is the agent’s short-term memory. Same agent, step 30:

Left to grow
30 raw tool results
110k / 128k
the key fact from step 4 is lost in the middle; every call pays for all of it
Engineered
28k / 128k
instructions + taskthoughts + actionstool resultssummary of old resultsillustrative sizes

Compact
summarise or clear old tool results

Delegate
sub-agents return conclusions only

Order
stable instructions first → caching (Session 4)

Remember
notes file, RAG over past runs, fetched like a tool

Most “the agent got dumber after 30 steps” bugs are context bugs, not model bugs.

The agentic ecosystem

A map of the agentic world

Model Context Protocol (MCP)

  • An MCP server is a small program that plugs tools and data into any AI app
  • Plugged in, it announces what it can do: a list of tools with their JSON schemas
  • Write it once → it works in every MCP host, like a USB device in any laptop

What is an MCP server?

  • Open standard released by Anthropic (Nov. 2024), adopted by OpenAI, Google, Microsoft; governed by the Linux Foundation’s Agentic AI Foundation since Dec. 2025
  • Hundreds of servers: GitHub, Slack, Postgres, filesystems, browsers… (official list)
  • ⚠️ An MCP server is code with your permissions: install only trusted ones, and remember the lethal trifecta (Session 4)

MCP: where does the server run?

  • Same JSON-RPC messages either way: only the transport changes
  • Local: check the code you install. Remote: check the data and scopes you hand over

Code frameworks: build your own agent

  • LangGraph: agents as state graphs, checkpoints, human-in-the-loop → controllable production agents
  • OpenAI Agents SDK: agents, handoffs, guardrails, tracing → multi-agent apps, any model via adapters
  • Claude Agent SDK: the Claude Code harness as a library (files, shell, MCP, sub-agents) → agents that work on files and code
  • smolagents: minimal; code agents write Python instead of JSON calls → learning, open-weight models
  • CrewAI: role-based “crews” of agents → quick multi-agent prototypes
  • AutoGen: conversations between agents → research, multi-agent patterns
  • LlamaIndex: agents over your data → RAG-heavy agents

Today’s lab writes the loop by hand (≈ 60 lines): once you understand it, every framework is just a nicer wrapper.

Agent frameworks: who’s who

LangGraph logo

LangGraph graphs & state

LlamaIndex logo

LlamaIndex graphs & state

CrewAI logo

CrewAI multi-agent teams

AutoGen logo

AutoGen multi-agent teams

Agno logo

Agno multi-agent teams

smolagents logo

smolagents minimal ReAct loop

PydanticAI logo

PydanticAI minimal ReAct loop

OpenAI Agents SDK logo

OpenAI Agents SDK vendor SDK

Claude Agent SDK logo

Claude Agent SDK vendor SDK

Google ADK logo

Google ADK vendor SDK

They all run the same loop you write by hand today (think → call a tool → observe → repeat); they differ in how much control, structure and lock-in they add.

Your loop in LangGraph

The lab’s hand-written loop, piece by piece, in LangGraph’s vocabulary:

  • llm.next_step(...) → an LLM node
  • your dispatch (TOOLS[name](arg), errors as observations) → a tools node
  • your stop rule (“tool call or final answer?”) → a conditional edge
  • transcript → the graph’s state (the message list)
  • max_iterations → the recursion limit

What the framework adds on top: checkpoints (resume a run), human approval before a node, streaming, tracing.

graph.add_conditional_edges("llm", route, ["tools", END])   # the stop rule
graph.add_edge("tools", "llm")                              # the loop

Low-code automation: n8n and friends

n8n (Berlin): visual workflows with 400+ integrations and AI agent nodes, a model + tools + memory, wired by drag-and-drop. Self-hostable (source-available “fair-code” licence).

[Gmail trigger] → [AI Agent: classify & draft reply] → [IF urgent]
                    ├ tool: CRM lookup                   ├→ [Slack alert]
                    └ tool: knowledge base (RAG)         └→ [Gmail: save draft]

💼 Business corner

n8n became one of Europe’s fastest-growing AI startups and reached a multi-billion-dollar valuation in 2025: companies want automation their ops teams can build and their IT teams can host.

ComfyUI: agents’ cousin for images

ComfyUI is an open-source node graph for image, video and audio generation pipelines.

[Load checkpoint] → [CLIP text encode: "ECB tower at sunset, watercolor"]
      ↑ [LoRA loader] (Session 3!)     → [KSampler] → [VAE decode] → [Save]
  • Same idea as n8n, applied to diffusion models: every step is a visible, swappable node
  • Workflows are shared as JSON files; thousands of community nodes
  • Can be driven by an agent through its API (or an MCP server) to generate visuals on demand

Session 7 (diffusion) explains what happens inside these nodes: text encoders, samplers, guidance, VAEs.

Agents at work in 2026

What changed since 2025

1 Models trained for tools

Post-training now includes long tool-use runs and RL (Session 3)

before: prompted to use tools → now: trained to use tools

2 Coding agents took off

Tests give feedback, sandboxes contain mistakes: clear ROI

Claude Code Codex Copilot agent Cursor

3 Shared standards

MCP joined the Linux Foundation in Dec. 2025

MCP: tools A2A: agent to agent AGENTS.md: instructions

4 Open weights caught up

Agent loops on your own servers

gpt-oss Qwen Mistral DeepSeek

💼 Business corner

×2 every ~7 months: the length of tasks agents finish alone (50% success, METR). Plan around a moving target.

Real uses (1/2): agents that work on their own

Coding agents Claude Code, Codex, Copilot agent, open-source OpenHands

Task: “fix issue #142” → a pull request

Tools: read and edit files, terminal, tests, git

Autonomy: runs alone in a sandbox for minutes to hours; a human reviews the pull request

Works because tests verify and git undoes. Fails on vague tickets and code without tests.

Deep research ChatGPT, Gemini, Claude, Perplexity

Task: “how has euro-area bank lending changed since 2022?” → a cited report

Tools: web search, read pages and PDFs, write

Autonomy: 5 to 30 minutes alone, read-only; a human reads the report

Works because nothing is changed in the world. Fails on weak sources quoted with confidence.

Browser and computer use ChatGPT agent, Claude computer use, open-source browser-use

Task: fill a supplier form on a website that has no API

Tools: screenshot, click, type, scroll

Autonomy: step by step, with approval before submitting or paying

Works when no API exists. Fails on changing pages; still many times slower than a person.

Live demo: a real coding agent

Claude Code: an agent in your terminal that works on a real codebase.

  • Reads and searches your files
  • Runs commands and tests
  • Edits code, then checks its own work
  • Asks before risky actions

Live: fix a bug in a tiny ECB repository until the tests pass.

Real uses (2/2): agents with a human in the loop

Customer support Sierra, Decagon, Intercom Fin

Task: “where is my refund?” → answer, or refund within a limit

Tools: order lookup, refund up to a set amount, hand off to a human

Autonomy: narrow and policy-bound; every unusual case goes to a person

Works because tools and policies are narrow. Fails on cost-only goals: Klarna rehired humans in 2025.

Back-office documents Invoice, claims and KYC processing

Task: invoice PDF → checked ERP entry, matched to the purchase order

Tools: extraction with structured outputs (Session 4), ERP lookup, validation rules

Autonomy: high volume; exceptions go to an accountant

Works because every field is validated. Fails on unusual formats that skip the checks.

Data analysis ChatGPT and Claude analysis, BI copilots

Task: “why did sales drop in Q3?” → SQL, a chart, an explanation

Tools: SQL on read-only data, a Python sandbox, charts

Autonomy: explores alone; an analyst checks the conclusion

Works because the code can be rerun and checked. Fails on a wrong join that gives a plausible number.

💼 Business corner

Sierra (customer-service agents) was valued at $10B in Sept. 2025. Klarna said in 2024 that its assistant did the work of ~700 agents, then in 2025 its CEO said cost had weighed too much and quality had suffered. The winning pattern is agent + human, not agent instead of human.

Measuring an agent

Example scorecard: one agent, 15 ECB questions (illustrative)

73%
Success rate
11 / 15 correct answers
4.2
Iterations per task
mean; max 8
5%
Hallucinated tool calls
3 invalid / 62 calls
18 s
Per task
seconds and €, not per call
Why it stopped
done 1221
max_iterations 2, stuck 1
done is not correct: 12 runs ended with an answer, 11 were right
Run it 3 timesrun 1: 11/15run 2: 10/15run 3: 12/15→ report the mean, 73% (Session 8)

Public benchmarks: SWE-bench GAIA τ-bench WebArena OSWorld

Limits of agents

Live demo: how a small model fails

Same agent, a much smaller model: llama3.2:1b (1 billion parameters instead of 8). Three questions:

  1. A two-hop question with only 2 steps allowed: what does the user get?
  2. “What is the latest deposit facility rate in the archive?”: who answers, the archive or the planted memo-x?
  3. “Search Google for today’s ECB rate.”: there is no Google tool. What does the model do?

Name each failure before the next slide does.

Errors compound

A 95%-reliable step sounds great, until the task needs 20 of them. Fewer, better steps beat long autonomous chains.

What goes wrong

  • Loops and drift: repeating the same search, forgetting the goal after 30 steps
  • Hallucinated tools, arguments or results (see above)
  • Cost and latency: 10–50 LLM calls per task; a “simple question” can cost euros and minutes
  • Prompt injection through every web page, email and document the agent reads (Session 4)
  • Over-confidence: a fluent final answer hides a failed tool call three steps earlier
  • Evaluation is hard: many valid paths, non-deterministic runs

True stories (1/3): an agent runs a shop

Project Vend (Anthropic, 2025): Claude ran the office shop for a month, with web search, email to wholesalers, Slack with customers and control of prices.

What went wrong

  • Sold below cost and handed out discount codes to anyone who asked
  • Stocked tungsten cubes after a joke request, sold them at a loss
  • Invented a payment account; on April 1, claimed it would deliver in person “wearing a blue blazer”

Fix: tools that know the numbers (costs, a CRM) and instructions that reward profit, not pleasing the customer

True stories (2/3): an agent deletes production

Replit (July 2025): SaaStr’s founder built an app with Replit’s coding agent, then declared a code freeze.

What went wrong

  • The agent saw empty query results, “panicked” and ran npm run db:push without asking
  • It wiped the production database: 1,206 executives, 1,196+ companies
  • It then said a rollback would not work; the data was restored anyway

Fix (Replit, two days later): automatic dev/prod database separation, a planning-only mode, one-click restore

A freeze written in a prompt is not a permission system: no production credentials in the agent, destructive commands behind human approval.

True stories (3/3): 40% of projects cancelled

What Gartner predicts (June 2025): over 40% of agentic AI projects cancelled by the end of 2027, for escalating costs, unclear business value or weak risk controls

  • “Agent washing”: chatbots and RPA tools rebranded as agents; about 130 of the thousands of “agentic” vendors are real
  • Many use cases sold as agentic do not need an agent at all

Fix: start from a workflow (“Workflows first”), measure it (the scorecard), add autonomy only where it pays

Security: least privilege, always

Lethal trifecta (Session 4): any two are fine; with all three, one injected page can send your data out

Sandbox

Code and browsers run in a container or VM, with no production credentials

Read-only by default

Send, pay, delete, deploy → human approval. One approval would have saved Replit’s database

Scoped credentials

One short-lived token per tool; no “admin” API key in the agent

Audit logs

Every tool call, with its arguments: you will need them

Treat an agent like a new intern with superpowers: no production keys on day one.

Data privacy

What leaves your company?

With a cloud API, everything the agent reads is sent to the provider: the prompt, every tool result, the files it opens, the emails it summarises.

  • Questions to ask a provider: data retention period? used for training? processing region (EU)? sub-processors? zero-data-retention option? signed DPA?
  • GDPR: personal data needs a legal basis, minimisation and a processor agreement; the EU AI Act adds transparency duties for AI systems
  • Agents multiply exposure: one RAG answer sends 5 chunks; one agent task can send 50 documents

Privacy story: Samsung and ChatGPT

What went wrong (March 2023): weeks after allowing ChatGPT, its chip division found three leaks

  • source code of a faulty chip database, pasted in to get a fix
  • code for spotting defective equipment
  • an internal meeting, pasted in to write the minutes

All of it ended up on OpenAI’s servers

Fix

  • A 1,024-byte prompt cap, then (2 May 2023) a ban on company devices
  • Today: enterprise plans (no training on your data), a usage policy, self-hosted models for secrets

With an agent, nobody pastes: the tools read the files for you

Self-hosted, open-source alternatives

An open-source agent stack

UI & automation Jupyter notebook Open WebUI n8n Langflow Dify

Agent loop your 60 lines LangGraph smolagents goose OpenHands

Tools ECB search (Session 5) calculator local MCP servers

Open-weight models Llama 3.1 8B gpt-oss Qwen Mistral DeepSeek

Your hardware laptop on-prem GPUs EU cloud

outlined = today’s lab, every layer on your laptop

You own GPUs, updates, security patches and evaluation. Open weights are great at routine tool use, weaker on long, hard tasks Common split: sensitive data → self-hosted model; public or anonymised data → frontier API

Practice session

Lab overview

Build the agent from the demos, then measure how reliable it is.

  1. Model: llama3.1:8b and llama3.2:1b with Ollama, pulled before class (no API key)
  2. Tools: search (BM25 over the ECB archive), calculator, days_between, final_answer
  3. Loop: text ReAct, Action: tool[input] parsed by your regex, max_iterations = 8
  4. Evaluation: 15 questions of four kinds: single-hop, multi-hop, unanswerable, traps (5 in class with QUICK = True)

Done means: the results table for both models, plus 3 failed traces explained, not “the agent seemed smart”.

Lab tasks

  1. Tools: write a safe calculator (no eval: parse with ast)
  2. Parsing: write parse_action, which turns Action: search[ECB rate] into a call, or returns None
  3. Loop: complete run_agent: dispatch, invalid calls, max_iterations, and stuck as soon as a call repeats
  4. Watch: run trace_board on a two-hop question, then read three failed traces with show_trace
  5. Evaluate: write is_correct, run the questions with both models, complete the summary

Bonus: break it (the three experiments from the demo), and the same agent in LangGraph.

Lab: report your results

Fill in one row per model:

Model Success rate Mean iterations Hallucinated-tool-call rate Stopped by max_iterations or stuck Seconds / task
llama3.2:1b
llama3.1:8b

Then explain 3 failed traces (which step went wrong, and why) and name the one improvement you would make first. What does 8 times more parameters buy you?

Common pitfalls

Symptom Likely cause
Agent never stops No final_answer tool, or no max_iterations
Answers in free text, loop continues System prompt does not require the final-answer tool
Calls search with the whole question 10 times No progress check; poor tool description
“Unknown tool: web_search” Tool names in the prompt ≠ registry; local model parsing free text
Crashes on a tool error Exceptions not returned as observations
Great on 3 demo questions No 15-question evaluation, no repeated runs

How today’s concepts show up next

Later topic Hook from Session 6
Diffusion (S7) ComfyUI node graphs; agents that call image models as tools
Evaluation (S8) Success rate, LLM-as-judge on traces, cost/latency Pareto
Project RAG + multi-step agent with tool selection and failure handling
30h agents course Multi-agent systems, memory, MCP servers, deployment, guardrails

Knowledge check

  1. What is the difference between a workflow and an agent? Give one example of each.
  2. Write the three parts of one ReAct step.
  3. Why use an explicit final_answer tool instead of free text?
  4. Name three termination conditions and the status each one reports.
  5. A step succeeds 90% of the time. What is the success rate of a 10-step task?
  6. Your agent must summarise client emails. Name two privacy risks and two mitigations.
  7. Native tool use or text ReAct: which one produces more hallucinated tool calls with a small local model, and why?

Key takeaways

  • An agent = an LLM in a loop choosing tool calls from observations, until a stop condition
  • Start with workflows; add autonomy only when an evaluation proves it helps
  • ReAct + tool dispatch is ~60 lines: validate arguments, return errors as observations, log everything
  • Terminate explicitly: final-answer tool, max iterations, budgets, no-progress detection
  • The ecosystem standardises around MCP, code frameworks and low-code tools (n8n, ComfyUI)
  • Agents compound errors, cost more and widen the attack surface; self-hosted open-weight stacks keep sensitive data inside

Checklist (close)

Before you leave, you can explain:

Next session

Session 7, Diffusion and multimodal generation: from text to images.

  • The forward and reverse diffusion process, latent diffusion
  • CLIP text conditioning, classifier-free guidance, samplers
  • Evaluation: CLIP score, FID, structured human protocol