Sub topic 3
Short-term memory: the conversation buffer
This chapter assumes you can write basic Python and have called a chat-style LLM API. It also assumes you know an agent is a model running in a loop with tools. The previous chapters covered why model calls are stateless and what the context window is. Here you build the simplest working memory: the conversation buffer.
What the buffer is
A conversation buffer is a list of messages that your code keeps between model calls. Each call sends the whole list. The model sees the earlier turns only because you sent them again.
That makes short-term memory a data structure in your program, not a feature of the model. It lives in the context window while a call runs, and in your process memory between calls.
A typical buffer holds these message types:
| Role | Content | Who creates it |
|---|---|---|
| system | Instructions, persona, rules | Your code, once per session |
| user | What the person typed | The user |
| assistant | The model's reply, possibly with tool calls | The model |
| tool | The result of a tool call | Your code |
The request cycle
Every turn follows the same four steps. Append the user message, send the full list, receive the reply, append the reply.
A minimal buffer in code
The following example uses a fake model so it runs without an API key. The fake model only reads the messages argument, as a real stateless API would.
class ConversationBuffer:
def __init__(self, system_prompt):
self.messages = [{"role": "system", "content": system_prompt}]
def add(self, role, content):
self.messages.append({"role": role, "content": content})
def as_prompt(self):
# Return a copy so callers cannot change the stored history by accident.
return [dict(m) for m in self.messages]
def fake_llm(messages):
"""Stand-in for a chat API. It only knows what is in `messages`."""
last = messages[-1]["content"].lower()
if "what is my name" in last:
for m in messages:
if m["role"] == "user" and m["content"].startswith("My name is "):
name = m["content"][len("My name is "):].rstrip(".")
return "Your name is " + name + "."
return "I don't know your name."
return "Noted."
def chat(buffer, user_input, llm):
buffer.add("user", user_input)
reply = llm(buffer.as_prompt())
buffer.add("assistant", reply)
return reply
with_memory = ConversationBuffer("You are a helpful assistant.")
print(chat(with_memory, "My name is Priya.", fake_llm))
print(chat(with_memory, "What is my name?", fake_llm))
no_memory = ConversationBuffer("You are a helpful assistant.")
print(chat(no_memory, "What is my name?", fake_llm))The output is:
Noted.
Your name is Priya.
I don't know your name.The second and third calls use the same model function and the same question. The answers differ only because the first call received the earlier turn in its message list.
Design decisions in the buffer
Keep the system message first
Most APIs expect the system message at the start. Store it in the buffer's first slot, or keep it separate and prepend it when you build the prompt. The second approach makes it harder to delete the system message when you later cut old messages. You will see this in the next chapter.
Append only, at first
Treat the buffer as an append-only log during a session. Appending is simple and predictable, and it preserves a faithful record for debugging. Any editing, such as removing or compressing old turns, should happen when you build the prompt. That way you can still inspect the original history.
Return copies
If as_prompt returns the internal list, a later step can change it. For example, a function that inserts retrieved memories into the system message would change the stored history. The as_prompt method above copies each message dictionary to avoid this.
One buffer per session
A buffer belongs to one conversation. Do not store it in a module-level global. Two users sharing one list will see each other's messages. A common pattern is a dictionary keyed by session ID:
buffers = {}
def get_buffer(session_id, system_prompt="You are a helpful assistant."):
if session_id not in buffers:
buffers[session_id] = ConversationBuffer(system_prompt)
return buffers[session_id]If your server handles requests concurrently, two requests for the same session can interleave. Serialize them per session, for example with a lock, or the buffer can end up with two user messages in a row.
What the buffer costs
The buffer grows every turn, and each turn resends everything. Suppose an exchange (user message plus reply) averages 200 tokens and you ignore the system message.
| Turn | Tokens in this prompt | Total tokens sent so far |
|---|---|---|
| 1 | 200 | 200 |
| 5 | 1,000 | 3,000 |
| 10 | 2,000 | 11,000 |
| 20 | 4,000 | 42,000 |
| 50 | 10,000 | 255,000 |
The prompt size grows linearly, but the total you send and pay for grows roughly with the square of the number of turns. Latency grows too, since the model must read a longer input each time. Long conversations are therefore costly and slow before they ever hit the context limit.
Edge cases
Tool calls and tool results
In an agent, the buffer also holds tool traffic. An assistant message may contain a tool call, and the next message holds the tool's result. Many APIs reject a prompt where a tool result has no matching tool call, or where a tool call has no result. Treat the call and its result as a unit. If you remove one, remove the other.
Large tool outputs
A tool that returns a whole web page or a 5,000-line log can fill the buffer in one step. Truncate or summarize tool output before you append it, and note in the text that it was shortened, for example [truncated, 12,000 characters omitted]. Otherwise the model may treat partial output as complete.
Role ordering rules
Some APIs require strict alternation of user and assistant messages, or reject two system messages in the middle of a conversation. Check your provider's rules. A buffer that works against one API can fail against another.
Failed calls
If the model call fails after you appended the user message, the buffer now ends with an unanswered user message. On retry you would append the same message again. Either append the user message only after a successful call, or remove it when the call fails. Pick one rule and apply it consistently.
Restarts
The buffer lives in process memory. If your server restarts, every session starts empty. Saving the message list to a database or file lets a session survive a restart, but this is still short-term memory. It holds one conversation and nothing is extracted from it. Chapters on long-term memory cover facts that outlast any single conversation.
Common mistakes
- Sending only the latest message. The model then answers each turn with no context.
- Sharing one buffer across users. This leaks private content between sessions.
- Appending the same message twice after a retry, so the model sees duplicated turns and may respond to both.
- Editing the stored history to save tokens. You lose the original record. Build a shorter prompt from the full history instead.
- Assuming the buffer has no limit. It always has one, set by the model's context window and by your budget.
Where the buffer stops
The buffer gives the model perfect recall of the current conversation, as long as the conversation fits. It has two limits:
- Size: it cannot grow without bound, so old turns must eventually be removed or compressed.
- Scope: it ends with the session. A fact the user told you last week is not in this week's buffer.
The first limit is handled by trimming and summarizing. The second is handled by long-term memory. Both are built on the buffer you wrote above.
Exercise
A teammate's agent stores messages in a module-level list named history and appends to it on every request. In testing with one user it works. After launch, users report answers that mention other people's details. What is the cause, and how do you fix it?
Show answer
All requests share one buffer, so every user's messages are sent to the model together and the model can use them in answers. Give each session its own buffer, for example a dictionary keyed by session ID as in get_buffer, and serialize concurrent requests for the same session. Also check that old sessions are cleaned up, so the dictionary does not grow forever.
Exercise
Each exchange averages 300 tokens. Ignoring the system message, how many tokens does the prompt hold at turn 12, and how many tokens in total have been sent to the model across turns 1 to 12?
Show answer
The prompt at turn 12 holds about 12 x 300 = 3,600 tokens. The total sent is 300 x (12 x 13 / 2) = 300 x 78 = 23,400 tokens, because every turn resends all earlier turns.