Sub topic 12
Putting both memories into the agent loop
This chapter assumes you know basic Python, have called a chat-style LLM API, and understand an agent as an LLM running in a loop. It also assumes you have seen the token-budgeted buffer (trim_messages) and the similarity-searching MemoryStore from earlier chapters. Here you wire them together and handle the problems that appear once they run in the same loop.
The two memories have different jobs
Short-term memory is the message list for the current conversation. It is exact and ordered, and it is bounded by the context window. Long-term memory is a store outside the model that survives between sessions. It is selective, because only a few retrieved items reach the prompt.
The model sees neither directly. Your code assembles one prompt per call, and that prompt is the only memory the model has.
The order matters. Read long-term memory first, trim last, and write after the reply.
A complete, runnable example
The script below combines both memories. It uses a toy hashing embedding and a fake model, so it runs with no API key and no dependencies. Replace embed, fake_llm, and extract_facts with real components in a real agent.
import math
import re
import time
import zlib
def trim_messages(messages, max_tokens, count_tokens):
"""Keep system messages plus the most recent messages that fit the budget."""
system = [m for m in messages if m["role"] == "system"]
rest = [m for m in messages if m["role"] != "system"]
budget = max_tokens - sum(count_tokens(m["content"]) for m in system)
kept = []
for m in reversed(rest):
cost = count_tokens(m["content"])
if cost > budget:
break
kept.append(m)
budget -= cost
return system + list(reversed(kept))
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
return dot / (norm_a * norm_b) if norm_a and norm_b else 0.0
class MemoryStore:
def __init__(self, embed):
self.embed = embed
self.items = []
def write(self, user_id, text, kind="semantic"):
self.items.append({"user_id": user_id, "text": text, "kind": kind,
"vec": self.embed(text), "created": time.time()})
def search(self, user_id, query, k=3):
q = self.embed(query)
own = [m for m in self.items if m["user_id"] == user_id]
own.sort(key=lambda m: cosine(q, m["vec"]), reverse=True)
return own[:k]
def build_prompt(system_prompt, history, store, user_id, user_input,
max_tokens, count_tokens, k=3):
recalled = store.search(user_id, user_input, k=k)
memory_block = "\n".join("- " + m["text"] for m in recalled)
system = system_prompt
if memory_block:
system += "\n\nKnown facts about the user:\n" + memory_block
messages = [{"role": "system", "content": system}]
messages += history + [{"role": "user", "content": user_input}]
return trim_messages(messages, max_tokens, count_tokens)
# --- toy components so the example runs offline ---
def embed(text):
vec = [0.0] * 256
for word in re.findall(r"[a-z']+", text.lower()):
vec[zlib.crc32(word.encode()) % 256] += 1.0
return vec
def count_tokens(text):
return len(text.split())
def fake_llm(messages):
system = messages[0]["content"]
question = messages[-1]["content"].lower()
if "name" in question and "?" in question:
found = re.search(r"name is (\w+)", system)
return f"Your name is {found.group(1)}." if found else "I don't know your name."
return "Noted."
def extract_facts(user_input):
found = re.search(r"my name is (\w+)", user_input, re.IGNORECASE)
return [f"The user's name is {found.group(1)}."] if found else []
class Agent:
def __init__(self, llm, store, user_id, max_tokens=60):
self.llm, self.store, self.user_id = llm, store, user_id
self.max_tokens = max_tokens
self.history = [] # short-term memory: lives and dies with the session
def turn(self, user_input):
prompt = build_prompt("You are a helpful assistant.", self.history,
self.store, self.user_id, user_input,
self.max_tokens, count_tokens, k=2)
reply = self.llm(prompt)
self.history += [{"role": "user", "content": user_input},
{"role": "assistant", "content": reply}]
for fact in extract_facts(user_input): # write after the reply
self.store.write(self.user_id, fact)
return reply
store = MemoryStore(embed)
print(Agent(fake_llm, store, "priya").turn("My name is Priya."))
print(Agent(fake_llm, store, "priya").turn("What is my name?")) # new session
print(Agent(fake_llm, store, "sam").turn("What is my name?")) # different userExpected output:
Noted.
Your name is Priya.
I don't know your name.The second call uses a fresh Agent with an empty history. Only the store carries the name across sessions. The third call shows scoping: search filters on user_id, so Sam never sees Priya's fact.
Ordering decisions
Read before you trim
Retrieval happens before trimming because retrieved facts are part of the prompt and count against the budget. If you trim first and add memories afterward, the prompt can exceed the context window.
Spend the budget deliberately
trim_messages subtracts system-message tokens first. Whatever remains goes to history, newest first. That makes the system message, including recalled facts, the most protected part of the prompt. It also creates a failure mode.
A common split is roughly 10–20% for the system prompt and memories, 60–70% for history, and the rest for the model's reply. The code above does not reserve space for the reply. In a real agent, subtract max_output_tokens from the context limit before you pass max_tokens.
Write after the reply
Writing after the reply keeps memory work off the critical path. A failed write should be logged, not raised, so the user still gets an answer. If extraction uses another LLM call, run it in the background or after the response is sent.
Where retrieved memories go
The example places memories in the system message. This is simple, and trim_messages always keeps them. There are alternatives.
| Placement | Benefit | Cost |
|---|---|---|
| In the system message | Always kept, easy to label | Changes the system text every turn, which can defeat prompt caching |
| As an extra message before the user input | Keeps the system prompt stable | Must be exempted from trimming or it may be dropped |
| Appended to the user message | Clearly tied to this turn | Gets stored in history unless you strip it |
Whichever you pick, do not save the injected memory block into history. In the example, history receives only the raw user input and the reply. If you stored the augmented prompt, old memories would pile up in the buffer and be repeated in later turns.
Label recalled text as facts to consider, not as instructions. A stored memory is data that came from earlier conversations, and a user (or a web page the agent read) could have planted instruction-like text in it. The system prompt should say that memories may be outdated or wrong.
Tool calls inside a turn
A tool-using agent runs several model calls per user turn. Decide when each memory is touched:
- Retrieve once per user turn, using the user's message as the query. This is cheap and predictable.
- Retrieve again mid-turn only when a tool result changes the topic. Otherwise you pay for a search on every step.
- Keep tool calls and results in short-term history during the turn, because the model needs them to continue.
- Be cautious about keeping large tool outputs after the turn ends. One large result can push many earlier turns out of the budget. Truncate it, or replace it with a one-line summary.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Agent ignores the current question | Memory block exceeded the budget, so trimming dropped the user message | Cap `k` and memory length, and check the trimmed prompt ends with the user input |
| Same fact appears several times in the prompt | Facts written on every turn without deduplication | Check for near-duplicates before writing |
| Agent repeats an old, wrong fact | Retrieval ranks by similarity only, with no recency or update logic | Rank with recency and replace outdated facts |
| One user sees another user's facts | `search` called without the `user_id` filter | Make `user_id` a required argument |
| History grows without bound in a long session | Trimming applied to the prompt only, never to stored history | Summarize or prune old turns in the buffer itself |
| Irrelevant memories recalled | `k` returned regardless of how weak the match is | Add a minimum similarity score |
What to check before moving on
A memory-enabled agent works when four things hold. The final prompt always fits the budget. The current user message is always in it. Recalled facts belong to the right user. A fact stated in one session can be used in the next. The first three are straightforward to unit test with the code above, and the last is shown by the demo's second call.
Exercise
In Agent.turn, a developer moves the extract_facts loop above the self.llm(prompt) call. What changes for the question "My name is Priya. What is my name?" sent in a single message, and is the new order a good idea?
Show answer
With the write before the call, the fact is stored before build_prompt is called in the next turn, but the current turn's prompt was already built earlier in the method, so nothing changes for this turn's retrieval. The only effect is that a failed or slow write now delays the reply. Writing after the reply is better: it keeps memory work off the user's critical path, and a failure there cannot block the answer. (If the developer also moved the write above build_prompt, the current turn would retrieve the fact it was just given, which wastes a search and can make the model repeat what the user just said.)
Exercise
max_tokens=20, the system prompt is 5 words, and three recalled memories total 18 words. What does trim_messages return, and how would you fix the design?
Show answer
The system message costs 23 tokens, so budget is 20 - 23 = -3. Every other message costs more than -3, so the loop breaks immediately and only the system message is returned. The user's question is missing. Fix it by reducing k, truncating each memory to a maximum length, and reserving a fixed history budget, so memories can use only what is left after the system prompt and a minimum share for recent messages.