From Chatbot to Agent: The Engineer's Guide to LLM Memory Systems
LLM APIs forget everything between calls. This guide shows the three kinds of agent memory, then builds a small hybrid memory in Python: a rolling window, a summary step and a vector store with recency weighting and a salience filter. You test the whole loop with a fake model, so you need no API key to check it.

This guide is for developers who have a working chatbot and now want an agent that remembers. You will learn the three kinds of agent memory, then build a small hybrid memory in Python: a rolling window for the current chat, a summary step, and a vector store for long-term facts. You will also test the loop with a fake model, so you can check it without an API key.
Key takeaways
- An LLM API keeps no state between calls. Memory is whatever your code puts back into the next prompt.
- Use a short window for the current chat and a searchable store for facts that must last. Keep hard facts, like names and IDs, outside any summary.
- Rank old memories by both meaning and age, and only save turns worth keeping. That stops stale or empty memories from crowding the prompt.
The goldfish problem
Every call to an LLM API starts fresh. The model does not remember your last request. If the user said their name two messages ago, the model only knows it if you send that message again.
Agent memory is the code that decides what past information goes back into the prompt, and where the rest is stored. For a simple chatbot, you can resend the whole chat each time. For an agent that runs for weeks, that stops working. The prompt grows, each call costs more, and the context window has a hard limit.
Long prompts also hurt quality. The "Lost in the Middle" study found that models use facts near the start or end of a long input better than facts buried in the middle. So more history is not always better history.
This post is part 9 of the LLM & LangChain Fundamentals series. In part 8 you set up vector databases for semantic search. Here you use that search as long-term memory, in plain Python first, so you can see every moving part.
The three kinds of agent memory
Agent design borrows names from human memory. The CoALA paper maps them onto language agents, and the LangChain memory docs use the same split.
Working memory (short-term)
This is the context window: the system prompt, the recent chat and any notes the agent made in this run. It is exact but short-lived. Once a message drops out of the prompt, the model cannot see it.
Long-term memory
This lives outside the prompt, usually in a database. LangChain's docs split it into two types:
- Semantic memory holds facts, such as "the user's stack is TypeScript and Postgres".
- Episodic memory holds past events and experiences, often reused as examples of how a task was done.
A vector store is a common home for both, because you can search it by meaning. You fetch the memories that fit the current question, not just the most recent ones.
Procedural memory
This is how the agent knows how to act. LangChain's docs describe it mainly as the system prompt, and CoALA adds the rules written in the agent's own code. It changes rarely, but it is still memory, and you can update it on purpose.
| Memory type | Where it lives | Trade-off | Use it for |
|---|---|---|---|
| Working (short-term) | The prompt | Exact, but small and costly per call | The current chat and task |
| Semantic (long-term) | Database or vector store | Lasts, but needs search and upkeep | Facts about the user or project |
| Episodic (long-term) | Vector store | Gives good examples, but can go stale | Past runs and how they went |
| Procedural | System prompt and code | Stable, but changes need care | Rules and how-to knowledge |
Pattern 1: the rolling window
The simplest memory is a queue that keeps the last few turns. When a new turn arrives, the oldest one drops off. Create memory_agent.py:
# memory_agent.py
import json
import os
import time
from collections import deque
from langchain_core.documents import Document
from langchain_core.vectorstores import InMemoryVectorStore
class ShortTermMemory:
def __init__(self, max_turns=5):
# Each item is a (user, ai) pair; deque drops the oldest one for us.
self.history = deque(maxlen=max_turns)
def add_interaction(self, user_input, ai_response):
self.history.append((user_input, ai_response))
def get_context_string(self):
return "\n".join(f"User: {u}\nAI: {a}" for u, a in self.history)
Checked against langchain@1.4.7, langchain-core@1.7.1, langchain-openai@1.7.3 and numpy@2.5.4, 2026-10-29.
deque(maxlen=5) does the dropping for you. The catch is the goldfish effect: if the user gave their name six turns ago, it is gone.
Pattern 2: the summary layer
To soften that hard cutoff, add a summary. Before a turn leaves the window, ask a model to fold it into a running summary. Add this to memory_agent.py:
# memory_agent.py (continued)
SUMMARY_PROMPT = (
"Here is the current summary of the conversation, and an older exchange that is "
"leaving the window. Update the summary so it keeps the key details. Stay under "
"150 words.\n\nSummary: {summary}\n\nUser: {user}\nAI: {ai}"
)
class SummarizingMemory(ShortTermMemory):
"""A rolling window that folds each dropped turn into a running summary."""
def __init__(self, model, max_turns=5):
super().__init__(max_turns)
self.model = model
self.summary = ""
def add_interaction(self, user_input, ai_response):
if len(self.history) == self.history.maxlen:
old_user, old_ai = self.history[0] # the turn the deque is about to drop
prompt = SUMMARY_PROMPT.format(summary=self.summary or "(none)", user=old_user, ai=old_ai)
self.summary = self.model.invoke(prompt).text
super().add_interaction(user_input, ai_response)
def get_context_string(self):
recent = super().get_context_string()
return f"Summary of earlier turns: {self.summary}\n{recent}" if self.summary else recent
SummarizingMemory works anywhere ShortTermMemory does, so the agent loop below can use either. The agent keeps the gist ("the user is debugging a Python script") without paying for every old code block. In the next part you will see that LangChain ships this pattern as ready-made middleware, so you rarely write it by hand.
Summaries have a weakness, covered under memory drift below: details fade each time you summarize again.
Pattern 3: a long-term store
Facts that must last go into a searchable store. The loop for each turn looks like this:
- Retrieve: search the store for memories related to the user's message.
- Inject: put those memories and the recent chat into the system prompt.
- Generate: call the model.
- Store: save the new exchange, with a timestamp, for later turns.
Start with the store side. Each memory is a Document with the time it was saved in its metadata:
# memory_agent.py (continued)
def remember(store, text, ts=None):
"""Save one memory with the time it was written."""
store.add_documents([Document(page_content=text, metadata={"ts": ts or time.time()})])
InMemoryVectorStore from langchain_core keeps everything in a Python dict and scores matches with cosine similarity. That is fine for learning and tests. For real data, use a database-backed vector store like the ones in part 8.
Rank memories by meaning and age
A plain similarity search has a blind spot. If the user asks "why is the server down?", it may return a server crash from two years ago, and the model may treat that old fix as today's answer.
The Generative Agents paper scores each memory on relevance, recency and importance, and adds the three together. Recency there is an exponential decay over time. You can borrow the first two parts. Fetch more matches than you need, add a recency score, and keep the best:
# memory_agent.py (continued)
def recency_weighted_search(store, query, k=2, half_life_hours=24.0, now=None):
"""Similarity plus a recency bonus that halves every `half_life_hours`."""
now = now or time.time()
scored = []
for doc, similarity in store.similarity_search_with_score(query, k=k * 4):
age_hours = (now - doc.metadata["ts"]) / 3600
recency = 0.5 ** (age_hours / half_life_hours)
scored.append((similarity + recency, doc))
scored.sort(key=lambda pair: pair[0], reverse=True)
return [doc for _, doc in scored[:k]]
When two memories match equally well, the newer one wins. The 24-hour half-life is a rule of thumb, not a value from the paper. Tune it to how fast facts change in your app.
Only save what is worth saving
If you store every turn, the store fills with "hi", "thanks" and "ok". Those empty memories then show up in searches and waste prompt space.
Add a salience filter. Before saving, ask a small, cheap model a yes-or-no question:
# memory_agent.py (continued)
SALIENCE_PROMPT = (
"Does this exchange contain a fact worth remembering later, such as a name, "
"a preference or a decision? Answer yes or no.\n\nUser: {user}\nAI: {ai}"
)
def worth_remembering(judge, user_input, ai_response):
reply = judge.invoke(SALIENCE_PROMPT.format(user=user_input, ai=ai_response))
return reply.text.strip().lower().startswith("yes")
The judge can be a different, cheaper model than the one that talks to the user. This check costs one extra call per turn, so run it in the background if latency matters. The LangChain memory docs call this "background" memory writing, as opposed to writing "in the hot path" before the reply.
Put the loop together
Now wire the pieces into one turn of the agent:
# memory_agent.py (continued)
def agent_cycle(user_input, model, store, chat_history, judge=None):
# 1. Retrieve: long-term memories that fit this message
memories = recency_weighted_search(store, user_input)
memory_text = "\n".join(d.page_content for d in memories)
# 2. Inject: memories and recent chat go into the system prompt
system_msg = (
"You are a helpful assistant.\n\n"
f"LONG-TERM MEMORY:\n{memory_text}\n\n"
f"RECENT CONVERSATION:\n{chat_history.get_context_string()}"
)
# 3. Generate
response = model.invoke([("system", system_msg), ("human", user_input)]).text
# 4. Store: short-term always, long-term only if it is worth it
chat_history.add_interaction(user_input, response)
if judge is None or worth_remembering(judge, user_input, response):
remember(store, f"User said: {user_input}\nAI answered: {response}")
return response
if __name__ == "__main__":
from langchain.chat_models import init_chat_model
from langchain_openai import OpenAIEmbeddings
# Needs OPENAI_API_KEY. Check the provider's models page for current ids.
model = init_chat_model(os.getenv("CHAT_MODEL", "openai:gpt-6-luna"))
store = InMemoryVectorStore(OpenAIEmbeddings(model="text-embedding-3-small"))
history = ShortTermMemory()
print(agent_cycle("My name is Priya and I deploy on Fly.io.", model, store, history))
print(agent_cycle("Where do I deploy?", model, store, history))
Install the packages with pip install -U langchain langchain-openai numpy (the in-memory store needs numpy). The real run also needs an OPENAI_API_KEY. On the date above, OpenAI's models page lists gpt-6-luna as its most efficient model, and its embeddings guide lists text-embedding-3-small. Model ids change often, so check both pages and set CHAT_MODEL to swap models without code changes.
Test the loop without an API key
You can check the wiring for free. FakeListChatModel returns the replies you give it, in order, and DeterministicFakeEmbedding turns text into repeatable vectors without a network call:
# test_memory.py
import time
from langchain_core.embeddings import DeterministicFakeEmbedding
from langchain_core.language_models import FakeListChatModel
from langchain_core.vectorstores import InMemoryVectorStore
from memory_agent import ShortTermMemory, SummarizingMemory, agent_cycle, recency_weighted_search, remember
store = InMemoryVectorStore(DeterministicFakeEmbedding(size=64))
history = ShortTermMemory(max_turns=2)
model = FakeListChatModel(responses=["Nice to meet you, Priya.", "Thanks!"])
judge = FakeListChatModel(responses=["yes", "no"])
agent_cycle("My name is Priya.", model, store, history, judge=judge)
agent_cycle("Thanks", model, store, history, judge=judge)
assert len(store.store) == 1 # the judge said "no" to the second turn
assert len(history.history) == 2
# A one-turn window: the second turn pushes the first into the summary.
summarizer = FakeListChatModel(responses=["Priya introduced herself."])
short = SummarizingMemory(summarizer, max_turns=1)
short.add_interaction("My name is Priya.", "Hi Priya.")
short.add_interaction("Thanks", "You're welcome.")
assert short.summary == "Priya introduced herself."
assert "Priya introduced herself." in short.get_context_string()
# The same text saved twice: the newer copy must rank first.
now = time.time()
remember(store, "server crash fix", ts=now - 90 * 24 * 3600)
remember(store, "server crash fix", ts=now - 60)
top = recency_weighted_search(store, "server crash fix", k=1, now=now)[0]
assert top.metadata["ts"] == now - 60
print("memory loop works")
The fake embedding gives identical vectors for identical text, so the last check isolates the recency bonus. If it fails, your decay math is off.
Memory pitfalls in production
The code above is short. Keeping it reliable is the harder part. The fixes below are rules of thumb from common agent designs, so test them against your own data.
Memory drift
A summary of a summary loses detail. After many rounds, "the user wants a Python script that scrapes product prices" can shrink to "the user wants code".
Fix: keep hard facts out of the summary. Store names, dates, IDs and the tech stack as structured data, such as a JSON profile or a table, and inject them word for word:
# memory_agent.py (optional: add it above agent_cycle and prepend it to system_msg)
def profile_block(profile):
"""Hard facts go into the prompt word for word, never through the summarizer."""
return f"USER PROFILE (exact, never summarized):\n{json.dumps(profile)}\n\n"
# profile_block({"name": "Priya", "stack": ["TypeScript", "Postgres"]}) + system_msg
Context poisoning
A search can return a memory that matches the words but not the situation. The model then treats an old or unrelated fact as true now. Recency weighting helps. So does labelling each memory with its date in the prompt, so the model can see how old it is.
The "I know that" loop
Without a salience filter, small talk floods the store and pushes useful memories out of the top results. Filter before you save, and delete or merge memories that repeat the same fact.
Start small
Start with a rolling window. Add a structured profile for the facts that must never fade. Add a vector store only when users come back across sessions and expect the agent to recall them. Watch how full the prompt gets and what each call costs, and grow from there.
Next in the series, you will build the same ideas with LangChain's own tools in implementing memory in LangChain for conversational AI: checkpointers for short-term memory, summarization middleware and the Store API.
Frequently asked questions
Do LLMs remember previous conversations?
Not through the API. Each request is independent, and the model only sees what you send in that request. Chat apps that seem to remember are resending history or injecting stored memories into the prompt.
What is the difference between short-term and long-term memory in an AI agent?
Short-term memory is the recent conversation inside the prompt, scoped to one session. Long-term memory lives outside the prompt, in a database or vector store, and lasts across sessions. The agent searches it and adds only the relevant parts to each prompt.
Should I store every message in the vector database?
Usually not. Small talk adds noise to searches and costs storage. A salience filter, a cheap yes-or-no check before saving, keeps only turns with facts, preferences or decisions.
How do I stop an agent from using outdated memories?
Save a timestamp with each memory and add a recency bonus when you rank search results. Also show the date next to each memory in the prompt. For facts that change, such as a user's plan or address, overwrite one structured record instead of adding a new memory each time.
Do I need LangChain to add memory to an agent?
No. The loop in this post is plain Python plus a vector store. A framework saves you work on persistence, threads and summaries, which the next part of the series covers.
Sources
Verified against the sources below on October 29, 2026. Products and docs change often: check the linked sources if something looks different.
- LangChain docs: Memory overview (concepts)
- LangChain docs: Short-term memory
- LangChain docs: Long-term memory
- Cognitive Architectures for Language Agents (CoALA), Sumers et al.
- Generative Agents: Interactive Simulacra of Human Behavior, Park et al.
- Lost in the Middle: How Language Models Use Long Contexts, Liu et al.
- LangChain reference: InMemoryVectorStore
- LangChain docs: Unit testing (fake chat models)
- OpenAI API: Models
- OpenAI API: Embeddings guide
- langchain-core on PyPI
All 14 parts in this series
- Part 01What Is LangChain? When to Use It and When to Write Your Own Code
- Part 02LangChain vs. LlamaIndex vs. Vanilla: The Builder's Stack Selection Matrix
- Part 03Structured JSON Output from LLMs: Schema Injection, Pydantic and Retry Loops
- Part 04Building Your First LLM Chain: A Developer's Guide to Sequential Logic
- Part 05Building Your First RAG Pipeline: A Developer’s Guide to Context-Aware AI
- Part 06Building Robust RAG Pipelines: A Deep Dive into LangChain Document Loaders
- Part 07Stop Overthinking Vector Databases: A Builder’s Decision Framework
- Part 08Building Long-Term Memory: Setting Up Vector Databases for Semantic Search in LangChain
- Part 09From Chatbot to Agent: The Engineer's Guide to LLM Memory Systems
- Part 10Building State: A Deep Dive into LangChain Memory for Conversational AI
- Part 11Beyond Built-ins: Architecting Custom Tools in LangChain
- Part 12Unmasking the Black Box: Mastering LangChain Callbacks for Debugging
- Part 13Architecting Autonomous Agents: A Builder’s Guide to Complex Workflows
- Part 14Best Practices for Deploying LangChain Apps to Production
AI Automation Engineer & Salesforce Developer
Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.



Comments
Loading comments...