# Teacher Guide — Session 6: The agentic loop

**Program:** Applied AI — Intermediate Level
**Instructor:** Yann Isola
**Duration:** 2 hours (120 minutes)
**Module covered:** Module 4 — Part 1 (The agentic loop)

---

## 1. Session overview

### Educational objectives

At the end of this session, each participant should be able to:

1. **Distinguish between chatbot and agent**: a chatbot produces *one* response then stops; a **loop** agent — it chains actions until the task is accomplished.
2. **Unwind the agentic loop**: perceive → think → act → observe → start again, and know how to situate each step in a concrete example.
3. **State the key distinction**: it is the **agent who decides** when he is finished (the chatbot stops mechanically after a response).
4. **Connecting the tools to the loop**: tool calling, seen in Session 5, *is* the “act” step — the tools are the agent’s hands.
5. **Explain Planning**: The model breaks down a goal into sub-steps *before* taking action, and can revise that plan along the way.
6. **Describe an agent's working memory**: The conversation history and scratchpad serve as memory *during* an execution.
7. **List the essential safeguards**: maximum number of iterations, budget ceiling, human checkpoints (human-in-the-loop).
8. **Describe error recovery**: a tool fails → the model *reads* the error message → adapts its strategy → tries again differently.
9. **Know when NOT to use an agent**: if a single prompt is enough, an agent is over-engineering (cost, latency, unnecessary risks).

### Prerequisites

- **Session 5 (Outils & Tool Calling) is essential.** The agentic loop is literally the `tool_use` loop of Session 5, generalized and extended. If participants missed Session 5, allow 5 minutes of individual catch-up time before the start.
- Know how to read a simple JSON object (JavaScript Object Notation, data exchange format).
- Understand the concept of API (Application Programming Interface).

### Materials needed

- Video projector + session slides (`slides/slides.md`).
- Interactive web page (`webpage/index.html`) — works **offline**: animated visualizer of the agentic loop with the step-by-step TripDesk scenario, and interactive decision tree “Should I have an agent?” ".
- Worksheets (`exercises/exercises.md`) printed or shared.
- End of session quiz (`quiz/quiz.md`).
- Ideally: one laptop for two participants, to operate the viewer.

### Central message of the session

> “An agent is a language model in a loop, with tools, and the right to decide when it is finished. Everything else — planning, memory, safeguards — exists to make this loop *useful* and *safe*. »

Repeat this idea at least three times during the session, in different forms. A participant who only remembers this sentence leaves with the essentials.

### Narrative thread

The entire session is based on **a single spun example: TripDesk**, a travel reservation agent. Its typical mission:

> “Find me a flight Paris → Lisbon the week of the 14th, compatible with my schedule, book it and send me the confirmation. »Its tools: 🔍 `chercher_vols` (flight search), 📅 `consulter_agenda` (reading the user's calendar), ✈️ `reserver_vol` (reservation — irreversible action!), ✉️ `envoyer_confirmation` (confirmation email).

TripDesk is used to illustrate **each** concept: the loop, planning, memory, guardrails (the human checkpoint before `reserver_vol`), error recovery (a complete flight → the agent searches for an alternative). Repetition of the same example anchors concepts.

---

## 2. Unfolded minute by minute

| Schedule | Duration | Sequence | Support |
|---|---|---|---|
| 0:00 – 0:05 | 5 mins | Home, reminder Session 5 (tool calling), objectives | Slides 1–3 |
| 0:05 – 0:20 | 15 mins | Sequence A — From chatbot to agent | Slides 4–7 |
| 0:20 – 0:40 | 20 mins | Sequence B — The agentic loop (perceive → reflect → act → observe) | Slides 8–12 + visualizer |
| 0:40 – 0:55 | 15 mins | Sequence C — Step-by-step TripDesk Guided Demo | Webpage (viewer) |
| 0:55 – 1:05 | 10 mins | ☕ Break | — |
| 1:05 – 1:20 | 15 mins | Sequence D — Planning & working memory | Slides 13–17 |
| 1:20 – 1:35 | 15 mins | Sequence E — Guardrails & error recovery | Slides 18–22 |
| 1:35 – 1:45 | 10 mins | Sequence F — When NOT to use an agent (decision tree) | Slides 23–25 + webpage |
| 1:45 – 1:55 | 10 mins | Flash exercise in pairs (Exercise 1 of the sheet) | Exercises |
| 1:55 – 2:00 | 5 mins | Express quiz (5 oral questions), exit tickets, announcement Session 7 | Quiz + slides 26–28 |

> ⏱️ **Safety margin:** if you fall behind, Sequence F can be compressed to 5 minutes (the decision tree is also in the webpage, which participants can explore at home). **Never** sacrifice Sequence C (TripDesk demo): this is the moment when “it clicks”.

---

## 3. Detailed notes by sequence

### Sequence A — From chatbot to agent (15 min)

**Objective:** to bring out the definition of an agent by contrast with what the participants already know.

**Hooker (2 min).** Ask the question: “When you ask ChatGPT to book a flight for you, what happens? » Expected response: he *explains how to do it*, or he *invents* a reservation. He doesn't do it. For what ? Because a chatbot works in **one turn**: a question → an answer → stop.

**The fundamental contrast (8 min).** Write on the board, in two columns:

| Chatbot | Officer |
|---|---|
| One round: question → answer → **stop** | A **loop**: acts as long as the task is not finished |
| Stops mechanically after its response | **Decides for himself** when he is finished |
| Produces text | Produces **actions** (via tools) + text |
| No effect on the world | Can modify the world (book, write, send) |
| Error = false answer | Error = failed action → he can **make up for it** |

**Point of emphasis:** line 2 is THE conceptual distinction. A chatbot stops because that’s its architecture. An agent stops because it **evaluates** that the objective has been achieved. Control of “when it’s finished” moves from code to model. It's powerful — and that's exactly why we need guardrails (Sequence E teaser).

**Analogy that works well (3 min).** The chatbot is a **consultant on the phone**: it tells you what to do, then hangs up.The agent is a **personal assistant**: you entrust him with the mission, he makes the calls, compares, reserves, and comes back to you when it's done — or when he needs your agreement.

**Trap to defuse (2 min).** Some participants believe that an agent is “another model”, more intelligent. No: **it's often exactly the same model** (Claude, GPT, etc.), placed in a different architecture — a loop with tools. Agency is a property of the *system*, not of the model alone.

---

### Sequence B — The agentic loop (20 min)

**Objective:** that each participant knows how to draw and comment on the perceive → think → act → observe cycle.

**The cycle (10 min).** Draw the cycle on the board (or project slide 9):```
        ┌──────────────┐
   ┌───▶│ 1. PERCEVOIR │  (lire la mission, le contexte, les résultats précédents)
   │    └──────┬───────┘
   │           ▼
   │    ┌──────────────┐
   │    │ 2. RÉFLÉCHIR │  (raisonner : où en suis-je ? que faire ensuite ?)
   │    └──────┬───────┘
   │           ▼
   │    ┌──────────────┐
   │    │ 3. AGIR      │  (appeler un outil — les « mains » de l'agent)
   │    └──────┬───────┘
   │           ▼
   │    ┌──────────────┐
   └────│ 4. OBSERVER  │  (lire le résultat de l'outil : succès ? erreur ? données ?)
        └──────────────┘
              │
              ▼  (si l'objectif est atteint)
        ✅ TERMINÉ — l'agent le décide lui-même
```Comment on each step with TripDesk:

1. **Perceive**: TripDesk reads the mission (“Paris–Lisbon flight week of the 14th, calendar compatible, book, confirm”) and everything it already knows.
2. **Think**: “I don’t know the available flights or the schedule. I start by looking for flights. »
3. **Act**: call tool `chercher_vols(origine="CDG", destination="LIS", semaine="2026-07-14")`. Reminder Session 5: the model *requests* the call, it is **your code** that executes it.
4. **Observe**: the tool returns 3 flights. TripDesk reads this result... and the loop starts again: perceive (new state), reflect ("now, check the calendar"), act (`consulter_agenda`), observe...

**Explicit link with Session 5 (5 min).** Insist: “You already know step 3! The Session 5 tool call is exactly the "act" of the loop. What's new is that we **continue** the rounds instead of stopping after just one. » The tools are the **hands** of the agent; without tools, the loop thinks in a vacuum — it can do nothing but speak.

**Vocabulary (3 min).** Introduce the English terms that participants will encounter everywhere: *agentic loop*, *reasoning* (reasoning, the “think” step), *tool call*, *observation* (the returned result). Mention that some frameworks call this pattern “ReAct” (Reasoning + Acting) — no need to go into academic detail, it's the same cycle.

**Check question (2 min).** “In the loop, who actually executes the tool call?” » Expected response (acquired Session 5): the application code, never the model. If less than half the room answers correctly, do another 2-minute reminder.

---

### Sequence C — TripDesk guided demo (15 min)

**Goal:** see the loop *turn*, iteration by iteration.

Open `webpage/index.html`, “Loop Viewer” section. The TripDesk scenario is simulated in 5 iterations, each broken down into perceive / reflect / act / observe. Move forward with the “Next step” button and **comment out loud on each step**:

- **Iteration 1**: flight search → 3 results.
- **Iteration 2**: consultation of the agenda → conflict detected with the cheapest flight (meeting on Tuesday morning).
- **Iteration 3**: the agent **adapts his plan** — he rejects the conflicting flight, chooses Thursday's flight. ⚠️ Human checkpoint: before booking (irreversible action, payment!), the agent requests validation from the user. Point out the pause: *this is a safeguard, not a weakness*.
- **Iteration 4**: reservation → **simulated failure** (“full flight”). The agent reads the error, does not panic, does not try the same thing again: he **changes strategy** and books the next flight (after new validation). This is error recovery in action.
- **Iteration 5**: sending the confirmation → the agent **evaluates that the mission is accomplished** and decides to stop.

**Three things to point out explicitly:**
1. The iteration counter and budget counter at the top of the viewer — guardrail teaser (Sequence E).
2. The “scratchpad” panel which is enriched with each iteration — memory teaser (Sequence D).
3. The final moment when the agent declares “goal achieved”: **no one stopped him, he decided** — the loop on the key distinction of Sequence A.If time permits, give the pairs 3 minutes to replay the simulation themselves.

---

### Sequence D — Planning & working memory (15 min)

**Objective:** understand how the agent structures its work *before* and *during* the loop.

**Planning (8 min).** Before acting, a good agent **breaks down** the objective into sub-steps. For TripDesk:```
Objectif : réserver un vol Paris–Lisbonne compatible agenda
Plan :
  1. Chercher les vols disponibles la semaine du 14
  2. Consulter l'agenda pour identifier les conflits
  3. Sélectionner le meilleur vol sans conflit
  4. Demander validation à l'utilisateur
  5. Réserver
  6. Envoyer la confirmation
```Two points of emphasis:
- The plan is produced **by the model itself** (often triggered by an instruction from the system prompt such as “before acting, draw up a plan”). It’s text, in context — nothing magical.
- The plan **is not fixed**: in iteration 2, TripDesk discovers the agenda conflict and revises step 3. An agentic plan is a working hypothesis, not a contract. Compare to a GPS (Global Positioning System) route that recalculates when you miss an exit.

**Working memory (7 min).** Question to the room: “Between iteration 1 and iteration 4, how does TripDesk remember the 3 flights found? » Answer: **everything is in the conversation history**. Each tool call and each result are added to the context; at each iteration, the model rereads the whole thing. This is its **working memory** — we also speak of *scratchpad* (notepad).

Practical consequences to be stated:
- This memory is **limited by the context window** (context window, the maximum amount of text that the model can read at once). An agent that loops 50 times with large tool results can saturate its window — hence techniques for summarizing or truncating old results.
- This memory is **cleared at the end of execution**. *Persistent* memory between sessions (user profiles, preferences) is another topic — teaser for a later session.

**Analogy:** an investigator's notepad during a case. Everything is noted there (clues, ruled out leads, next actions); he rereads it before each decision; and he opens a new notepad for the next case.

---

### Sequence E — Guardrails & error recovery (15 min)

**Objective:** understand that unlimited autonomy is a design flaw, not an achievement.

**Why guardrails (3 min).** Recall the key distinction: the agent decides when he is finished. What if it never ends? What if he has the wrong objective? An agent without limits can: loop infinitely (and burn API budget with each iteration), wrongly undertake irreversible actions, drift far from the mission. The safeguards do not restrict the agent: they make his autonomy *acceptable*.

**The three canonical safeguards (7 min).** On the board:

| Guardrail | What it is | TripDesk Example |
|---|---|---|
| **Max iterations** | Maximum number of loop turns before forced stop | 15 iterations, otherwise abandon with report |
| **Budget ceiling** | Cost (tokens/API calls) or time limit | ⚠ p. ex. €0.50 API per mission (order of magnitude: API prices evolve) |
| **Human checkpoint** (human-in-the-loop) | The agent MUST request validation before certain actions | Always before `reserver_vol` (payment, irreversible) |

Practical rule to note: **any irreversible or costly action requires a human**. Reading flights: autonomous. Pay for a ticket: validation. This is a direct extension of the principle of least privilege seen in Session 5.

**Error recovery (5 min).** Unwind the pattern in 4 steps, with the reservation failure of the demo:

1. **The tool fails**: `reserver_vol` → `{"erreur": "vol complet"}` (with flag `is_error` from Session 5).
2. **The model reads the error**: the error message is returned *in context*, like any tool result.Hence the importance of **explicit** error messages: “complete flight” allows adaptation; “error 500” doesn’t say anything.
3. **He adapts his strategy**: no need to retry the same flight — he starts from the search results and selects the alternative.
4. **He tries again differently**: new human validation, new reservation, success.

**Point of emphasis:** the quality of recovery depends on the quality of the error messages *you write in your tools*. A robust agent is conceived on the tools side as much as on the model side. Anti-pattern to name: the agent which retries **identically** in a loop — this is precisely what the max iterations guardrail stops.

---

### Sequence F — When NOT to use an agent (10 min)

**Objective:** to vaccinate against over-engineering. This is the “critical thinking” sequence of the session.

**The trap (3 min).** Agents are in fashion; the “put an agent everywhere” reflex is expensive. Each iteration = one call to the model = cost + latency + additional risk of error. **If just one well-written prompt is enough, an agent is over-engineering.**

Examples to decide with the audience (have them vote by show of hands):
- “Summarize this document” → **a prompt is enough.** No action, no external data, no multi-step decision.
- “Translate this email into English” → **a prompt is enough.**
- “What is the weather like in Lisbon? » → **one tool call is enough** (Session 5) — no need for a loop.
- “Book me the best flight compatible with my schedule” → **agent**: several tools, order unknown in advance, intermediate decisions, adaptation to results.

**The decision tree (5 min).** Project the interactive tree of the webpage:

1. Does the task require **acting** on external systems or reading live data? → No: **simple prompt** (possibly with RAG, Retrieval-Augmented Generation, generation augmented by retrieval).
2. Is a **single** tool call enough, in an order known in advance? → Yes: **simple tool calling** (Session 5) or a hard-coded fixed sequence (workflow).
3. Does the number of steps or their order **depend on the intermediate results**? → Yes: **agent**.
4. Bonus: Is the cost of error high? → Add human checkpoints.

Formula to note: **“Prompt < single tool < fixed workflow < agent. Always take the simplest weapon that accomplishes the mission. »**

**Review (2 min).** Have 2–3 cases proposed by the participants themselves (their business contexts) classified. This is often the richest moment of the session.

---

### Closing (5 min)

- Express quiz: ask orally questions 1, 3, 5, 7, 10 of the quiz (the complete answers are in `quiz/quiz.md` for homework).
- Distribute the **exit tickets** (below).
- Announce Session 7 and the bridge: “You now know how to run ONE agent. What if several agents collaborated? » (or the hook adapted to the program).

---

## 4. Attendee Frequently Asked Questions (and Answers)

**“Is an agent a different model from a chatbot? "**
No. Often the exact same model. The difference is architectural: loop + tools + stopping criterion decided by the model. Agency is a property of the system.

**“How does the agent know he’s done?” »**
At each iteration, the model rereads the mission and the current state, and evaluates whether the objective is achieved.Concretely: either it responds without requesting a tool (natural end of the `tool_use` loop), or it calls an explicit tool of type `terminer(rapport)`. It is an evaluation by the model — hence the safeguards, because this evaluation can be erroneous.

**“What if the agent loops infinitely? »**
This is exactly the role of the max iterations guardrail: forced stop + report of what has been done. In practice, we also log each iteration to diagnose *why* it was going in circles (often: a too vague tool error message, or an ambiguous mission).

**“Can the agent spend money without authorization? »**
Only if you designed it that way — and that's a design flaw. Any irreversible or costly action must go through a human checkpoint. Reminder Session 5: it is *your code* that executes the calls; it is therefore your code which imposes the validation.

**“Is scheduling an API feature? »**
No, it is a behavior of the model, generally encouraged by the prompt system (“make a plan before you act”) and by the reasoning abilities of the model. The plan lives in context, like everything else. ⚠ Some platforms add dedicated mechanisms (extended reasoning modes, integrated planners) — the landscape is evolving quickly.

**“How many iterations is normal?” »**
⚠ Order of magnitude, very dependent on the task: 3 to 10 iterations for a typical TripDesk task; software development workers can do dozens of them. Beyond what you had estimated, it is an inspection signal, not necessarily a breakdown.

**“What is the difference between a workflow and an agent? »**
A workflow connects steps **set in advance by the developer** (step 1 then 2 then 3). An agent chooses **itself** its steps and their order based on the results. The workflow is more predictable and less expensive; the agent is more flexible. Many “fake agents” in production are actually workflows — and that’s fine.

---

## 5. Educational pitfalls to avoid

1. **Moving too quickly to Sequence A.** If the distinction “the agent decides when he is finished” is not anchored, everything else floats.
2. **Do the TripDesk demo without commenting on the internal steps.** The visualizer shows perceive/think/act/observe at each iteration: verbalize them systematically, otherwise the participants only see a succession of results.
3. **Present the safeguards as optional.** No: max iterations + budget + human validation of irreversible actions = the minimum kit for any agent in production.
4. **Glorifying agents.** Sequence F exists for that. A credible trainer is one who says *when not to* use the technology they are teaching.
5. **Lead to believe that working memory is persistent.** It disappears at the end of execution — say it explicitly, confusion is common.

---

## 6. Exit tickets (5)

To be distributed on paper or form in the last 5 minutes. One sentence response is enough.

1. **In one sentence: what is THE difference between a chatbot and an agent?**
*(Expected: the chatbot stops after a response; the agent loops and decides itself when the task is accomplished.)*

2. **List the 4 steps of the agentic loop, in order.**
*(Expected: perceive → think → act → observe, then start again.)*

3.**List two safeguards you would impose on an agent who can make payments.**
*(Expected, two of: human validation before payment, budget cap, max number of iterations, logging.)*

4. **A tool returns “error: theft complete”. What does a well-designed agent do?**
*(Expected: he reads the error, adapts his strategy — e.g. chooses another flight — and tries again differently; he does not try again the same way.)*

5. **Give an example of a task where using an agent would be over-engineering, and why.**
*(Expected: any task in one go – summary, translation, simple weather question – because a prompt or a single tool call is enough: cheaper, faster, less risky.)*

---

## 7. Bridge to the sequel

- **Acquired after this session:** the complete architecture of an individual agent — loop, tools, plan, working memory, guardrails, error recovery, and usage discernment.
- **Next session:** in-depth analysis of Module 4 (depending on the program: agent design in practice, multi-agent orchestration, or agent evaluation). Suggested hook: “This week, look around at a task in your job and ask yourself: prompt, single tool, workflow or agent? Bring your case, we'll break it down. »