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 have seen the two pieces built earlier: a token-budgeted buffer (trim_messages) and a vector-backed MemoryStore. Here you combine them in one agent turn.
The order of a turn
The model is stateless, so your code must rebuild its entire view of the world on every call. Short-term memory is the recent conversation. Long-term memory is whatever you retrieve from the store for this input. Each turn runs these steps in order:
- Retrieve memories for the current user and input.
- Put them into the system message.
- Trim the whole prompt to the token budget.
- Call the model.
- Append the exchange to the history.
- Decide whether anything is worth writing to long-term memory.
A runnable version
The block below includes the earlier helpers in compact form, so you can run the whole thing as one file. The embed function is a toy that hashes words into 32 buckets. Replace it with a real embedding model. The llm function is a stub.
import math
import re
import time
def trim_messages(messages, max_tokens, count_tokens):
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))
na = math.sqrt(sum(x * x for x in a))
nb = math.sqrt(sum(y * y for y in b))
return dot / (na * nb) if na and nb 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)
def agent_turn(llm, system_prompt, history, store, user_id, user_input,
max_tokens, count_tokens):
messages = build_prompt(system_prompt, history, store, user_id,
user_input, max_tokens, count_tokens)
reply = llm(messages)
history.append({"role": "user", "content": user_input})
history.append({"role": "assistant", "content": reply})
if user_input.lower().startswith("remember "):
store.write(user_id, user_input[len("remember "):])
return reply, messages
def embed(text):
vec = [0.0] * 32
for word in re.findall(r"[a-z]+", text.lower()):
vec[sum(map(ord, word)) % 32] += 1.0
return vec
store = MemoryStore(embed)
store.write("priya", "Priya prefers answers in Spanish")
store.write("sam", "Sam is allergic to peanuts")
history = []
count = lambda text: len(text.split())
llm = lambda messages: "Noted."
_, sent = agent_turn(llm, "You are a helpful assistant.", history, store,
"priya", "Which language should I answer in?", 60, count)
print(sent[0]["content"])The printed system message contains Priya's memory and not Sam's, because search filters by user_id before ranking.
Gotchas
- Memory competes with history. The memory block lives in the system message, and
trim_messagesalways keeps system messages. A largekleaves less budget for conversation turns, so keepksmall. - Trimming can drop the current input. If the system message uses most of the budget, the loop breaks at the newest user message and sends none of the conversation. Check the budget after adding memories.
- Retrieve before trimming, write after replying. Retrieval uses the raw user input, and the write step sees the finished exchange.
- Stale facts persist. Retrieved memories are treated as true. Maintenance, covered in a later chapter, keeps them current.
Exercise
In agent_turn, a user's long-term memories take 90% of the token budget. Which part of the prompt is affected, and why?
Show answer
The conversation history is affected. trim_messages always keeps the system message, which holds the memory block, and fills only the remaining budget with recent messages walking backward. Older turns, and possibly the latest user message, get dropped. Reduce k, shorten memories, or raise the budget.