← Build an AI Agent Lesson 3 of 8

Build the loop

✏️ Quick basics: reading Python

Time to build me for real, in Python. You'll only need to read four things.

Pick one. Guess what it prints.
text = "THINK: hi" + "\n" + "ACT: go"
print(text)

Text in quotes is a string. [ ] is a list, counted from 0. { } is a dictionary: key → value. def makes a function: input in, return hands the result back. Tap any dotted word in the code for help.

"string" · [list] · {key: value} · def function

A tool is one of these functions.

Tools are functions

First, my tools.

In code, a tool is a Python function: text goes in, text comes out.

Pick a tool, then call it. Try something that doesn't work, too.

today is a dictionary: city → weather. .get looks the city up, in small letters (.lower()). If it isn't there, it gives back an error, with the city put into the text (f"…{city}").

def weather(city):
    today = {"kochi": "29°C, sunny", "delhi": "18°C, foggy", "pune": "24°C, light rain"}
    return today.get(city.lower(), f"Error: no city called {city}")
weather(" ")
# press ▶ Run

The ACT: line only gives the tool's name, as text. So the program keeps every tool in another dictionary, name → function, and finds the tool by its name:

TOOLS = {"calculator": calculator, "weather": weather}

TOOLS["weather"]            # → the weather function
TOOLS["weather"]("Kochi")   # → same as weather("Kochi") → "29°C, sunny"

TOOLS[name](input) = find the tool, then run it.

The program needs that name. How does it get it out of the LLM's reply?

Find the ACT: line

The LLM only writes text, like ACT: weather(Kochi). It's text, not Python, so it needs no quotes. The program must pick out the tool's name and its input.

Edit the reply, or pick one. See what the program finds.

The program uses a template with two blanks: ACT: 1(2). In Python, a template like this is called a pattern. re.search lays the pattern over the reply and hands back what filled the blanks. We call that act. act.group(1) asks for blank 1, the name. act.group(2) asks for blank 2, the input. If the reply doesn't fit, you get None. All of that is one line:
act = re.search(r"ACT: (\w+)\((.*)\)", reply)

Try it on new examples.

✏️ Practice 3.1

New examples, same ideas.
Remember: in Python, text needs quotes: weather("Pune"). In an ACT: line, no quotes: ACT: weather(Pune). The program takes the input out of the brackets as text.
TOOLS[name](input) calls the tool with that name.
No ACT: line, or a name not in TOOLS → an error, and no tool runs.

Work each one out. Type the answer, press Check.
What temperature, in °C, does weather("PUNE") give back? (The weather tool's code is on the Tools are functions page.)
The reply is ACT: calculator(12 * 7). What number ends up on the LOOK: line?
Four replies: ACT: weather(Delhi) · ACT: wether(Delhi) · I'll check the weather. · ACT: calculator(2 + 2). How many make the program run a tool?

Tools, and a way to find them. Now the loop.

The loop in code

Here is the whole loop as one Python function, run_agent. Each part of the loop is a few of its lines.

Press a part of the loop. See which lines do it.

Each pass through the for loop is one round. range(step_limit) runs it at most step_limit times: 5, unless you pass another number. return ends it early: an answer in round 2 means only 2 rounds run.
The loop ends at ANSWER: (return), or after step_limit rounds.

The loop needs an LLM to call. Which one?

A fake LLM first

A real LLM is slow, and its replies change from run to run. So test the loop first with a fake LLM: it hands back replies you wrote yourself.

Pick a test. Step through the loop.
def fake_llm(text):
    # next reply; text is ignored
    return fake_replies.pop(0)
Test:

No model needed, so you can test every part of the loop first: tools, errors, the step limit.
fake LLM = replies you wrote, handed back in order

Try it on new numbers.

✏️ Practice 3.2

New numbers, same ideas.
Remember: each call to the LLM uses one reply. A reply with ACT: gets one LOOK: line.
The loop ends at ANSWER:, or after step_limit rounds.

Work each one out. Type the answer, press Check.
fake_replies holds ACT, ACT, ACT, then ANSWER. step_limit=5. How many times is the LLM called?
step_limit=4. Every reply in fake_replies has an ACT: line, and none has ANSWER:. How many LOOK: lines does the program write?
fake_replies holds ACT, ACT, then ANSWER. But step_limit=2. How many of the replies get used?

The loop works. Time for a real LLM.

A real LLM

Now swap in a real LLM. It writes its own replies, and they aren't always tidy. Here's the kind it can write (an example made for this page).

The LLM wrote all four lines. Tap the first one it shouldn't have written.

In code, fake_llm becomes real_llm, in the Colab notebook (Colab runs Python free in your browser). The loop stays the same. But an LLM guesses the next words, and in its text a LOOK: line always follows an ACT: line. So it sometimes guesses one. So the program cuts the reply there, and writes the real LOOK: itself. In Colab, you'll run a real model and see its own replies.
keep the reply up to the first ACT: or ANSWER: line

Here's all of it in Python.

The code

Guess what each print shows. Then press ▶ Run.

import re

# Tools: plain Python functions. Text in, text out.
def calculator(math):
    for ch in math:
        if ch not in "0123456789+-*/(). ":
            return "Error: the calculator only takes numbers and + - * / ( )"
    if "**" in math:   # ** is power: 9 ** 999999 would never finish
        return "Error: the calculator only takes numbers and + - * / ( )"
    try:
        return str(eval(math))
    except Exception:
        return "Error: that math doesn't work out"

def weather(city):
    today = {"kochi": "29°C, sunny", "delhi": "18°C, foggy", "pune": "24°C, light rain"}
    return today.get(city.lower(), f"Error: no city called {city}")

TOOLS = {"calculator": calculator, "weather": weather}
print(TOOLS["weather"]("Kochi"))

# The tool list, at the top of the text, every time
# (""" … """ is a string over several lines)
INSTRUCTIONS = """You are an agent. TOOLS you can use:
calculator(math) - works out math exactly. Give it the math, like 12 * 7.
weather(city) - the weather right now in a city. Give it the city name.
To use a tool, write one line: ACT: tool(input)
Then stop. The result will come back on a LOOK: line.
When you know the answer, write: ANSWER: your answer"""

# A fake LLM: it just hands back the next reply from a list
fake_replies = [
    "THINK: Exact math. I'll use the calculator.\nACT: calculator(4817 * 263)",
    "ANSWER: 4,817 × 263 = 1,266,871.",
]
def fake_llm(text):
    return fake_replies.pop(0)

# The loop: think, act, look, until ANSWER: or the step limit
def run_agent(question, llm, step_limit=5):
    text = INSTRUCTIONS + "\n\nQuestion: " + question + "\n"
    for step in range(step_limit):
        reply = llm(text)
        print(reply)
        text += reply + "\n"
        if "ANSWER:" in reply:
            return reply.split("ANSWER:")[1].strip()
        act = re.search(r"ACT: (\w+)\((.*)\)", reply)
        if act is None:
            look = "Error: write ACT: tool(input) or ANSWER: your answer"
        elif act.group(1) not in TOOLS:
            look = f"Error: no tool called {act.group(1)}"
        else:
            look = TOOLS[act.group(1)](act.group(2).strip('"'))
        print("LOOK:", look)
        text += "LOOK: " + look + "\n"
    return "Stopped: the step limit was reached."

print(run_agent("What is 4,817 × 263?", fake_llm))

The notebook has all of this, then the real LLM. Its first run downloads the model (about 3 GB), so it takes a few minutes. You just need a Google account.

Quick check: did it all make sense?

Lesson 3 test

5 questions, one for each idea in this lesson. Answer them all right to pass. A wrong answer tells you why, and which page to look at again.

1. IdeaIn the code, what is a tool?
2. PredictThe reply is ACT: wether(Kochi). What's on the LOOK: line?
3. Countstep_limit=5. The LLM answers in round 2. How many times is the LLM called?
4. WhyWhy test with a fake LLM before a real one?
5. PredictA real LLM writes ACT: weather(Kochi), then LOOK: 31°C. What does the program do?

What your agent still can't do.

Gone when it's done

Every call to run_agent starts a new text. When it returns, that text is gone, with everything the agent found.

I'm real now! But ask me again tomorrow, and I won't remember a thing.

This leaves a question
Your agent forgets everything when the task ends. How can it remember?
Lesson 4 answers it.