Claude API Agent Memory Implementation Guide
Claude's API is stateless by default: every request you send contains the full conversation so far, and Claude has no awareness of anything outside that request's context window. "Agent memory" is the engineering layer you build on top of the API to make an agent behave as if it remembers users, decisions, and facts across turns and sessions. There is no built-in "memory" endpoint — you implement it yourself using a combination of context management, external storage, and retrieval.
This article walks through the practical patterns for doing that: what to store, where to store it, how to get it back into the prompt, and how to keep costs and latency under control as conversations grow.
Why memory isn't free with a stateless API
Every call to Claude's Messages API takes a messages array as input. Claude processes exactly what you send — nothing more. If you want the model to "remember" that a user prefers metric units or that a support ticket was opened three days ago, that information has to be re-injected into the request every single time. The implementation challenge isn't convincing Claude to use memory — it's deciding what memory to keep, how to compress it, and when to fetch it.
There are three distinct memory problems that get conflated under one term:
- Short-term (session) memory — the current conversation's turn history.
- Long-term (user) memory — facts, preferences, and history that persist across sessions.
- Working memory — the subset of both that actually fits in the current context window.
Each needs a different implementation strategy.
Pattern 1: Raw history with a sliding window
The simplest approach is to keep appending messages to the array and truncate from the oldest end once you approach a token budget.
function buildMessages(history, maxTurns = 20) {
return history.slice(-maxTurns);
}
This works for short-lived conversations but breaks down fast: important early context gets dropped silently, and token costs grow linearly with conversation length. It's a fine starting point, not a real memory system.
Pattern 2: Rolling summarization
A better approach is to periodically compress older turns into a running summary, then prepend that summary instead of the raw turns. When the conversation crosses a turn or token threshold, send the older messages back to Claude with an instruction like "summarize the key facts, decisions, and open questions from this conversation in under 200 words," and store the result.
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-5",
max_tokens: 300,
messages: [
{ role: "user", content: `Summarize the key facts and decisions from this conversation:\n\n${JSON.stringify(oldMessages)}` }
]
})
});
const data = await res.json();
return data.content[0].text;
}
Each new request becomes: [system prompt] + [running summary] + [last N raw turns]. This keeps token usage bounded while preserving continuity. The trade-off is some loss of fidelity — summaries lose exact wording and edge-case details, so don't rely on this alone for anything that needs precise recall (legal clauses, numbers, exact quotes).
Pattern 3: External storage with retrieval (RAG-style memory)
For long-term, user-level memory, store discrete facts outside the prompt entirely — in a database, key-value store, or vector index — and retrieve only what's relevant to the current turn.
A practical schema:
{
"user_id": "u_123",
"fact": "Prefers responses in metric units",
"source": "conversation on 2024-03-02",
"embedding": [0.021, -0.013, ...]
}
At request time: embed the user's current message, run a similarity search against stored facts, and inject the top-k matches as a short context block before the actual user turn. This scales far better than summarization alone because retrieval cost doesn't grow with total memory size — only with how many facts you choose to pull back.
If your agent needs to decide when to look something up rather than always retrieving, model this as a tool call. Define a search_memory tool, let Claude decide when it needs more context, and return results from your store as a tool result. This is the same mechanical pattern as any other function calling setup — see /docs/tools for the request/response shape if you're implementing retrieval as a callable tool through SubToAPI.
Pattern 4: Structured state instead of free text
Not all memory should be prose. For task-oriented agents (order tracking, onboarding flows, multi-step forms), store state as structured JSON rather than natural language, and only render it into a prompt string when building the request:
const state = {
step: "collect_shipping_address",
completed: ["email", "name"],
pending: ["address", "payment"]
};
This is cheaper, more reliable to parse, and avoids the model hallucinating what "step" it's on because the state was ambiguously worded in a summary.
Putting it together: a minimal memory loop
A production agent typically combines all three: structured state for task progress, a rolling summary for conversational continuity, and vector retrieval for long-term facts. The request-building logic looks roughly like:
async function buildRequest(userId, sessionId, newMessage) {
const state = await getState(sessionId);
const summary = await getSummary(sessionId);
const facts = await retrieveFacts(userId, newMessage);
return {
model: "claude-sonnet-4-5",
system: `Task state: ${JSON.stringify(state)}\nKnown facts: ${facts.join("; ")}`,
messages: [
{ role: "user", content: `${summary}\n\n${newMessage}` }
]
};
}
If you're routing these calls through SubToAPI, the implementation on the Claude side doesn't change — you're still sending a standard Messages request to https://api.subtoapi.app/v1/messages with your sub_live_... key. SubToAPI adds usage metadata per request and per-team API key management on top, which is useful once you have multiple agents or customers each generating their own memory stores and you need to track consumption per source. See /docs/messages for the request format and /docs/quickstart to get a key set up.
Keeping memory honest
Memory implementations fail quietly when they drift — stale facts contradict new ones, summaries compound errors over many rounds, or retrieval pulls irrelevant results that confuse the model. Mitigations worth building in from day one:
- Timestamp every stored fact and prefer recent ones on conflict.
- Cap summary regeneration depth — summarize from raw history periodically, not summary-of-a-summary repeatedly, to avoid compounding drift.
- Log what was injected into each request so you can debug why the agent said something odd.
- Expire session memory separately from user memory — a task's working state shouldn't outlive the task.
None of this requires a specialized "memory API." It's standard application engineering — storage, retrieval, and careful prompt assembly — applied around a stateless model API.
Questions
Does Claude's API have a built-in memory feature? No. The Messages API is stateless — every request must include full conversation context. Memory is implemented by the application, typically through history management, summarization, or external storage with retrieval.
What's the difference between session memory and long-term memory for an agent? Session memory covers the current conversation's turn history and task state, cleared when the session ends. Long-term memory persists facts and preferences across sessions, usually stored externally and retrieved per request based on relevance.
Should I use vector search or just keep summarizing the conversation? Use summarization for conversational continuity within a session, and vector retrieval for facts that need to persist and be recalled accurately across many sessions. Summarization alone loses precision over time; retrieval scales better for long-term, fact-heavy memory.