← Build an AI Agent Lesson 4 of 8

Memory

The text is its memory

How do I remember what I found two rounds ago? Let's see.

Tap a line to hide it from the LLM. See what it writes next.

The LLM keeps nothing in its head between writes. Each time, it reads the text from the top. What's in the text is all it knows.
memory during a task = the text
Hide the LOOK: line, and it asks for the weather again.

The text grows every round. Can it grow forever?

The text has a limit

Every round makes the text longer. But an LLM can only read so much text at once.

Add rounds. Then switch how the program makes room.
Rounds: 3
Words

That limit is its context window. Here it's 300 words. 60 (tool list) + 10 (question) + 4 rounds Γ— 50 = 270 fits. A 5th round makes 320: something must go. Keep the start, and drop the oldest rounds.
text = start + rounds Γ— words per round

Try it on new numbers.

✏️ Practice 4.1

New numbers, same ideas.
Remember: text = start + rounds Γ— words per round
The start is the tool list and the question. The text must fit in the context window.

Work each one out. Type the answer, press Check.
Tool list: 100 words. Question: 20. Each round: 40. How many words is the text after 3 rounds?
Same agent. The context window is 400 words. How many rounds fit?
Window: 250 words. Start: 70. Each round: 60. The program keeps the start. How many rounds can it keep?

Dropping old rounds loses what they found. Is there a better way?

Summaries save space

Three rounds of shopping prices. Squeeze them into one line.
Words

A summary keeps the facts and drops the rest. The program asks the LLM to write it, one extra write, then swaps it in for the old rounds. The LLM's next step is the same, with far fewer words.
summary = the facts, in fewer words

That's memory during one task. What about the next task?

Notes for next time

Yesterday the agent saved a note. Today's task starts a new text. Switch the notes off and on.
Yesterday: β€œI'm vegetarian. Please remember that.” β†’ ACT: save_note(The person is vegetarian.)

A new task starts a new text, so the old one is gone. Notes are saved outside the text, in a list. The program puts them at the top of every new text.
notes = memory between tasks
The note β€œThe person is vegetarian.” β†’ paneer tikka, not butter chicken.

Try it on new numbers.

✏️ Practice 4.2

New numbers, same ideas.
Remember: notes go at the top of every new text.
summary = the facts, in fewer words
Words saved = the old rounds' words βˆ’ the summary's words.

Work each one out. Type the answer, press Check.
The agent has 5 notes of 12 words each. How many words do they add to every new task?
The program keeps 120 words of room for notes. Each note is 12 words. How many notes fit?
3 rounds of 50 words each become a 20-word summary. How many words are saved?

Here's notes memory in Python.

The code

The notes list lives outside run_agent, so it survives between tasks. Guess what each print shows. Then press β–Ά Run.

import re

# Long-term memory: notes kept outside the text, in a list
notes = []

def save_note(note):
    notes.append(note)
    return "Saved."

TOOLS = {"save_note": save_note}

# The instructions now end with every note saved so far
def instructions():
    rules = """You are an agent. TOOLS you can use:
save_note(note) - remember something for next time. Give it the note.
To use a tool, write one line: ACT: tool(input)
When you know the answer, write: ANSWER: your answer
NOTES from earlier tasks:"""
    for note in notes:
        rules += "\n- " + note
    return rules

# A fake LLM that reads the text, so you can see the notes matter
def fake_llm(text):
    if "Question: I'm vegetarian" in text:
        if "LOOK:" not in text:
            return "THINK: That's worth remembering.\nACT: save_note(The person is vegetarian.)"
        return "ANSWER: Got it. I'll remember that."
    if "- The person is vegetarian." in text:
        return "ANSWER: How about paneer tikka? It's vegetarian, like you."
    return "ANSWER: How about butter chicken?"

# The same loop as Lesson 3. It also shows how long the text has grown.
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"
        print("(the text is now", len(text.split()), "words)")
        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."

# Task 1, before any notes
print(run_agent("Suggest a dinner for me.", fake_llm))
# Task 2: tell it something worth remembering
print(run_agent("I'm vegetarian. Please remember that.", fake_llm))
print(notes)
# Task 3: a brand new text, but the note is at the top
print(run_agent("Suggest a dinner for me.", fake_llm))

The notebook has all of this, then the same with the real LLM from Lesson 3. Its first run downloads the model (about 3 GB).

Quick check: did it all make sense?

Lesson 4 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. PredictThe program forgets to add the LOOK: 29Β°C, sunny line. What does the LLM write next?
2. Spot the mistakeTo fit the context window, a program cuts the oldest words, from the very top. What goes wrong?
3. WhyWhy swap old rounds for a summary instead of just dropping them?
4. IdeaHow does an agent remember something from yesterday's task?
5. CodeIn the code, what puts the notes into a new task's text?

What your agent still can't do.

Too big for one go

Your agent remembers now. But give it a big goal, like planning a party, and it can wander off or forget a part.

Party for ten, under β‚Ή5,000? Where do I even start?

This leaves a question
Big goals need many steps. How does an agent plan them?
Lesson 5 answers it.