How to Add Memory to a Claude Chatbot
Claude has no built-in memory between API calls. Every request is stateless — the model only "remembers" what you include in the messages array you send. If your chatbot forgets who the user is, what they said five minutes ago, or a preference they set last week, the fix isn't a setting to toggle on. It's an architecture decision: you have to store conversation data somewhere and re-inject the relevant parts into each new request.
This guide covers the three practical layers of memory you can add to a Claude-based chatbot — short-term history, summarized long-term memory, and retrieval-based memory — plus working code for each.
Why Claude "forgets" by default
The Messages API takes a list of {role, content} objects and returns a completion based only on that list. There's no session, no user ID, no server-side state. If you send one message, Claude answers with zero awareness of anything before it. Memory has to be built on your side: your app decides what to store, what to forget, and what to send back on the next turn.
This matters for cost too — every token of "memory" you inject gets billed as input tokens on every single request. Good memory design is as much about compression as it is about storage.
Layer 1: Short-term memory (raw conversation history)
The simplest form of memory is just keeping the running conversation and replaying it:
let history = [];
async function sendMessage(userText) {
history.push({ role: "user", content: userText });
const res = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "claude-sonnet-4",
max_tokens: 1024,
messages: history
})
});
const data = await res.json();
history.push({ role: "assistant", content: data.content[0].text });
return data.content[0].text;
}
This works fine for short sessions but breaks down fast: context windows fill up, latency grows, and costs climb with every turn. You need a strategy for what happens once the conversation gets long — that's where the next two layers come in. The Messages docs cover the exact request shape if you're setting this up from scratch.
Layer 2: Summarized long-term memory
Instead of keeping every message forever, periodically compress older turns into a summary and drop the raw text. This gives the chatbot persistent memory of facts and context without the token cost of full history.
A common pattern:
- Keep the last N turns verbatim (recent context matters most).
- Every time history exceeds a threshold, ask Claude to summarize everything older than that into a few sentences.
- Store the summary per user (in a database, not in memory) and prepend it as a system message on future requests.
async function summarize(oldMessages) {
const res = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json"
},
body: JSON.stringify({
model: "claude-sonnet-4",
max_tokens: 300,
messages: [{
role: "user",
content: `Summarize the key facts, preferences, and decisions from this conversation in under 100 words:\n\n${JSON.stringify(oldMessages)}`
}]
})
});
const data = await res.json();
return data.content[0].text;
}
Store that summary against the user's ID and prepend it on the next session:
const messages = [
{ role: "user", content: `Context from earlier conversations: ${storedSummary}` },
...recentMessages
];
This is the pattern most production chatbots use for "remembering" users across sessions — it's cheap, simple, and doesn't require a vector database.
Layer 3: Retrieval-based memory (for large or structured histories)
If your bot needs to recall specific facts from months of conversation — not just a vague summary — store individual memory entries (facts, preferences, past decisions) as embeddings in a vector store, and retrieve only the relevant ones per query.
Rough flow:
- After each conversation, extract discrete facts ("user prefers metric units", "user's project deadline is March") and store each as a vector embedding with metadata.
- On a new message, embed the user's query and run a similarity search against stored facts.
- Inject the top few matches as context before calling Claude.
const relevantMemories = await vectorStore.query(userQuery, { topK: 5 });
const memoryContext = relevantMemories.map(m => `- ${m.text}`).join("\n");
const messages = [
{ role: "user", content: `Relevant facts about this user:\n${memoryContext}\n\nUser message: ${userQuery}` }
];
This scales much better than summarization alone because you're only paying for the tokens that are actually relevant to the current query, not a growing blob of history. The tradeoff is infrastructure — you now need an embedding model and a vector database alongside Claude.
Choosing a strategy
- Short conversations, single session → raw history is fine.
- Returning users, ongoing relationship → summarized memory, stored per user ID.
- Large knowledge base, specific fact recall, many users → retrieval-based memory with embeddings.
Most real chatbots combine all three: recent turns kept verbatim, an evolving summary for long-term continuity, and retrieval for specific facts when the conversation gets large or technical.
If you're building this on top of a raw Anthropic key, you'll also need to handle streaming, tool calls, and usage tracking yourself. SubToAPI wraps Claude access behind a standard HTTPS API with application keys (sub_live_...), so your memory layer sits on top of normal /v1/messages calls — streaming and tool use work the same way regardless of how much context you're injecting. Check the quickstart to get a key and see the request format, or look at pricing if you're evaluating it for a team project.
FAQs
Does Claude have native memory across sessions? No. The API is stateless — every request only knows what's in the messages array you send. Any persistence (user profiles, past conversations, preferences) has to be stored and re-injected by your application.
How much conversation history should I keep in each request? Enough for coherence, not more. A common approach is keeping the last 10–20 turns verbatim and replacing anything older with a short summary, which keeps token costs predictable as conversations grow.
Do I need a vector database to add memory? Only if you need precise recall of specific facts across a large history. For most chatbots, periodic summarization stored in a regular database is simpler, cheaper, and good enough.