AI agent memory explained: short-term vs long-term, with a tested example
An AI agent has two kinds of memory: short-term memory, which remembers the current conversation, and long-term memory, which keeps facts across conversations, such as what a user told it last week. The model itself remembers nothing between calls; your code decides what to save and what to send back in.1
Short-term vs long-term
| Short-term memory | Long-term memory | |
|---|---|---|
| Remembers | Earlier turns of this conversation1 | Facts and events across conversations1 |
| Scoped to | One thread, saved as checkpoints so it can resume later1 | A namespace you choose, often a user or organisation ID1 |
| Stored as | The agent's state, by a checkpointer2 | JSON documents in a store, each under a namespace and key1 |
| Main risk | Grows until it overflows the context window1 | Saving wrong or stale facts that keep coming back |
Three kinds of long-term memory
- Semantic: facts and concepts, such as facts about a user.1
- Episodic: past events or actions, such as what the agent did last time.1
- Procedural: the rules for doing a task, such as the agent's system prompt.1
Most client projects start with semantic memory: a user's role, preferred language or account details, so they do not repeat themselves.
A tested example
This LangGraph agent saves a fact when a message starts with remember:, and otherwise reports its turn count (short-term) and the facts it knows (long-term). The model call is replaced by plain code so it runs with no API key. We ran it with langgraph 1.2.24.
from dataclasses import dataclass
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import StateGraph, MessagesState, START
from langgraph.runtime import Runtime
from langgraph.store.memory import InMemoryStore
@dataclass
class Context:
user_id: str
def agent(state: MessagesState, runtime: Runtime[Context]):
ns = (runtime.context.user_id, "facts")
text = state["messages"][-1].content
if text.startswith("remember:"): # long-term: save a fact for this user
runtime.store.put(ns, "lang", {"fact": text.split(":", 1)[1].strip()})
return {"messages": [{"role": "ai", "content": "Saved."}]}
facts = [i.value["fact"] for i in runtime.store.search(ns)]
turns = len(state["messages"]) # short-term: this thread's history
return {"messages": [{"role": "ai", "content": f"turn {turns}, I know: {facts}"}]}
g = StateGraph(MessagesState, context_schema=Context)
g.add_node(agent)
g.add_edge(START, "agent")
app = g.compile(checkpointer=InMemorySaver(), store=InMemoryStore())
def say(thread, text, user="u1"):
out = app.invoke({"messages": [{"role": "user", "content": text}]},
{"configurable": {"thread_id": thread}}, context=Context(user_id=user))
print(thread, user, "->", out["messages"][-1].content)
say("chat-1", "remember: I write Python")
say("chat-1", "hello")
say("chat-2", "hello") # new thread: history resets, facts stay
say("chat-3", "hello", user="u2") # another user: no facts
Output:
chat-1 u1 -> Saved.
chat-1 u1 -> turn 3, I know: ['I write Python']
chat-2 u1 -> turn 1, I know: ['I write Python']
chat-3 u2 -> turn 1, I know: []
Read it line by line. In chat-2 the history resets because it is a new thread, but the fact survives because it lives in the store under user u1. User u2 sees nothing, because their namespace is different. That separation is what stops one customer's data leaking into another's answers.
What to change for production
- Use a database.
InMemorySaverandInMemoryStoreare for development; LangGraph ships Postgres versions,PostgresSaverandPostgresStore, for production.2 - Search by meaning. Give the store an embedding model and
store.search(namespace, query=...)returns the memories closest to the question, the same idea as RAG.2 - Forget on purpose. Long histories can overflow the context window and models often do worse over long contexts, so remove stale information.1
- Test it. Add memory cases to your evals: does the agent recall the right fact, and never another user's?
Memory is one of the pieces that turns a demo agent into one a client can use every day. Zero to FDE builds agents step by step in the roadmap; it is self-paced and written, with no live classes, mentors or certificate.
Zero to FDE is a self-paced 16-week course, ₹2,999 once, with a 7-day full refund. Week 1 is free, and one Week 4 lesson is free if you already write backend code. It has no live classes, no mentors and no accredited certificate.
Sources
Zero to FDE is a 16-week path, for working engineers and AIML graduates, to the work Forward Deployed Engineers do: backend basics, LLMs, RAG, agents, evaluation and deployment, with a shipped deliverable every week. Week 1 is free and complete, no card needed.
Start Week 1 freeMore from the blog
- Forward Deployed Engineer jobs in 2026: what the data says
- What is RAG? Retrieval-augmented generation, explained with working code
- What is an AI agent? The agent loop, explained with code
- AI engineer roadmap 2026: what to learn, and in what order
- Will AI replace software engineers? What the data says in 2026
- Forward Deployed Engineer courses in India (2026): fees, format and how they compare
- Forward Deployed Engineer vs ML engineer: which AI role fits you?
- Forward Deployed Engineer salary in India: what the 2026 data says for 2027
- Forward Deployed Engineer interview questions: the six rounds and how to answer
- Why Forward Deployed Engineer is a smart next move for a software engineer
- Forward Deployed Engineer certification in 2026: what exists, what it costs, and what employers check
- Forward Deployed Engineer skills: what 1,000 job posts ask for
- Forward Deployed Engineer vs Solutions Engineer: the real difference
- Forward Deployed Engineer resume: what to put on one page
- Forward Deployed Software Engineer (FDSE): what the Palantir title means
- Forward deployed AI engineer, AI deployment engineer, FDE: the titles explained
- Prompt injection explained: what it is and how to defend against it
- Context engineering explained: beyond prompt engineering
- RAG vs fine-tuning: which one to use, and when
- LLM evals explained: how to test a system that gives different answers
- LLM observability explained: traces, cost and what to log
- Tool calling explained: how an LLM uses your functions
- What is MCP? The Model Context Protocol explained
- AI agent vs workflow: which one does your problem need?
- AI engineer vs ML engineer: what each one does
- AI engineer interview questions: 25 that test whether you have built anything
- What is a vector database? Explained with a 30-line example
- EY now hires Forward Deployed Engineers for audit. The role is leaving the AI labs
- LangGraph explained: state, nodes and edges, with a 30-line example
- Randstad: 90% of Indian employers are growing tech teams for AI. What it means for engineers
- LLM cost optimization: prompt caching, batching and model routing, with the numbers
- Structured outputs from an LLM: JSON schema, validation and retries
- Embeddings explained: vectors, cosine similarity and dimensions
- Data engineer to AI engineer: what carries over and what to learn
- AWS launches a Forward Deployed Engineering Competency, with Infosys, TCS and Coforge among 22 launch partners
- Forward Deployed Architect: what the role is, certifications and courses
- Persistent launches a Forward Deployed Engineering program with Microsoft, a day after NIIT's FDE talent blueprint
- How to become an AI engineer in India: the route depends on where you start
- Self-paced Forward Deployed Engineer courses in India under ₹10,000 (and under ₹3,000)
- AWS and OpenAI will jointly staff forward deployed engineering teams inside customer environments
- Backend developer to AI engineer: what carries over and what to learn
- Claude now runs on premises in customers' own data centers through AWS AI Factories
- Agentic AI courses compared: four free options, and what a course must make you build
- AWS: attacks on AI systems grew about 800% in 2026, and an AI agent broke into a decoy MCP server in 12.7 minutes