Session 6 - 3 hours - Lecture + live-coding lab
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
Produced: a research-assistant agent evaluated on 15 questions: success rate, iterations, hallucinated-tool-call rate
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?
✅ 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.
You normalise every embedding to length 1 at indexing time. Which ranking changes?
✅ 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).
The reranker returns 20 chunks for a question. What do you put in the prompt?
✅ 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.
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.
“Agentic” is the most used, and most abused, word in AI right now
Today = the vocabulary, the loop and the judgement. Course on agentic workflow will give you a concrete usage of them
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
Not an agent
→ those are workflows, often the better choice
Start with the simplest pattern that works: add agentic complexity only when it measurably helps.
🎲 first projects
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.")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.
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:
A tool = name + description + JSON schema of arguments (Session 4: tool calling is structured output).
SELECT, file read → low riskfinal_answer, ask_human, handoff_to_agent → steer the loop itselfTool design matters as much as prompts: clear names, precise descriptions, few well-scoped tools, errors that tell the model how to recover.
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}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}is_error)final_answerNative tool use (the code above)
Text ReAct (today’s lab)
Thought: I need the July 2022 rate.
Action: search[ECB rate July 2022]
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.
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
They come in three flavours:
Count them in your evaluation:
hallucinated-tool-call rate = invalid calls ÷ all calls
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
Reasoning models (Session 4) already plan inside their thinking tokens; a written plan adds what they lack: progress that survives 50 steps.
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
The context window is the agent’s short-term memory. Same agent, step 30:
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.
Today’s lab writes the loop by hand (≈ 60 lines): once you understand it, every framework is just a nicer wrapper.
LangGraph graphs & state
LlamaIndex graphs & state
CrewAI multi-agent teams
AutoGen multi-agent teams
Agno multi-agent teams
smolagents minimal ReAct loop
PydanticAI minimal ReAct loop
OpenAI Agents SDK vendor SDK
Claude Agent SDK vendor SDK
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.
The lab’s hand-written loop, piece by piece, in LangGraph’s vocabulary:
llm.next_step(...) → an LLM nodeTOOLS[name](arg), errors as observations) → a tools nodetranscript → the graph’s state (the message list)max_iterations → the recursion limitWhat the framework adds on top: checkpoints (resume a run), human approval before a node, streaming, tracing.
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 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]
Session 7 (diffusion) explains what happens inside these nodes: text encoders, samplers, guidance, VAEs.
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
3 Shared standards
MCP joined the Linux Foundation in Dec. 2025
💼 Business corner
×2 every ~7 months: the length of tasks agents finish alone (50% success, METR). Plan around a moving target.
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.
Claude Code: an agent in your terminal that works on a real codebase.
Live: fix a bug in a tiny ECB repository until the tests pass.
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.
Example scorecard: one agent, 15 ECB questions (illustrative)
max_iterations 2, stuck 1Same agent, a much smaller model: llama3.2:1b (1 billion parameters instead of 8). Three questions:
memo-x?Name each failure before the next slide does.
A 95%-reliable step sounds great, until the task needs 20 of them. Fewer, better steps beat long autonomous chains.
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
Fix: tools that know the numbers (costs, a CRM) and instructions that reward profit, not pleasing the customer
Replit (July 2025): SaaStr’s founder built an app with Replit’s coding agent, then declared a code freeze.
What went wrong
npm run db:push without askingFix (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.
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
Fix: start from a workflow (“Workflows first”), measure it (the scorecard), add autonomy only where it pays
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.
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.
What went wrong (March 2023): weeks after allowing ChatGPT, its chip division found three leaks
All of it ended up on OpenAI’s servers
Fix
With an agent, nobody pastes: the tools read the files for you
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
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
Build the agent from the demos, then measure how reliable it is.
llama3.1:8b and llama3.2:1b with Ollama, pulled before class (no API key)search (BM25 over the ECB archive), calculator, days_between, final_answerAction: tool[input] parsed by your regex, max_iterations = 8QUICK = True)Done means: the results table for both models, plus 3 failed traces explained, not “the agent seemed smart”.
calculator (no eval: parse with ast)parse_action, which turns Action: search[ECB rate] into a call, or returns Nonerun_agent: dispatch, invalid calls, max_iterations, and stuck as soon as a call repeatstrace_board on a two-hop question, then read three failed traces with show_traceis_correct, run the questions with both models, complete the summaryBonus: break it (the three experiments from the demo), and the same agent in LangGraph.
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?
| 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 |
| 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 |
final_answer tool instead of free text?Before you leave, you can explain:
Session 7, Diffusion and multimodal generation: from text to images.
Albert School - Agents and Tool Use