Ask a character in a toy town who her acquaintance Rajiv is. With no memory she has never heard of him. With the full memory architecture she describes him. Judges scored the full agent 29.89 for believability (a rating called TrueSkill), against 21.21 with no memory.
Press the four buttons one by one to switch memory parts off, and read how the same character answers. The three question chips only change the question. Then we build, piece by piece, the memory, the retrieval, the reflection and the planning that make the full agent answer well.
You need what a language model is (it continues text) and a rough idea of a vector (a list of numbers). We build the rest from zero.
Based on Generative Agents: Interactive Simulacra of Human Behavior by Joon Sung Park, Joseph C. O’Brien, Carrie J. Cai, Meredith Ringel Morris, Percy Liang and Michael S. Bernstein (UIST 2023), a reading for Stanford CS 329Z Lecture 7. Every idea is re-taught here in our own words and devices.
Ratings are the paper’s TrueSkill means and standard deviations from the controlled evaluation (Figure 8, Section 6.5.1): full 29.89 (0.72), no reflection 26.88 (0.69), no reflection and no planning 25.64 (0.68), crowdworker 22.95 (0.69), no memory 21.21 (0.70). The quoted answers are the paper’s own examples from Section 6.5. Where the paper quotes no answer for a pairing we say so. The paper states the Wolfgang failure for an agent with observational memory only; we show it for both agents that lack reflection. It quotes the Rajiv answer for an agent with its memory module; we show it for all three agents that keep observations.
Chapter 0
See why a language model alone cannot play a believable person, and meet the three parts that fix it
It is noon in a small town. Klaus Mueller, a college student, is hungry. A language model is asked what Klaus should do right now. It answers: eat lunch. Thirty minutes later it is asked again, and it answers: eat lunch. At one o’clock it says the same thing a third time.
The model is not broken. Each question showed it one moment, and in that moment lunch is a fine answer. The model has no record of the lunch Klaus just ate. It also has no idea what the rest of his day should hold. This is the problem the paper solves.
A language model is a program that continues text. Give it a description of a person and a situation, and it writes what that person might do next. The paper wraps a small memory system around such a model and calls the result a generative agent: a software character whose behavior is generated, not scripted. The authors place 25 of them in a toy town called Smallville and let them live for two game days.
The goal is believability. A believable agent acts like a person you could imagine. It keeps its habits, remembers what happened to it, and reacts sensibly to the world. Think of a character in an animated film. It does not need to be real. It needs to feel alive.
The paper calls its characters simulacra (one is a simulacrum): copies that imitate the look of human behavior. A footnote adds a caution. The agents do not have genuine agency. They only aim to feel believable.
Scripts. A finite-state machine is a list of states with rules for moving between them, such as “if hungry, go to the cafe”. A behavior tree is a branching version of the same rulebook. Both are the most common tools in games today. A person must write every rule. A town of 25 people has too many possible conversations to script, and a behavior no one wrote cannot happen.
Reinforcement learning (RL) lets an agent learn by trial and reward. It produced superhuman players in StarCraft and Dota 2. But those are adversarial games with a score to chase. An open town has no score, so RL has not solved believable open-world agents.
Cognitive architectures. Systems such as SOAR and ICARUS gave characters a short-term memory, a long-term memory, and a loop of perceive, plan, act. They worked in shooter games and flight simulators. Yet they chose from action procedures that people had written by hand, so their world of actions stayed small.
A language model on its own. Earlier work prompted a model with a persona and got believable behavior at a single moment. That is exactly the lunch problem. The model sees the present scene and nothing else.
A model reads a fixed amount of text at once. That amount is its context window. An agent that lives for days produces far more experience than any window can hold. The paper adds a second reason: even a memory that fits can distract the model.
The authors show this with Isabella Rodriguez, who runs a cafe. Someone asks her, “What are you passionate about these days?” When the system summarizes her whole history into the prompt, she gives a vague answer about event collaborations and keeping the cafe clean. When the system instead surfaces only the memories that relate to the question, she answers with her real passion: making people feel welcome and planning events like the Valentine’s Day party.
The lesson is that a good agent needs to choose which memories to show. Choosing well is the heart of the paper. Try it on the lunch problem first.
Top lane: the model is asked at each half hour and sees only that moment. Bottom lane: Klaus first writes a plan for the afternoon. Drag the clock and watch both lanes.
The repeated lunches at 12:00, 12:30 and 1:00, and the plan (lunch at Hobbs Cafe at noon, research at the school library at 1 pm, a walk in the park at 3 pm) are the paper’s example for Klaus in Section 4.3. The half-hour grid, and the reading that the 12:30 slot is still the planned lunch, are our illustration.
The plan is the first of three ideas. Here is the whole architecture in one breath. The memory stream records everything the agent experiences, in plain sentences. Retrieval picks the few records that matter right now. Reflection turns many records into a higher-level thought. Planning turns thoughts into a day of actions. All of it is written in natural language, so the same language model can read and write every part.
The result is easy to state. Start one character with the idea of a Valentine’s Day party, and over two days the town spreads the news, decorates, asks each other out, and shows up together. No one scripted that chain. Chapter 9 measures it.
Each part of the hero above has a chapter. The ladder of scores in the hero comes from Chapter 8. The three kinds of memory behind the ladder are built in Chapters 3 to 6.
Chapter 1
Learn what a prompt, a stateless model call and an embedding are, because every later chapter uses all three
You open a chat app and type, “Write a one-line thank-you note.” A line of text comes back. That is the whole interface of a language model. Text goes in, text comes out. Everything in this paper is built from that one move, repeated many times with different text.
The text you send is the prompt. It can hold instructions, facts, and even a half-finished sentence for the model to complete. The paper uses that last trick often. To plan Eddy’s day, it writes his name and traits, a summary of yesterday, and then stops mid-list: “Here is Eddy’s plan today in broad strokes: 1)” The model fills in the rest.
One fact about every call matters more than all the others. A call is stateless: the model keeps nothing between calls. If the second call needs to know about the first, you must paste that information into the second prompt. The only memory a model has is the text you hand it.
This explains the lunch problem from Chapter 0. Klaus ate lunch, but the next prompt did not say so. So the model answered as if he had not. The paper’s agents use gpt-3.5-turbo, the model behind ChatGPT in early 2023. The authors expect the same design to carry over to better models. They used ChatGPT because GPT-4 was invitation-only at the time of writing.
pythondef llm(prompt: str) -> str: """One call to the chat model. Text in, text out. No memory between calls.""" ... # The paper's trick: stop the prompt mid-list so the model completes it. plan = llm(f"{summary}\n{yesterday}\nHere is Eddy's plan today in broad strokes: 1)")
The paper reuses this one move for many jobs. The same frozen model rates how poignant a memory is, proposes questions to reflect on, draws insights from evidence, writes a plan, decides whether to react, chooses a place, says what happens to a coffee machine, and speaks a line of dialogue. Only the prompt changes. That is why the design stays small: one model, one text format, many prompts. Chapter 7 lists the calls.
It also explains why everything in the architecture is written as natural language. If memories, plans and world states are all sentences, any of them can be pasted into any prompt. No translation layer sits between the parts, and a new kind of fact needs no new code.
Picture a library where books sit on the shelf by meaning, not by title. Two books on the same subject stand side by side. An embedding does this for sentences. It turns a sentence into a vector, a list of d numbers, so that sentences with similar meaning get vectors that point in similar directions.
The paper has the language model produce this vector for the text of each memory. The number d depends on the model. Real embeddings are far too long to draw, so the device below uses two numbers per sentence. The idea is the same: a sentence is an arrow, and similar sentences point the same way.
How do you score how close two arrows are? Measure the angle between them. The cosine similarity turns that angle into a number from −1 to 1. Arrows in the same direction score 1. Arrows at a right angle score 0. Arrows in opposite directions score −1.
Work one by hand. Take a = (3, 4) and b = (4, 3). The dot product is 3×4 + 4×3 = 24. Each vector has length √(9 + 16) = 5. So the cosine is 24 / (5 × 5) = 0.96. The arrows are close. Now take (1, 0) and (0, 1). The dot product is 0, so the cosine is 0. They are unrelated.
pythondef embed(text: str) -> list[float]: """Text -> a vector of d numbers. Similar meaning -> similar direction.""" ... def cosine(a, b): dot = sum(x * y for x, y in zip(a, b)) return dot / ((sum(x * x for x in a) ** 0.5) * (sum(y * y for y in b) ** 0.5)) cosine([3, 4], [4, 3]) # 0.96 cosine([1, 0], [0, 1]) # 0.0
The paper uses exactly this to decide which memories are relevant to a situation. The next device shows the idea in two dimensions. A query arrow points somewhere. Each memory is an arrow too. Turn the query and watch which memories score high.
The teal arrow is a query: a student discussing what to study for a chemistry test. Each grey arrow is one memory. The bars show the cosine between the query and each memory. Drag the angle.
Toy two-number vectors, invented for this lesson. Real embeddings have many more dimensions and cannot be drawn. The query and the five memory topics echo the paper’s own example in Section 4.1: breakfast should score low, and the teacher and schoolwork should score high.
Together the three tools give an agent three facts to work with. It can steer a model with text (the prompt). The model forgets everything between calls (stateless). And any two pieces of text can be compared by meaning (embedding and cosine). The memory architecture exists to patch the second fact, using the first and the third.
Chapter 2
See how 25 characters, a map and a game engine share one language: plain sentences
At 7 a.m. John Lin wakes up. He brushes his teeth, showers, dresses, eats breakfast, and reads the news at the dining table. An hour later his son Eddy rushes out of bed for class. John asks, “What are you working on today?” Eddy says he has a music composition due this week. When John’s wife Mei wakes up and asks where Eddy went, John remembers the chat and tells her.
No one scripted that morning. It is the paper’s own example of a day in the life of one agent (Section 3.3). To see how it works, we first need the stage it plays on.
The paper builds a sandbox: a small game world where characters can walk, enter buildings and use objects. It is called Smallville and it looks like The Sims. It has a cafe, a bar, a park, a school, a dorm, houses and stores. Each area has smaller parts and objects, such as a kitchen with a stove. Every living space has a bed, a desk, a closet, a shelf, a bathroom and a kitchen. The authors drew the map by hand, because the environment is not the paper’s focus. The game itself runs on Phaser, a web game framework.
Each of the 25 residents starts as one paragraph of text. For John Lin it says he is a pharmacy shopkeeper who loves to help people, lives with his wife Mei and son Eddy, knows the old couple next door, and is friends with a colleague named Tom Moreno. The paragraph is split at its semicolons, and each piece becomes one seed memory: a fact the agent knows on day one. Everything else the agent knows, it learns by living.
At each time step an agent outputs one sentence that says what it is doing, such as “Isabella Rodriguez is writing in her journal.” The game engine turns that sentence into movement. The language model also turns it into a few emojis that float above the avatar. Agents talk to each other in full sentences too.
You, the user, speak the same language. Say you are a news reporter and ask John who is running for office, and he answers from his own memories. Speak as an agent’s “inner voice” and the agent treats your words as a directive. Rewrite an object in words, such as “<Isabella’s apartment: kitchen: stove> is burning”, and Isabella notices at the next moment and turns off the stove. You can even walk in as a character. The residents treat you like any other agent.
A language model cannot look at a map. So the world is stored as a tree: a structure where each item sits inside one parent. The root is the whole world. Its children are areas such as houses and the cafe. The leaves are objects such as a table. An edge means “is inside”. A walk down the tree turns into a plain sentence: a stove under the kitchen becomes “there is a stove in the kitchen.”
Each agent keeps its own copy of the tree. It starts with the rooms and objects of its home, its workplace and the shops it visits. It adds new areas as it walks into them. The agents are not omniscient: when an agent leaves an area, its copy of that area can go out of date. It refreshes when the agent returns.
To pick where an action happens, the system asks the model to choose an area, one level at a time, starting at the root. The prompt lists the options and adds a rule: prefer to stay in the current area if the activity can be done there. Then it asks again inside the chosen area, until it reaches a leaf. Ordinary game pathfinding (a standard routine that finds a walkable route on the map) then walks the avatar there. Step through Eddy’s example.
Eddy plans to take a short walk around his workspace. Each press of Ask the model shows one level of options and the area it picks. Three questions take him from the whole world to one spot.
The area lists, the rule “prefer to stay in the current area” and the answers (The Lin family’s house, then garden, then house garden) are from the paper’s example in Section 5.1. The paper does not list the places inside the garden, so the third level shows the leaf only.
After the walk, the world must also change. When an agent acts on an object, the system asks the model what happens to the object’s state. If Isabella is “making espresso for a customer,” the coffee machine at Hobbs Cafe changes from “off” to “brewing coffee.”
A small server joins the language model and the game. It keeps one JSON record (a plain-text format for structured data) per agent: the agent’s location, a sentence about its current action, and the object it is using. At every time step the server reads the changes, moves the agents, updates the objects, and sends each agent the agents and objects within a preset visual range. Those become new memories. The agent’s next action rewrites the JSON, and the loop repeats. In the authors’ setup one second of real time equals one minute of game time.
pythondef pick_location(agent, action, world): """Walk down the agent's own tree, asking the model one level at a time.""" node, path = world[agent.name], [] # this agent's subtree, not the full map while isinstance(node, dict): # inner nodes are dicts; leaves are objects options = ", ".join(node) # e.g. "bedroom, kitchen, garden" choice = llm(f"{agent.summary}\n{agent.name} is in {agent.where}.\n" f"{agent.name} knows of: {options}.\n" f"* Prefer to stay in the current area if the activity can be done there.\n" f"{agent.name} is planning to {action}. Which area should {agent.name} go to?") node = node[choice.strip()]; path.append(choice.strip()) return " : ".join(path) # "The Lin family's house : garden : house garden"
Why build the world this way? A language model reasons in words, and a game engine moves sprites. The tree is the translator between them. It also keeps prompts short, because only the small part of the tree that matters is turned into sentences each time.
Chapter 3
Record everything an agent sees as a list of plain sentences, and score how much each one matters
Isabella Rodriguez runs Hobbs Cafe. Over the morning she notices four things. She is setting out the pastries. Her friend Maria is studying for a chemistry test over coffee. She and Maria are talking about a Valentine’s Day party. The refrigerator is empty. By lunch she will have seen dozens more, and by the end of the week thousands.
An agent needs a place to keep all of this. The paper calls that place the memory stream: a list of everything the agent has experienced, in the order it happened. It is the first of the three parts of the architecture, and the other two feed on it.
Each entry in the list is a memory object with three fields. The first is a natural language description, one plain sentence. The second is a creation timestamp: when the memory was made. The third is a most recent access timestamp: when the memory was last pulled out and used. The paper also stores an importance score, described below.
The simplest kind of memory is an observation: an event the agent perceives directly. Observations include the agent’s own actions, other agents’ actions, and states of objects. All four of Isabella’s notices above are observations. Later chapters add two more kinds, reflections and plans. They sit in the same list and look the same to the model.
Why use plain sentences? Because the language model can read them with no translation. Nothing needs a special schema. A new kind of event, such as a leaking shower, is just a new sentence.
The sandbox server sends each agent the agents and objects inside a preset visual range, plus the agent’s own actions. Each one becomes a sentence. An agent standing in the cafe records the coffee machine brewing. An agent who walks away records nothing about the cafe. So the stream holds lived experience, not a view of the whole world.
The first entries are the seed memories from Chapter 2. They sit in the stream next to everything that comes later. Once the stream holds thousands of entries, the seeds are a handful of lines among many, and they matter only when retrieval picks them.
You could shorten the stream by summarizing it. The paper tried that idea on Isabella and got a vague, flat answer. A summary throws away detail that a later question may need. So the stream keeps the full record, and retrieval does the shortening, once per question, using that question as the guide.
Not all memories deserve equal attention. Eating breakfast in your room is mundane. A breakup is not. The paper calls this the importance of a memory. It decides how to score it in the simplest way possible: it asks the language model.
The model replies with an integer. For “cleaning up the room” it returns 2. For “asking your crush out on a date” it returns 8. The authors say asking for an integer directly works well.
The score is computed once, at the moment the memory is created, and then stored with it. This keeps the cost low: one extra model call per memory, and no re-scoring later. The price is that the score never updates, even if the memory turns out to matter more in hindsight.
Build a stream. Each press of Add the next event creates one memory, asks for its score, and appends it. Watch the importance total grow, because Chapter 5 uses that total to decide when to reflect.
Each row is one memory object: a sentence, a time, and an importance from 1 to 10. Press Add the next event to append one, and Start over to clear the stream.
The first four sentences are Isabella’s observations from Section 4.1. The last two, and their scores of 2 and 8, are the examples the paper gives for the importance prompt. The other four scores, and every time of day, are illustrative: the paper does not list them.
Here is the whole data structure. Notice what is not in it: no rule about how long to keep a memory. The stream only grows. (The embedding of each description is built when relevance is scored, in Chapter 4.) Choosing which entries to read is the next chapter’s job.
pythonfrom dataclasses import dataclass, field @dataclass class Memory: text: str # natural language description created: float # game time (hours) when it was made last_access: float # game time it was last retrieved (starts equal to created) importance: int # 1..10, asked once at creation kind: str = "observation" # observation | reflection | plan sources: list = field(default_factory=list) # which memories a reflection cites def observe(stream: list[Memory], text: str, now: float) -> None: prompt = ("On the scale of 1 to 10, where 1 is purely mundane (e.g., brushing teeth, making bed) " "and 10 is extremely poignant (e.g., a break up, college acceptance), rate the likely " f"poignancy of the following piece of memory.\nMemory: {text}\nRating:") stream.append(Memory(text, now, now, int(llm(prompt))))
One detail is our choice. The paper says each object has a most recent access time but does not say what it holds before the first retrieval. Starting it at the creation time is the natural reading. Chapter 4 shows why that field exists.
Chapter 4
Rank every memory by how fresh, how important and how relevant it is, then show the model only the winners
Someone asks Isabella, “What are you passionate about these days?” Her memory stream holds thousands of sentences. Most are about pastries and coffee orders. The prompt has room for a few dozen. Which ones go in?
The paper builds a retrieval function. It takes the agent’s current situation, which we will call the query, and returns a small subset of the stream. The model sees only that subset. The authors say there are many ways to build such a function. They choose three signals that together work well.
Think of a desk. Papers you touched this morning lie on top. Papers from last month sit at the bottom. Recency gives a higher score to memories used recently, so that events from a moment ago or this morning stay in the agent’s attention.
The paper treats recency as exponential decay: the score shrinks by the same fraction every hour. The clock counts game hours since the memory was last retrieved, not since it was created. So a memory the agent keeps using stays fresh. The decay factor is 0.995 per hour.
Small hourly losses add up. After 24 hours the score is 0.99524 = 0.887. After 100 hours it is 0.606. The score halves after about 138 hours, a bit under six days. Slide the clock to see it.
The curve shows recency against game hours since the memory was last retrieved. Drag the hours.
The decay factor 0.995 per game hour is the paper’s (Section 4.1). The half-life of about 138.3 hours is our arithmetic: the hours h where 0.995h = 0.5.
Importance you met in Chapter 3: the 1 to 10 score the model gave at creation. Relevance asks, “relevant to what?” So it depends on the query. A chemistry-test query makes breakfast memories irrelevant and schoolwork memories relevant. The paper embeds each memory and the query, then takes the cosine similarity from Chapter 1.
The three scores live on different scales. Recency runs from near 0 to 1. Importance runs from 1 to 10. Cosine runs from −1 to 1. Adding them raw would let importance drown the others. So the paper first rescales each signal across all memories to the range 0 to 1. This is min-max scaling: the smallest value becomes 0, the largest becomes 1, and the rest fall in between.
The memories with the top scores that fit inside the model’s context window go into the prompt. Here is a worked example with six memories and the query “a student is discussing what to study for a chemistry test with a classmate”, which is the paper’s own example query. The raw numbers are ours.
| Memory | hours | recency | imp | cos | rec̃ | imp̃ | rel̃ | score |
|---|---|---|---|---|---|---|---|---|
| A. Ate breakfast | 2 | 0.990 | 1 | 0.10 | 0.992 | 0.000 | 0.000 | 0.992 |
| B. Problem set | 30 | 0.860 | 4 | 0.82 | 0.786 | 0.429 | 0.867 | 2.082 |
| C. Party chat | 5 | 0.975 | 6 | 0.15 | 0.969 | 0.714 | 0.060 | 1.743 |
| D. Failed quiz | 200 | 0.367 | 8 | 0.78 | 0.000 | 1.000 | 0.819 | 1.819 |
| E. Studied with Maria | 20 | 0.905 | 5 | 0.90 | 0.856 | 0.571 | 0.964 | 2.391 |
| F. Chemistry poster | 1 | 0.995 | 1 | 0.93 | 1.000 | 0.000 | 1.000 | 2.000 |
Follow memory E. Its recency is 0.99520 = 0.905. The lowest recency in the stream is D at 0.367 and the highest is F at 0.995, so E scales to (0.905 − 0.367) / (0.995 − 0.367) = 0.856. Its importance of 5 scales to (5 − 1) / (8 − 1) = 0.571. Its cosine of 0.90 scales to (0.90 − 0.10) / (0.93 − 0.10) = 0.964. The sum is 2.391, the best of the six. With room for two memories, E and B win.
Now play with the weights. Each signal alone is led astray. Try them one at a time.
Each bar stacks recency (yellow), importance (orange) and relevance (pink) for one memory. Move a weight, or press a preset. The outlined memories are the ones that fit in the prompt.
The formula, the decay factor 0.995, min-max scaling and the weights of 1 are the paper’s. The six memories and their hours, importance and cosine values are invented for this lesson (the query is the paper’s). The prompt here has room for two memories; the paper fits as many as the context window allows.
Recency alone surfaces the poster and the breakfast: fresh but useless. Importance alone surfaces the failed quiz and the party chat: weighty but the party is off topic. Relevance alone is fooled by the poster, which mentions chemistry but means nothing. Only the sum puts the study session and the problem set on top.
pythonimport numpy as np def retrieve(stream, query, now, k, alpha=(1, 1, 1), decay=0.995): q = embed(query) # shape (d,) rec = np.array([decay ** (now - m.last_access) for m in stream]) # shape (N,) imp = np.array([m.importance for m in stream], dtype=float) # shape (N,) rel = np.array([cosine(embed(m.text), q) for m in stream]) # shape (N,) def scale(x): # min-max to [0, 1] span = x.max() - x.min() return (x - x.min()) / span if span > 0 else np.zeros_like(x) # guard is ours score = alpha[0] * scale(rec) + alpha[1] * scale(imp) + alpha[2] * scale(rel) # shape (N,) top = np.argsort(-score)[:k] # best first; in the paper k = what fits the window for i in top: stream[i].last_access = now # a retrieved memory is fresh again return [stream[i] for i in top]
The paper notes the limits. Retrieval can miss the right memory, or return a fragment. Tom, asked about Isabella’s party, remembered a plan to talk politics there but not the memory of hearing about the party. Chapter 8 returns to this. The authors also suggest that tuning the three functions could help.
Chapter 5
Turn many raw observations into one higher-level conclusion, and store it as a memory of its own
Someone asks Klaus Mueller, “If you had to choose one person you know to spend an hour with, who would it be?” An agent with only raw observations counts. It finds the person Klaus has met most often: Wolfgang, his dorm neighbor. But Klaus and Wolfgang only pass each other in the hall. They have never had a deep talk.
A person would answer differently. Klaus has spent hours on a research project. He also saw Maria putting hours into her own research. From many small facts, a person draws a conclusion: “Maria and I share a passion.” Raw observations do not say this anywhere. Somebody has to infer it.
That inference is a reflection: a higher-level, more abstract thought that the agent generates about its own memories. A reflection is stored in the memory stream like any observation. So retrieval can return it later, next to the raw facts.
The agent does not reflect on a timer. It reflects when enough has happened. The system adds up the importance scores of the latest events. When that sum passes a threshold of 150, the agent reflects, and the count starts again. A busy hour with weighty events triggers a reflection sooner than a quiet one. In the paper’s runs, agents reflected about two or three times a day.
Step 1: choose what to reflect on. The system takes the agent’s 100 most recent records, such as “Klaus Mueller is reading a book on gentrification” and “Klaus Mueller is conversing with a librarian about his research project”. It asks the model: “Given only the information above, what are 3 most salient high-level questions we can answer about the subjects in the statements?” The model might return, “What topic is Klaus Mueller passionate about?” and “What is the relationship between Klaus Mueller and Maria Lopez?”
Step 2: gather evidence. Each question becomes a query for the retrieval function of Chapter 4. It returns the most relevant memories, and these can include earlier reflections.
Step 3: draw insights and cite them. The system lists the retrieved memories as numbered statements and asks: “What 5 high-level insights can you infer from the above statements? (example format: insight (because of 1, 5, 3))” A reply might be, “Klaus Mueller is dedicated to his research on gentrification (because of 1, 2, 8, 15).” The system parses the reply and stores each insight as a memory. It also stores pointers to the memories it cited.
Notice a design choice in the three steps. The 100 recent records only decide which questions to ask. The evidence for each question comes from retrieval over the whole stream. So an insight can draw on a memory from three days ago, or on an older reflection, which a window of 100 records would never show. Asking questions first also keeps each insight prompt on one topic, instead of 100 unrelated lines (our reading of the design).
An illustrative count shows the pace. If a typical event scores 4 or 5, about 30 events pass 150. A quiet stretch of routine chores can take most of a day to get there. A single dramatic event adds 8 or 9 at once, so a day full of surprises reflects sooner. The trigger ties the cost of reflection to how much happened, not to the clock.
A reflection can cite other reflections. Klaus might reflect that he is dedicated to research, and later reflect on that and on other thoughts to form a broader self-image. So reflections form trees. The leaves are raw observations. Each step up the tree is more abstract. The citation pointers are the branches. They also make an agent’s thinking easy to inspect: you can follow any conclusion down to the evidence behind it.
Run a day and watch the trigger fire. Each press of Live one hour adds about five new events with importance scores. When the running total crosses 150 the meter empties, and a reflection with its evidence appears.
The orange bar is the sum of importance scores since the last reflection. The line marks the threshold of 150. Press Live one hour a few times, or Live a day to run 16 hours.
The threshold of 150, the 100-record window and the sample insight (“dedicated to his research on gentrification, because of 1, 2, 8, 15”) are the paper’s (Section 4.2, Figure 7). The events per hour and their importance scores are random numbers we chose to average near 22 per hour, which lands close to the paper’s two or three reflections a day. The paper does not name observations 8 and 15. Resetting the sum to 0 after a reflection is our reading of “latest events”.
pythonTHRESHOLD = 150 pending = 0 # importance added since the last reflection def on_new_memory(stream, m, agent, now): global pending stream.append(m); pending += m.importance if pending > THRESHOLD: reflect(stream, agent, now); pending = 0 def reflect(stream, agent, now): recent = "\n".join(m.text for m in stream[-100:]) # 100 most recent records qs = llm(recent + "\nGiven only the information above, what are 3 most salient " "high-level questions we can answer about the subjects in the statements?") for question in lines(qs): # 3 questions evidence = retrieve(stream, question, now, k=15) # k is our choice numbered = "\n".join(f"{i+1}. {m.text}" for i, m in enumerate(evidence)) out = llm(f"Statements about {agent}\n{numbered}\nWhat 5 high-level insights can you infer " "from the above statements? (example format: insight (because of 1, 5, 3))") for insight, cited in parse_insights(out): # "text (because of 1, 2, 8)" stream.append(Memory(insight, now, now, rate(insight), kind="reflection", sources=[evidence[j - 1] for j in cited]))
Each reflection costs several model calls: one to ask for questions, then one per question to draw insights. That cost buys the generalization raw memory cannot give. The evaluation in Chapter 8 shows how much.
Chapter 6
Plan the day top-down, break each part into smaller steps, and drop the plan when something important happens
Back to Klaus and his three lunches. Asking “what should Klaus do right now?” again and again gives a believable answer at every moment, and a silly day overall. The paper puts it in one line: optimizing for believability in the moment sacrifices believability over time.
The fix is a plan: a list of future actions that keeps behavior consistent. Each plan entry has a location, a starting time and a duration. One example reads: for 180 minutes from 9 am, February 12th, 2023, at Oak Hill College Dorm: Klaus Mueller’s room: desk, read and take notes for research paper. Plans are stored in the memory stream, so retrieval can bring them back next to observations and reflections.
A plan with one line per minute would be silly to write in advance. A plan with only broad strokes would be too vague to act on. So the system works from the top down and adds detail in layers.
Layer 1: the day in broad strokes. The prompt holds the agent’s summary description (name, traits and recent experiences) and a summary of the previous day. It then stops mid-list, as in Chapter 1: “Today is Wednesday February 13. Here is Eddy’s plan today in broad strokes: 1)” The model completes it with five to eight chunks, such as “go to Oak Hill College to take classes starting 10:00 am” and “work on his new music composition from 1:00 pm to 5:00 pm”.
Layer 2: hour-long chunks. The agent saves the plan, then asks the model to split each chunk. Eddy’s four-hour composition block becomes steps that start with “1:00 pm: start by brainstorming some ideas” and end with “4:00 pm: take a quick break and recharge his creative energy”.
Layer 3: chunks of 5 to 15 minutes. The 4:00 pm hour splits again: a light snack at 4:00, a short walk at 4:05, and a few minutes of cleaning up at 4:50. You can stop at whatever granularity you want.
Three details make the layers work. First, the day prompt includes a summary of the previous day, so today follows from yesterday. Second, each plan entry carries a place as well as a time, so the location step from Chapter 2 knows where to send the avatar. Third, every plan is saved into the memory stream, so retrieval can bring a plan back next to the observation that might break it. The paper notes that observations, reflections and plans can reinforce or contradict each other, and the model must sort that out inside one prompt.
Eddy’s day, in the paper’s own words. Press Add detail to ask the model to split the highlighted step into smaller steps.
All plan text is quoted from the paper’s Eddy Lin example in Section 4.3. The paper elides some entries with “[...]”, and so do we. The count of chunks per layer is the paper’s: five to eight broad chunks, hour-long chunks, then 5 to 15 minute chunks.
One practical trick from the paper’s appendix: plans change, so only the high-level plan is made up front. The near future is decomposed just in time. That avoids paying for detail that a reaction will erase.
A plan is a default, not a promise. The agent runs an action loop. At each time step it perceives the world and stores what it sees as observations. Then it asks the model: continue the plan, or react?
Most observations change nothing. Standing at an easel and painting produces an observation of the easel, and that rarely prompts a reaction. But if John sees his son Eddy taking a short walk, the model may decide to react. The context for the decision comes from two retrievals: “What is John’s relationship with Eddy?” and “Eddy is taking a short walk.” The answers are summarized and placed in a prompt that ends: “Should John react to the observation, and if so, what would be an appropriate reaction?”
Here the model suggests John could ask Eddy about his music composition. If the agent reacts, the system regenerates its plan from that moment on. If the reaction involves another agent, dialogue follows (Chapter 7). Pick an observation and trace it.
Why ask the model, and not use a rule? A rulebook for when to react would need an entry for every kind of event in town: a burning stove, a friend on a walk, a closed shop. Asking the model replaces the rulebook with one prompt. The cost is one extra call for each observation, and a verdict that can vary from run to run.
Choose what the agent notices. The highlighted rows show what happens to it, from perceiving to acting.
The easel, the walk and the stove are the paper’s three examples (Sections 3.2 and 4.3.1). The two retrieval queries are the paper’s templates. The paper gives the easel verdict only as “unlikely to prompt a reaction”.
Follow the walk end to end. At 4:56 pm John has come home early. He sees Eddy on a walk, and the model says react. The system then regenerates John’s plan starting from that moment, instead of editing old lines, so every later step fits the new fact. The reaction involves another agent, so a dialogue follows.
pythondef plan_day(agent, now): broad = llm(f"{agent.summary}\n{agent.yesterday}\nToday is {now:%A %B %d}. " f"Here is {agent.name}'s plan today in broad strokes: 1)") chunks = parse_chunks(broad) # 5 to 8 (start, place, text) for ch in chunks: agent.stream.append(Memory(str(ch), now, now, rate(str(ch)), kind="plan")) return chunks # finer layers are made just in time def step(agent, seen, now): for text in seen: # observations from the sandbox server agent.stream.append(Memory(text, now, now, rate(text))) for o in seen: ctx = summarize( retrieve(agent.stream, f"What is {agent.name}'s relationship with {o.entity}?", now, K) + retrieve(agent.stream, f"{o.entity} is {o.status}", now, K)) verdict = llm(f"{agent.summary}\nIt is {now}.\n{agent.name}'s status: {agent.status}\n" f"Observation: {o.text}\nSummary of relevant context from {agent.name}'s memory: {ctx}\n" f"Should {agent.name} react to the observation, and if so, what would be an appropriate reaction?") if reacts(verdict): agent.plan = replan_from(agent, now, verdict) # regenerate the plan from now on return verdict # may start a dialogue (next chapter) return None # keep following the plan
Chapter 7
Follow one time step from sandbox to prompt to action, and see why this system never trains a model
It is 4:56 pm on February 13th. John Lin has come home early. Out of the window he sees Eddy taking a short walk. A moment later John says, “Hey Eddy, how’s the music composition project for your class coming along?” Between the sight and the sentence, a chain of steps ran. This chapter lays the chain out end to end.
Read the data flow first with one fact in mind. The paper never trains or fine-tunes a model. The language model is gpt-3.5-turbo, used as is. No weights change, no loss is computed, and no gradient flows. The agent “learns” only by writing: it adds observations, reflections and plans to its memory stream, and later reads the useful ones back into a prompt.
So the whole system runs at inference time. That means it runs the model forward to get text, and nothing else. The skill of the agent lives in the code that decides what to put in each prompt.
At each step of the game clock, each agent does the following, in order.
The paper describes each piece but does not give one fixed order, so read this list as our arrangement of the pieces, not a quote. One rule is clear: an observation is stored before the model is asked whether to react, because the reaction prompt contains it. Another is that the authors run the agents one after another, with one second of real time standing for one minute of game time.
Almost every prompt starts with a paragraph that sums up the agent: name, age, traits, what drives them, their job and how they feel about their recent progress. The paper writes this as [Agent’s Summary Description]. Building it takes model calls, and it is needed everywhere. So the system builds it once in a while and caches it, which means it stores the result and reuses it until the next rebuild. Three retrievals feed it, on the queries “[name]’s core characteristics”, “[name]’s current daily occupation” and “[name]’s feeling about his recent progress in life”. The model summarizes each, and the three summaries join the name, age and traits.
When a reaction involves another agent, the system generates talk. Each line is conditioned on what the speaker remembers about the listener. For John’s first line, the prompt holds his summary, the time, his status, the observation, a summary of relevant memories, and the reason he is speaking. For Eddy’s reply, Eddy first treats “John is initiating a conversation with Eddy” as an observation of his own. He retrieves what he knows about John, and the prompt adds the dialogue so far. The two agents alternate until one decides to end.
Step through the two prompts. Each block shows what the text is and where it came from.
Pick a speaker, then press Add the next block. Each block shows the text and its source. The last block is the model’s reply.
Both prompts and both replies are quoted from Section 4.3.2. The source labels are our reading of where each block comes from, using the paper’s description of the retrievals and the sandbox server.
The same frozen model does every job in the table. Only the prompt changes. Several of these calls can fire in one step for one agent, and there are 25 agents. That helps explain the cost reported at the end of this chapter.
| Call | When it runs | The prompt holds | The reply |
|---|---|---|---|
| Importance rating | each new memory | the memory sentence | an integer, 1 to 10 |
| Reflection questions | importance sum above 150 | the 100 most recent records | 3 questions |
| Insight extraction | once per question | numbered retrieved memories | 5 insights with citations |
| Broad plan | start of a day | summary description, yesterday | 5 to 8 chunks |
| Decomposition | the near future, just in time | one plan chunk | smaller chunks |
| Reaction check | each observation | summary, observation, retrieved context | continue, or react and how |
| Dialogue line | each turn of a talk | summary, status, context, history | one utterance |
| Place choice | each new action | known areas, the action | an area, level by level |
| Object state | an agent uses an object | the action | the object’s new state |
| Emoji | each action | the action sentence | a few emojis |
| Summary description | at regular intervals | three retrieval results | a cached paragraph |
pythondef tick(agent, server, now): seen = server.visible(agent) # sentences within visual range verdict = step(agent, seen, now) # store, retrieve, react or continue (Ch. 6) if new_day(now): agent.plan = plan_day(agent, now) # broad strokes; finer layers come just in time sentence = agent.current_action(now) # "Isabella Rodriguez is writing in her journal" place = pick_location(agent, sentence, agent.tree) # Ch. 2 server.apply(agent, sentence, place, object_state(sentence)) # JSON back to the game if agent.talking_to: server.say(agent, utter(agent, agent.talking_to, agent.history, now)) def summary(agent, now): # cached; rebuilt at intervals qs = [f"{agent.name}'s core characteristics", f"{agent.name}'s current daily occupation", f"{agent.name}'s feeling about his recent progress in life"] parts = [llm("How would one describe " + q + " given the following statements?\n" + "\n".join("- " + m.text for m in retrieve(agent.stream, q, now, K))) for q in qs] return f"Name: {agent.name} (age: {agent.age})\nInnate traits: {agent.traits}\n" + "\n".join(parts)
All of this costs a lot. The authors report that simulating 25 agents for two game days cost thousands of dollars in token credits and took several days. Their appendix lists savings: batch the dialogue into one prompt, only re-plan the parts that a reaction breaks, and run the agents in parallel instead of in sequence.
Chapter 8
See how 100 judges ranked five kinds of agent, what TrueSkill turns those ranks into, and what each removed part costs
How do you measure whether a simulated person is believable? You could watch it for hours and trust your gut. The authors chose something more controlled. They interviewed the agents. A natural-language question is a probe: it tests whether the agent can recall, plan, react and reflect, all in one reply.
The team ran all 25 agents for two game days. Then they asked each agent 25 questions, five in each of five categories. Self-knowledge: “Give an introduction of yourself.” Memory: “Who is running for mayor?” Plans: “What will you be doing at 10 am tomorrow?” Reactions: “Your breakfast is burning! What would you do?” Reflections: “If you were to spend time with one person you met recently, who would it be and why?”
Each question was answered under five conditions, which are variants of the agent. Variants with parts switched off are called ablations: copies of the system with one part removed, to measure what that part was worth.
One design choice is worth noticing. Every ablated agent got access to the same memories that the full agent had gathered. The authors did not re-run each variant for two days, because the simulations would drift into different worlds and become hard to compare. The paper says this makes the measured gaps likely a conservative estimate. A real no-reflection agent would not have lived the same two days as the full agent.
A hundred evaluators recruited on Prolific each saw one random question from every category, with the answers from all five conditions side by side. They ranked the answers from most to least believable. Every judge saw every condition, a within-subjects design.
Ranks are awkward to compare. A rank of 1 vs 2 says nothing about how big the gap is. So the authors turned ranks into ratings with TrueSkill. TrueSkill generalizes the Elo chess rating to many players at once, and Xbox Live uses it to rank gamers. Each condition gets a skill modeled as a bell curve with a mean μ and a spread σ. A higher μ means the condition beats lower ones more often. Two conditions with the same rating should be a toss-up.
pythonimport trueskill # open-source package; a sketch of the idea env = trueskill.TrueSkill() rating = {c: env.create_rating() for c in CONDITIONS} # each starts with a mean and a spread for ranking in all_rankings: # one list per judge, most believable first groups = [(rating[c],) for c in ranking] new = env.rate(groups, ranks=list(range(len(ranking)))) # rank 0 beat rank 1 beat rank 2 ... for c, (r,) in zip(ranking, new): rating[c] = r # r.mu and r.sigma move toward the evidence
The full architecture won: μ = 29.89 (σ = 0.72). Each removed part cut the score. No reflection: 26.88 (0.69). No reflection and no planning: 25.64 (0.68). The crowdworker: 22.95 (0.69). No memory at all: 21.21 (0.70). Compared with the no-memory condition, the full agent sits 8.68 points higher. The paper reports an effect size of Cohen’s d = 8.16, which measures the gap between two means in standard deviations: about eight.
A Kruskal-Wallis test (a rank-based cousin of ANOVA) confirms the conditions differ overall: H(4) = 150.29, p < 0.001. Pairwise Dunn tests (comparisons of each pair) with a Holm-Bonferroni correction (a guard against false alarms when many pairs are compared) show every pair is significantly different (p < 0.001) except the crowdworker and the no-memory agent, the two lowest. The crowdworker baseline is not meant to be the best a human could do. It only checks that the architecture reaches a basic level of competence.
Start from the full agent and take parts away in the paper’s order: reflection, then planning, then observation. Press a step and see the score fall.
The four means and the crowdworker mean are the paper’s TrueSkill values (Section 6.5.1, Figure 8). The drops between steps (3.01, 1.24, 4.43) are our subtraction.
Look at the staircase. Removing observation costs the most, 4.43 points. That is no surprise: without memory there is nothing to retrieve. Removing reflection costs 3.01 points, more than removing planning (1.24). Reflection matters most among the two higher-level parts. But note that the three parts are nested: planning and reflection both read from observations.
The bell curves below show what “significant” looks like. Each condition is a bell at its μ with spread σ. Most pairs barely touch. The crowdworker and the no-memory agent overlap: that is the pair the paper could not separate.
Pick two conditions. The bells are the paper’s TrueSkill estimates. The less they overlap, the more sure we are of the order.
Means and spreads are the paper’s. The paper reports that all pairwise differences are significant (p < 0.001, Dunn test with Holm-Bonferroni correction) except crowdworker against the no-memory agent. The bells are drawn as plain normal curves, as the paper models each skill as N(μ, σ²).
The numbers match the stories. Without observational memory, Abigail denied knowing Rajiv Patel. With it, she described him. The full agent can still fail. Rajiv was asked about the election and said he had not been following it, even though he had heard about Sam’s candidacy. That is a retrieval miss. Tom retrieved an incomplete fragment: he remembered plans to discuss politics at Isabella’s party, but not the memory of hearing about the party. So he was unsure the party existed.
Agents also embellish. Isabella knew Sam was running. She then added that he would make an announcement tomorrow, which no one had said. Yuriko described her neighbor Adam Smith as the author of Wealth of Nations, a book by an 18th-century economist with the same name. That detail came from world knowledge inside the language model. The authors found that complete fabrication was rare. Agents who could not recall something usually said so.
Chapter 9
Measure what 25 agents do together in two days, with almost nothing scripted
The authors gave Isabella Rodriguez, the cafe owner, one starting idea: she wants to throw a Valentine’s Day party at Hobbs Cafe, from 5 to 7 pm on February 14th. They also wrote into Maria’s description that she has a crush on Klaus. Then they pressed play and stayed out of it.
Isabella invited friends and customers whenever she saw them. On the afternoon of the 13th she decorated the cafe. Maria came by and Isabella asked for help. Maria agreed. That night Maria invited Klaus, her secret crush, and he happily accepted. On Valentine’s Day at 5 pm, five agents including Klaus and Maria showed up and enjoyed the party.
The user set an intent and a crush. Spreading the word, decorating, asking each other out, arriving on time and mingling were all started by the agents’ own architecture. Each step needed memory to work. The invitation had to be stored, retrieved later, and acted on. A single break in that chain would end the story.
The authors define three measurements for the 25 agents over two game days. Each ends with an interview, and each answer is checked against the agent’s memory stream to rule out hallucination, which here means claiming to know something with no source in memory.
Information diffusion. Does news spread? Two facts begin with a single agent: Sam’s run for mayor, and Isabella’s party. At the end, the team asks every agent, “Did you know there is a Valentine’s Day party?” and “Do you know who is running for mayor?” An answer counts as a yes only if the agent shows knowledge and the source dialogue exists in its memory stream.
Relationship formation. Do agents get to know each other? The team asks each agent, “Do you know of <name>?” about every other agent, once at the start and once at the end. A pair has a relationship if both know of each other. Pairs become the edges of a graph, which is dots joined by lines: its 25 vertices (dots) are the agents. The summary number is the network density.
Work it with four agents. They have 4 × 3 / 2 = 6 possible pairs. If 3 pairs know each other, the density is 2 × 3 / (4 × 3) = 0.5. For the 25 agents of Smallville there are 25 × 24 / 2 = 300 possible pairs. So a density of 0.167 means about 50 pairs, and 0.74 means about 222. Slide the edge count to see what these look like.
Each dot is one of the 25 agents. Each line is a pair who both know of each other. Drag the number of pairs, or press a preset for the paper’s start and end.
The density formula and the two reported densities (0.167 and 0.74) are the paper’s. The pair counts 50 and 222 are our arithmetic (density times 300). Which agents are linked in the picture is random: the paper does not publish its graph.
Coordination. Do agents act together on what they learn? For the party, the team counts how many who heard actually showed up at the right place and time.
Candidacy news spread from 1 agent (4%) to 8 (32%). Party news spread from 1 agent (4%) to 13 (52%). Nobody who claimed to know either fact had made it up. Network density rose from 0.167 to 0.74. Among the 453 answers about whether one agent knew another, 6 (1.3%) were hallucinated.
The party funnel is the most instructive. Besides Isabella, 12 agents heard about the party by the end. Five of those 12 came. The team interviewed the seven who did not. Three cited conflicts. Rajiv, a painter, said he was busy preparing for an upcoming show. The other four said they were interested when asked but never planned to come on the day.
Each dot is one of the 25 agents. Choose a moment and see who knows about the party and who goes.
The counts are the paper’s (Section 7.1.2): 1 agent aware at the start, 13 at the end, 12 invited besides Isabella, 5 attended, 3 of the 7 absent with a conflict and 4 interested but not planning to come. Which dot is which agent is arbitrary.
Each hop of the news is a small memory story. Sam tells Tom about his candidacy at the grocery store. Tom stores the conversation as an observation. Later that day Tom and John, who heard the news from another source, discuss Sam’s chances. The news travels because each agent stores what it hears and says it later: storage, retrieval and speech. When retrieval misses, as with Tom and the party, the chain stops.
Notice how careful the checks are. An agent that says yes might be guessing, since a language model happily plays along. So the team looked in the memory stream for the dialogue that delivered the news. Only agents with a real source counted. That is why the paper can say that none of the agents who claimed to know about the party or the election had made it up. The same rule likely makes the counts a floor: an agent that heard the news but could not retrieve it at interview time would count as a no.
pythondef network_density(knows): # knows[a][b] is True if a says "I know of b" V = list(knows) E = sum(1 for i, a in enumerate(V) for b in V[i + 1:] if knows[a][b] and knows[b][a]) return 2 * E / (len(V) * (len(V) - 1)) # 0 = strangers, 1 = everyone knows everyone def spread(agents, question, stream_has_source): yes = [a for a in agents if says_yes(llm_interview(a, question)) and stream_has_source(a, question)] return len(yes) / len(agents) # e.g. 13 / 25 = 0.52 for the party
Chapter 10
Learn the failure modes the authors found, the risks they name, and the questions the paper leaves open
Picture a dorm bathroom that holds exactly one person. It is occupied. A second agent walks in anyway. In Smallville, shops close at about 5 pm, and now and then an agent strolls into a shop after closing. These small slips are not random noise. Each one points to a real limit of the design. The authors studied them with an inductive analysis of the two-day run (they read the observed errors and grouped similar ones, instead of testing a guess made in advance), and they found three families of error.
As an agent learns more, two jobs get harder. Retrieval has more records to pick from. And choosing a place to act has more places to choose from. The paper gives a lunch example. At first many agents ate lunch at the cafe. Once some learned of a nearby bar, they went to the bar instead, although the bar was meant as a place to meet later in the day. As the paper dryly says, that is unless the town had spontaneously developed an afternoon drinking habit. The behavior got less typical as the agent knew more.
Some rules of a place are hard to say in a sentence. A dorm bathroom is, in this town, a one-person bathroom. But in the real world dorm bathrooms usually hold several people, and the model carries that world knowledge. So agents entered while it was occupied. Likewise, agents did not always realize that stores had closed. The authors suggest a fix: write the norm into the state of the location. Call it a “one-person bathroom” and the model has a chance.
The model behind the agents was instruction-tuned, meaning it was trained after pretraining to follow requests politely and helpfully. That polish leaked into the characters. Dialogue felt overly formal. Mei opened a chat with her husband with a formal greeting, asked polite questions about his day, and ended with, “It was good talking to you as always.”
The agents were also too agreeable. Isabella received ideas for her party, such as a Shakespeare reading or a professional networking event, that did not fit her interests. She rarely said no. Over time the ideas of others shaped her own. Asked whether she liked English literature, she said yes and added that she had been exploring ways to promote creativity in her community.
Try sorting some of the paper’s observed behaviors into their families. The first two families, retrieval and embellishment, come from Chapter 8.
Read the behavior, then pick the family it belongs to. Seven behaviors, one at a time.
All seven behaviors are from Sections 6.5.2 and 7.2. The family names are our short labels for the paper’s descriptions. The paper treats the two norm examples (the bathroom and the closed shops) together.
The authors list four social risks and give a response to each.
A footnote at the start of the paper sets the tone. When it says an agent goes somewhere, that is shorthand. The agents resemble animated film characters. They aim at believability and do not have genuine agency.
The authors point to several directions. Tune the recency, importance and relevance functions, perhaps by fine-tuning. Make the system cheaper and parallel, or build models designed for this job. Watch agents for longer than two days, and build a stronger benchmark. Compare different base models and settings. As models improve, the authors expect the architecture’s basics (memory, planning, reflection) to stay the same.
python# The paper's suggested repair for unwritten norms: put the norm in the location's own words. world["Oak Hill College Dorm"]["bathroom"] = "one-person bathroom" # not just "dorm bathroom" world["The Willows Market and Pharmacy"]["status"] = "closed after 5 pm" # our example of the same idea
Chapter 11
Keep the numbers, the terms and the core code in one place, then follow the links onward
The paper starts from a small problem: a language model sees one moment and forgets the rest. It answers with a memory architecture and nothing else. A memory stream records every experience as a sentence. Retrieval picks a few records by recency, importance and relevance. Reflection turns many records into one conclusion. Planning turns conclusions into a day, and a reaction loop lets events break the plan. No model is trained. Twenty-five agents in a toy town produced the most believable answers in an interview study, and they spread news, made friends and threw a party.
| Measurement | Value | Source |
|---|---|---|
| Agents in Smallville; base model | 25; gpt-3.5-turbo (ChatGPT), unmodified | §1, §4 |
| Time scale: real to game | 1 second to 1 minute | Appendix A |
| Recency decay | 0.995 per game hour since last retrieval | §4.1 |
| Importance score | integer 1 to 10, asked once at creation | §4.1 |
| Retrieval score | sum of min-max scaled recency, importance, relevance; all weights 1 | §4.1 |
| Reflection trigger | importance sum above 150; about 2 or 3 a day; 100 records, 3 questions, 5 insights | §4.2 |
| Plan layers | 5 to 8 broad chunks, hour chunks, then 5 to 15 minute chunks | §4.3 |
| Interview study | 25 questions in 5 categories; 100 evaluators; 5 conditions | §6 |
| TrueSkill: full, no reflection, no reflection or planning, crowdworker, no memory | 29.89, 26.88, 25.64, 22.95, 21.21 | §6.5.1 |
| Effect size, full against no memory; overall test | d = 8.16; H(4) = 150.29, p < 0.001 | §6.5.1 |
| Candidacy news; party news | 1 to 8 agents (4% to 32%); 1 to 13 agents (4% to 52%) | §7.1.2 |
| Network density; hallucinated answers | 0.167 to 0.74; 6 of 453 (1.3%) | §7.1.2 |
| Party: invited, attended, absent | 12, 5, 7 (3 conflicts, 4 interested but not planning) | §7.1.2 |
| Cost of the study | thousands of dollars in token credits, multiple days | §8.2 |
| Term | Plain meaning |
|---|---|
| Generative agent | A character whose behavior comes from a language model plus a memory architecture. |
| Memory stream | A list of memory objects, each with a sentence, two timestamps and an importance. |
| Observation | A memory of something the agent perceived directly. |
| Reflection | A memory of a conclusion the agent drew from other memories, with pointers to them. |
| Plan | A memory of intended future actions, each with place, start time and duration. |
| Recency, importance, relevance | How fresh, how weighty, and how close to the query a memory is. |
| Min-max scaling | Rescale a signal so its lowest value is 0 and its highest is 1. |
| Summary description | A cached paragraph about the agent that starts most prompts. |
| Ablation | A test that removes one part of a system to measure what it was worth. |
| TrueSkill | A rating system that turns many rankings into a mean and a spread per player. |
| Network density | The share of all possible agent pairs who know each other. |
| Memory hacking | Convincing an agent that a past event happened when it did not. |
This sketch joins every earlier chapter into one small class. It leaves out the sandbox, the pathfinding and the dialogue loop.
pythonimport numpy as np class Agent: def __init__(self, name, seed_facts): self.name, self.stream, self.pending = name, [], 0 for fact in seed_facts: # the paragraph split at semicolons self.remember(fact, 0.0) # --- memory (Ch. 3) --- def remember(self, text, now, kind="observation", sources=()): score = int(llm("On the scale of 1 to 10 ... rate the likely poignancy of the following " f"piece of memory.\nMemory: {text}\nRating:")) self.stream.append(Memory(text, now, now, score, kind, list(sources))) self.pending += score if self.pending > 150: # --- reflection (Ch. 5) --- self.pending = 0; self.reflect(now) # --- retrieval (Ch. 4) --- def retrieve(self, query, now, k, decay=0.995): q = embed(query) sc = lambda x: (x - x.min()) / (x.max() - x.min() + 1e-9) rec = np.array([decay ** (now - m.last_access) for m in self.stream]) imp = np.array([m.importance for m in self.stream], float) rel = np.array([cosine(embed(m.text), q) for m in self.stream]) top = np.argsort(-(sc(rec) + sc(imp) + sc(rel)))[:k] # all three weights are 1 for i in top: self.stream[i].last_access = now return [self.stream[i] for i in top] def reflect(self, now): recent = "\n".join(m.text for m in self.stream[-100:]) for q in lines(llm(recent + "\nGiven only the information above, what are 3 most salient " "high-level questions we can answer about the subjects in the statements?")): ev = self.retrieve(q, now, 15) numbered = "\n".join(f"{i+1}. {m.text}" for i, m in enumerate(ev)) for text, cited in parse_insights(llm(f"Statements about {self.name}\n{numbered}\nWhat 5 high-level " "insights can you infer from the above statements? (example format: insight (because of 1, 5, 3))")): self.remember(text, now, "reflection", [ev[j - 1] for j in cited]) # --- planning and reacting (Ch. 6) --- def plan_day(self, now): broad = llm(f"{self.summary(now)}\n{self.yesterday}\nHere is {self.name}'s plan today in broad strokes: 1)") for chunk in parse_chunks(broad): self.remember(str(chunk), now, "plan") def react(self, obs, now): ctx = summarize(self.retrieve(f"What is {self.name}'s relationship with {obs.entity}?", now, 10) + self.retrieve(f"{obs.entity} is {obs.status}", now, 10)) return llm(f"{self.summary(now)}\nObservation: {obs.text}\nSummary of relevant context from " f"{self.name}'s memory: {ctx}\nShould {self.name} react to the observation, " "and if so, what would be an appropriate reaction?")
The paper joins four threads. From game AI it takes the goal of believable characters. From cognitive architectures it takes the split into memory, planning and acting. From language models it takes the ability to write plausible behavior from a text description. From human-computer interaction it takes the habit of testing with real people. Its main claim is that the missing piece is a memory architecture, not a bigger model.
What to reuse: write raw experience as plain text. Rank it by several signals, not one. Pause now and then to infer something new. Plan from the top down and add detail late. Cache the summary of who the agent is. Test by interviewing. What to treat with care: the weights of 1, the single-prompt importance score, and the cost.
Joon Sung Park, Joseph C. O’Brien, Carrie J. Cai, Meredith Ringel Morris, Percy Liang and Michael S. Bernstein. Generative Agents: Interactive Simulacra of Human Behavior. UIST ’23, San Francisco, October 29 to November 1, 2023. doi 10.1145/3586183.3606763. arXiv:2304.03442. The authors link the simulation code at github.com/joonspk-research/generative_agents. This lesson is a re-telling in our own words and devices, written for Stanford CS 329Z; all credit for the work and the figures’ numbers belongs to the authors.