Unlock all weeks

Zero to FDE / Free Week 1 / Week 4 sample

Free sample · Week 4, lesson 1 of 4 · about 180 min

The ReAct loop by hand: call, parse, execute, feed back

Roadmap task: Build the ReAct pattern yourself: a loop that calls the model, parses a tool call, executes it, feeds the result back

Why this lesson is free. If you already write backend code, Week 1 will not tell you much about this course. This lesson will: it is one of the 77 lessons from Weeks 2 to 16, unchanged.

In this lesson: 8 ideas
  • The mental model: the model proposes, your code disposes
  • The ReAct idea
  • From text protocol to native tool use
  • The loop as a state machine
  • Message history: the shape the API insists on
  • and 3 more
180 min
to read and practise
14 steps
one idea at a time
2 visuals
diagrams and hands-on
6 code
2 you can run here
5 checks
test yourself
Why this matters

Every agent framework you will meet, LangGraph next week included, is a wrapper around one small loop: ask the model what to do, run the tool it asked for, show it the result, repeat until it says it is done. When a client's agent "hangs", "calls the same tool forever", or "gives up after one step", the bug is almost always in that loop: a missing stop condition, a tool result attached to the wrong call, a history the API rejects. If you have only ever used a framework, you cannot see the loop, so you cannot debug it. This lesson has you write it yourself, run it with no API key against a scripted fake model, and then point the same design at the real Anthropic Messages API.

The mental model: the model proposes, your code disposes

A language model cannot do anything. It cannot call an API, read a database, or send an email. All it can do is produce output. An "agent" is your program reading that output, noticing that it is a request to run a tool, running the tool itself, and handing the result back as more input. The model never touches the outside world; your loop does, on its behalf, one step at a time.

Hold on to that sentence: the model proposes, your code disposes. It tells you where every safety control lives (in your code, not in the prompt), where every bug lives (usually in your code too), and why the loop is worth understanding in detail.

The agent loop
  1. Call the modelwith the messages and tool definitions
  2. Read stop_reasontool_use, or end_turn?
  3. Run the toolyour code does it, never the model
  4. Append the resultas a tool_result message
back to the model, until end_turn or the step limit

The ReAct idea

The pattern has a name and a paper. In "ReAct: Synergizing Reasoning and Acting in Language Models" (Yao et al., first posted October 2022, published at ICLR 2023), the authors prompted a model to interleave three kinds of text:

  • Thought: free-text reasoning about what to do next ("I need the birth year of the director, so I should search for the film first").
  • Action: a call to a tool from a fixed set. For the question-answering tasks they gave the model a tiny Wikipedia API with three actions: search[entity], lookup[string] and finish[answer].
  • Observation: the tool's output, pasted back into the prompt by the program, not written by the model.

The argument of the paper is that the two halves help each other. Reasoning alone (chain-of-thought) has no way to check facts, so it confidently invents them; the authors found hallucination was the main cause of chain-of-thought failures on HotpotQA. Acting alone (just emitting tool calls) has no place to plan, track progress or notice a dead end. Interleaving them grounds the reasoning in real observations and gives the actions a plan. On two interactive benchmarks, ALFWorld and WebShop, ReAct beat imitation-learning and reinforcement-learning baselines by 34 and 10 absolute percentage points of success rate using only one or two examples in the prompt.

The paper is also honest about failure, and those failures are exactly what this week is about. ReAct's most common error was reasoning that went wrong, including the model repeating its previous thought and action in a loop. Unhelpful search results derailed it too. The authors capped the loop at a fixed number of steps and fell back to another method when it ran out. You will build the same guards.

From text protocol to native tool use

In 2022 the "tool call" was plain text that the program had to parse. A trace looked like this (an illustrative example, not from the paper):

Text
Thought: I need the order before I can compute anything.
Action: get_order[A-1023]
Observation: {"items": [{"sku": "kurta", "price": 1299, "qty": 2}]}
Thought: Subtotal is 2598. Add 18% GST.
Action: finish[3065.64]

Parsing that is fragile, which you can see for yourself:

Python · runs as is
import re

ACTION = re.compile(r"^Action:\s*(\w+)\[(.*)\]\s*$", re.MULTILINE)

def parse_action(model_text: str) -> tuple[str, str] | None:
    """Return (tool_name, argument) from the LAST Action line, or None."""
    matches = ACTION.findall(model_text)
    return matches[-1] if matches else None

print(parse_action("Thought: look it up\nAction: get_order[A-1023]"))
print(parse_action("Thought: done\nAction: finish[3065.64]"))
print(parse_action("I think I should call get_order for A-1023."))   # prose, no action: None
print(parse_action("Action: get_order(A-1023)"))                     # wrong brackets: None
What will this print? Guess first, then check.Show output
('get_order', 'A-1023')
('finish', '3065.64')
None
None

The major model providers now offer native tool use instead. You send tool definitions (a name, a description, and a JSON Schema for the input) with the request; the model's response comes back as structured content blocks, and a tool_use block already has its name and its input parsed into an object. The ReAct structure survives intact: the model's text blocks are the Thought, the tool_use block is the Action, and the tool_result you send back is the Observation. What changed is who does the parsing. Note that you still validate what comes back; lesson 4 of this week is about the day it is wrong.

The loop as a state machine

Draw the loop before you code it. It has one working state and several exits:

Text
           +------------------+
 start --->|   CALL_MODEL     |<-------------------------------+
           +------------------+                                |
                    | inspect stop_reason                      |
     +--------------+---------------+-------------+            |
     v              v               v             v            |
  end_turn       tool_use       max_tokens    anything else    |
     |              |               |             |            |
   DONE      EXECUTE each tool   TRUNCATED      FAILED         |
             call, collect                                     |
             one result per call                               |
                    |                                          |
             APPEND assistant turn + results -- step < limit --+
                    |
               step == limit --> STEP_LIMIT

Two things to notice. First, the decision is made on a field the API gives you, stop_reason, not on the text. You never decide "the model is done" by searching its prose for the word "final". The Anthropic API returns end_turn when the model finished naturally, tool_use when it wants a client tool run, max_tokens when it was cut off by your limit, and a few others (stop_sequence, pause_turn for server-side tools, refusal, model_context_window_exceeded) that a production loop handles explicitly rather than falling through. Second, every exit except DONE is a failure your caller must be told about. A loop that silently returns None on the step limit is the classic "agent did nothing" bug.

An interactive exercise appears here when JavaScript is on.

Message history: the shape the API insists on

The model is stateless. Each call sends the whole conversation so far, and the model reads it from the top. The Messages API has a strict shape for that history, and most "400 Bad Request" errors in a hand-written loop come from breaking it:

JSON
[
  {"role": "user", "content": "What is the GST-inclusive total for order A-1023?"},
  {"role": "assistant", "content": [
    {"type": "text", "text": "I'll fetch the order first."},
    {"type": "tool_use", "id": "toolu_01", "name": "get_order", "input": {"order_id": "A-1023"}}
  ]},
  {"role": "user", "content": [
    {"type": "tool_result", "tool_use_id": "toolu_01", "content": "{\"items\": [...]}"}
  ]},
  {"role": "assistant", "content": [
    {"type": "text", "text": "Order A-1023 comes to ₹3,654.46 including GST."}
  ]}
]

The rules, from the current tool-use docs:

  1. The system prompt is a separate system parameter, not a message.
  2. Tool results go back in a user message. There is no separate "tool" role in this API.
  3. Each tool_result carries the tool_use_id of the call it answers. If the model made two calls in one turn (parallel tool use), you send two results in the same user message.
  4. The results must come in the message immediately after the assistant turn that made the calls, and the tool_result blocks must come first in that message's content. Any text you add goes after them.
  5. Every tool_use needs a tool_result, even when the tool failed or the name was nonsense. A failure is reported as a result with "is_error": true, not by skipping it.
  6. Append the assistant's content back exactly as you received it. Current Claude models can return thinking blocks alongside tool calls, and the API rejects a tool-use continuation where those blocks were dropped or edited.

A complete loop you can run with no API key

The trick that makes agent code testable is to hide the model behind a small interface (create(system, messages, tools) -> response) and write a scripted fake that returns canned responses in exactly the shape the real API uses. The fake below also checks the history rules above and fails loudly if your loop breaks them, the way the real API would with a 400.

Python · runs as is
import ast
import json
import operator
from dataclasses import dataclass, field

# ---------------- Tools: ordinary Python functions ----------------
ORDERS = {"A-1023": {"customer": "Priya", "items": [
    {"sku": "kurta", "price": 1299, "qty": 2},
    {"sku": "dupatta", "price": 499, "qty": 1}]}}

def get_order(order_id: str) -> dict:
    if order_id not in ORDERS:
        raise KeyError(f"no order with id {order_id!r}")
    return ORDERS[order_id]

_OPS = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul,
        ast.Div: operator.truediv, ast.USub: operator.neg}

def calculate(expression: str) -> float:
    """Arithmetic only. Never eval() model output: it would run any Python it wrote."""
    def ev(node):
        if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
            return node.value
        if isinstance(node, ast.BinOp) and type(node.op) in _OPS:
            return _OPS[type(node.op)](ev(node.left), ev(node.right))
        if isinstance(node, ast.UnaryOp) and type(node.op) in _OPS:
            return _OPS[type(node.op)](ev(node.operand))
        raise ValueError(f"unsupported syntax: {type(node).__name__}")
    return round(ev(ast.parse(expression, mode="eval").body), 2)

TOOLS = {"get_order": get_order, "calculate": calculate}
TOOL_SCHEMAS = [  # what the model is shown; same format as the real API
    {"name": "get_order", "description": "Fetch an order by id. Returns customer and line items with unit price in INR.",
     "input_schema": {"type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"]}},
    {"name": "calculate", "description": "Evaluate an arithmetic expression using + - * / and parentheses.",
     "input_schema": {"type": "object", "properties": {"expression": {"type": "string"}}, "required": ["expression"]}},
]
SYSTEM = "You are an order assistant. Use tools for every fact and every calculation."

# ---------------- The fake model ----------------
def check_history(messages: list[dict]) -> None:
    """Enforce the same history rules the real Messages API enforces."""
    assert messages[0]["role"] == "user", "history must start with a user message"
    for prev, cur in zip(messages, messages[1:]):
        assert prev["role"] != cur["role"], "roles must alternate user/assistant"
        if prev["role"] == "assistant":
            wanted = {b["id"] for b in prev["content"] if b["type"] == "tool_use"}
            if wanted:
                got = [b for b in cur["content"] if b["type"] == "tool_result"]
                assert cur["content"][:len(got)] == got, "tool_result blocks must come first"
                assert {b["tool_use_id"] for b in got} == wanted, "every tool_use needs exactly one tool_result"

class ScriptedModel:
    def __init__(self, script):
        self.script = iter(script)
    def create(self, system: str, messages: list[dict], tools: list[dict]) -> dict:
        check_history(messages)
        return next(self.script)   # StopIteration means the loop called the model too often

def says(text):            return {"type": "text", "text": text}
def calls(id, name, inp):  return {"type": "tool_use", "id": id, "name": name, "input": inp}

# ---------------- The loop ----------------
@dataclass
class AgentResult:
    status: str                     # "done" | "step_limit" | "failed"
    answer: str | None
    steps: int
    messages: list = field(repr=False, default_factory=list)

def execute(block: dict) -> dict:
    """Run one tool call. Always return a tool_result, success or failure."""
    fn = TOOLS.get(block["name"])
    try:
        if fn is None:
            raise LookupError(f"unknown tool {block['name']!r}; available: {sorted(TOOLS)}")
        output = fn(**block["input"])
        return {"type": "tool_result", "tool_use_id": block["id"], "content": json.dumps(output)}
    except Exception as e:   # report to the model; the loop itself keeps going
        return {"type": "tool_result", "tool_use_id": block["id"],
                "content": f"{type(e).__name__}: {e}", "is_error": True}

def run_agent(model, user_text: str, max_steps: int = 6) -> AgentResult:
    messages = [{"role": "user", "content": user_text}]
    for step in range(1, max_steps + 1):
        response = model.create(system=SYSTEM, messages=messages, tools=TOOL_SCHEMAS)
        messages.append({"role": "assistant", "content": response["content"]})
        for b in response["content"]:
            if b["type"] == "text":
                print(f"  step {step} thought: {b['text']}")
            elif b["type"] == "tool_use":
                print(f"  step {step} action : {b['name']}({json.dumps(b['input'])})")

        if response["stop_reason"] == "end_turn":
            answer = "".join(b["text"] for b in response["content"] if b["type"] == "text")
            return AgentResult("done", answer, step, messages)
        if response["stop_reason"] != "tool_use":
            return AgentResult("failed", f"unhandled stop_reason {response['stop_reason']!r}", step, messages)

        results = [execute(b) for b in response["content"] if b["type"] == "tool_use"]
        for r in results:
            print(f"  step {step} observe: {r['content'][:70]}{'  [ERROR]' if r.get('is_error') else ''}")
        messages.append({"role": "user", "content": results})
    return AgentResult("step_limit", None, max_steps, messages)

# ---------------- Run 1: the happy path ----------------
happy = ScriptedModel([
    {"stop_reason": "tool_use", "content": [says("I need the line items first."),
                                            calls("toolu_01", "get_order", {"order_id": "A-1023"})]},
    {"stop_reason": "tool_use", "content": [says("Subtotal is 2*1299 + 499. Add 18% GST."),
                                            calls("toolu_02", "calculate", {"expression": "(2*1299 + 499) * 1.18"})]},
    {"stop_reason": "end_turn", "content": [says("Order A-1023 comes to Rs 3654.46 including 18% GST.")]},
])
print("Run 1")
result = run_agent(happy, "What is the GST-inclusive total for order A-1023?")
print(" ->", result.status, "after", result.steps, "steps:", result.answer)
print("    history has", len(result.messages), "messages")

# ---------------- Run 2: a tool fails, the model recovers ----------------
recovers = ScriptedModel([
    {"stop_reason": "tool_use", "content": [calls("toolu_11", "get_order", {"order_id": "A-1O23"})]},  # letter O, not zero
    {"stop_reason": "tool_use", "content": [says("That id looks mistyped; retrying with a zero."),
                                            calls("toolu_12", "get_order", {"order_id": "A-1023"})]},
    {"stop_reason": "end_turn", "content": [says("Priya ordered 2 kurtas and 1 dupatta.")]},
])
print("Run 2")
result = run_agent(recovers, "What did order A-1O23 contain?")
print(" ->", result.status, "after", result.steps, "steps:", result.answer)

# ---------------- Run 3: a model that never stops ----------------
def forever():
    i = 0
    while True:
        i += 1
        yield {"stop_reason": "tool_use", "content": [calls(f"toolu_x{i}", "calculate", {"expression": "1+1"})]}
print("Run 3")
result = run_agent(ScriptedModel(forever()), "Keep going", max_steps=3)
print(" ->", result.status, "after", result.steps, "steps, answer:", result.answer)
What will this print? Guess first, then check.Show output
Run 1
  step 1 thought: I need the line items first.
  step 1 action : get_order({"order_id": "A-1023"})
  step 1 observe: {"customer": "Priya", "items": [{"sku": "kurta", "price": 1299, "qty":
  step 2 thought: Subtotal is 2*1299 + 499. Add 18% GST.
  step 2 action : calculate({"expression": "(2*1299 + 499) * 1.18"})
  step 2 observe: 3654.46
  step 3 thought: Order A-1023 comes to Rs 3654.46 including 18% GST.
 -> done after 3 steps: Order A-1023 comes to Rs 3654.46 including 18% GST.
    history has 6 messages
Run 2
  step 1 action : get_order({"order_id": "A-1O23"})
  step 1 observe: KeyError: "no order with id 'A-1O23'"  [ERROR]
  step 2 thought: That id looks mistyped; retrying with a zero.
  step 2 action : get_order({"order_id": "A-1023"})
  step 2 observe: {"customer": "Priya", "items": [{"sku": "kurta", "price": 1299, "qty":
  step 3 thought: Priya ordered 2 kurtas and 1 dupatta.
 -> done after 3 steps: Priya ordered 2 kurtas and 1 dupatta.
Run 3
  step 1 action : calculate({"expression": "1+1"})
  step 1 observe: 2
  step 2 action : calculate({"expression": "1+1"})
  step 2 observe: 2
  step 3 action : calculate({"expression": "1+1"})
  step 3 observe: 2
 -> step_limit after 3 steps, answer: None

Read the output line by line. Run 2 is the important one: the tool raised KeyError, the loop did not crash, the error went back to the model as an is_error result tied to the right tool_use_id, and the (scripted) model corrected itself. That is the recovery path a real model takes too. Run 3 shows why max_steps is not optional: without it, that loop runs, and bills you, forever.

Try breaking the loop on purpose: put a text block before the tool results, or drop one result when the model makes two calls. The fake's check_history fails the same way the real API returns a 400.

The same loop against the real Messages API

Swapping the fake for the real model changes only how you call it and how you read blocks (the SDK returns typed objects with attributes rather than dicts). The state machine is identical.

Python
# anthropic Python SDK 1.13 (pip install anthropic). Checked against
# platform.claude.com tool-use docs, October 2026. Needs ANTHROPIC_API_KEY.
import json
import os
import anthropic

client = anthropic.Anthropic()                      # reads ANTHROPIC_API_KEY from the environment
MODEL = os.environ["ANTHROPIC_MODEL"]               # a current id from the models list (Week 2)

# TOOLS, TOOL_SCHEMAS, SYSTEM: exactly as in the runnable version above.

def execute(block) -> dict:
    fn = TOOLS.get(block.name)
    try:
        if fn is None:
            raise LookupError(f"unknown tool {block.name!r}; available: {sorted(TOOLS)}")
        return {"type": "tool_result", "tool_use_id": block.id, "content": json.dumps(fn(**block.input))}
    except Exception as e:
        return {"type": "tool_result", "tool_use_id": block.id,
                "content": f"{type(e).__name__}: {e}", "is_error": True}

def run_agent(user_text: str, max_steps: int = 8) -> str:
    messages = [{"role": "user", "content": user_text}]
    for step in range(1, max_steps + 1):
        response = client.messages.create(
            model=MODEL, max_tokens=2048, system=SYSTEM,
            tools=TOOL_SCHEMAS, messages=messages,
        )
        # Send the assistant content back unchanged: it may include thinking
        # blocks that the API requires on the next request.
        messages.append({"role": "assistant", "content": response.content})

        if response.stop_reason == "end_turn":
            return "".join(b.text for b in response.content if b.type == "text")
        if response.stop_reason == "tool_use":
            results = [execute(b) for b in response.content if b.type == "tool_use"]
            messages.append({"role": "user", "content": results})
            continue
        if response.stop_reason == "max_tokens":
            raise RuntimeError("Response cut off by max_tokens; a tool call may be incomplete. Raise max_tokens.")
        raise RuntimeError(f"Unhandled stop_reason {response.stop_reason!r} at step {step}")
    raise RuntimeError(f"No final answer within {max_steps} steps")

if __name__ == "__main__":
    print(run_agent("What is the GST-inclusive total for order A-1023?"))

The SDK also offers a "tool runner" helper that runs this loop for you. Use it later if you like; this week the point is that you can write and debug the loop it hides.

How this shows up in FDE work

A logistics client in Pune has a "shipment status agent" built on a framework by a previous vendor. Support staff say it "sometimes just stops answering". You add logging around the loop and find the pattern in an afternoon: when a customer asks about two shipments, the model makes two track_shipment calls in one turn, the framework's custom wrapper only returns a result for the first, the API rejects the next request with a 400, and the wrapper swallows the exception and returns an empty string. Nobody saw it because nobody had looked at the loop. You fix it by returning one result per call, surfacing errors as a visible failure status, and adding a step limit. You can only find bugs like this quickly if you have written the loop yourself.

Pitfalls
  • Deciding the agent is finished by reading its text ("if 'final answer' in text"). Use stop_reason. Prose changes with every model version; the field does not.
  • Returning results for only some of the tool calls in a turn, or putting a text block before them. The API rejects the next request, and a wrapper that hides the 400 turns it into a silent stall.
  • Letting a tool exception escape the loop. One bad tool input should become an is_error result the model can react to, not a crashed request.
  • No step limit, or a step limit that returns nothing. Every non-success exit must report a clear status to the caller, and the limit must exist before your first real API call, not after the first surprise bill.
  • Calling eval() on model output for a "calculator" tool. The model's text is untrusted input; eval runs whatever Python it contains.
  • Rebuilding assistant messages by hand (keeping only text and tool_use) instead of appending the content you received. On models that return thinking blocks with tool calls, the next request fails.
Practice
Check yourself

Answer in your head or on paper first, then open the answer and be honest with yourself.

Who executes a tool in an agent: the model or your program? Why does the answer matter for safety?

Your program. The model only emits a request; your loop decides whether and how to run it, so permission checks, validation and limits belong in your code, where they cannot be talked around by a prompt.

The model made two tool calls in one turn and the second tool raised an exception. What do you send back?

One user message containing two tool_result blocks, first in the content, each with its own tool_use_id; the failed one carries the error message and "is_error": true.

Why does the loop branch on stop_reason rather than on whether the text contains an answer?

stop_reason is a structured signal from the API that says exactly why generation stopped (finished, wants a tool, truncated, refused). Text heuristics break when wording changes and cannot tell a truncated answer from a complete one.

What did ReAct add over plain chain-of-thought, and what failure did the paper itself report?

It interleaved reasoning with real actions and observations, grounding the reasoning in retrieved facts instead of letting it hallucinate them. The paper reported that ReAct sometimes repeats the same thought and action in a loop, which is why a step limit is part of the design.

Why build a scripted fake model at all if you have an API key?

It makes the loop deterministic and free to run, so you can test every path (success, tool failure, step limit, malformed history) in milliseconds and in CI, which a live model cannot do reliably.

Use AI for this

This is a week to write the code yourself first. The loop is about sixty lines, and typing it is how you learn where each rule lives. Once your version runs against the fake model, AI tools are useful in three ways: as a reviewer that checks your loop against the API's history rules, as a generator of nasty test scripts for your fake model, and as an explainer for the paper. Do not ask an assistant to "build me an agent"; you will get a framework call that hides exactly what this week is teaching.

Review my agent loop against the API rules
You are a senior engineer who has debugged many hand-written LLM agent loops built on the
Anthropic Messages API with client tools. Review my loop below. Check specifically:
1. Is the decision to stop or continue based on stop_reason, and is every stop_reason value
   handled explicitly (end_turn, tool_use, max_tokens, refusal, and anything else)?
2. Does every tool_use block get exactly one tool_result with the matching tool_use_id,
   in the very next user message, with tool_result blocks first in the content?
3. Is the assistant content appended back unchanged (no rebuilt blocks)?
4. Can any tool exception escape the loop instead of becoming an is_error result?
5. Is there a step limit, and does every non-success exit return a clear status?
For each problem: quote the line, explain the failure it causes at runtime, and show the
smallest fix. Do not rewrite the loop or suggest a framework. If you are unsure whether the
API enforces a rule, say so instead of guessing.

My code:
[PASTE YOUR LOOP]
Generate adversarial scripts for my fake model
I test my hand-written agent loop with a scripted fake model. Each script is a Python list of
responses in the Anthropic Messages API shape: {"stop_reason": ..., "content": [blocks]}, where
blocks are {"type": "text", "text": ...} or {"type": "tool_use", "id": ..., "name": ..., "input": {...}}.
My tools are: [LIST TOOL NAMES AND THEIR INPUT FIELDS].

Write 6 scripts that each exercise a different path through the loop: two parallel tool calls
in one turn, a tool that raises, a call to a tool name that does not exist, a stop_reason of
"max_tokens", a model that never stops calling tools, and a normal success. For each script
state in one sentence what the loop SHOULD do, so I can turn it into an assertion. Output only
Python code with comments; no prose outside the code.
Walk me through the ReAct paper
I am reading "ReAct: Synergizing Reasoning and Acting in Language Models" (Yao et al., arXiv
2210.03629). Act as a tutor. First ask me to explain, in my own words, what problem the paper
says chain-of-thought alone has and what problem acting alone has. Correct my answer. Then
explain the Thought / Action / Observation format using one of the paper's HotpotQA-style
tasks, and map each part onto native tool use in today's APIs (text block, tool_use block,
tool_result block). Finally ask me three questions about the failure modes the paper reports
and how a step limit addresses one of them. Do not quote long passages; summarise and point
me to the section to read.
Watch out

AI assistants often write agent loops for an older or different API shape: a separate "role": "tool" message (that is another provider's format, not Anthropic's), function_call fields, or results matched to calls by position instead of by tool_use_id. They also love while True: with no step limit, eval() for calculator tools, and a broad except Exception: return "" around the API call that turns every 400 into a silent stall. Model names in generated code are frequently out of date. Check every message shape against the "Handle tool calls" page linked below, read model names from an environment variable, and run the generated loop against your fake model's check_history before you spend a single API call.

Go deeper
The rest of Week 4

This loop becomes a real agent.

A from-scratch agent loop, still zero frameworks, using three or more tools, that retries failed calls and stops cleanly when done or after a step limit. Keep this file. You will compare it to LangGraph next week.

  • Agent memory three ways: buffer, rolling summary, retrieval
  • When tools fail: retries, timeouts, backoff and honest error reports
  • Breaking your agent on purpose: malformed output, guards, and the Week 4 build
Unlock all 16 weeks

₹2,999 once · 7-day full refund

8 of our paying students are working engineers with 3 to 8 years of experience.