Claude API Agent Memory & State Management
Why Claude agents need explicit memory management
The Claude API is stateless. Every request you send is evaluated independently — there's no server-side session that remembers what happened five minutes ago, or even five seconds ago. If you want an agent that remembers earlier steps, tool results, user preferences, or progress through a multi-step task, you have to build and manage that state yourself.
This is the core problem behind "claude api agent memory state management": how do you persist context across turns without blowing your token budget, losing accuracy, or writing a fragile mess of ad-hoc session logic? The answer is a combination of a few well-understood patterns — conversation windowing, external storage, summarization, and structured state objects — applied consistently depending on how long-lived and how large your agent's context needs to be.
The three layers of agent memory
Most production agents need memory at three different timescales, and conflating them is where most implementations go wrong.
1. Turn-level state (the current task)
This is the scratchpad for whatever the agent is doing right now: the current plan, intermediate tool results, partial outputs. It lives entirely in the messages array you send with each request and typically gets discarded once the task completes.
let messages = [
{ role: "user", content: "Research competitor pricing and summarize." }
];
// After each tool call or model response, append to the array
messages.push({ role: "assistant", content: assistantResponse });
messages.push({ role: "user", content: toolResultAsText });
2. Session-level memory (the conversation)
This is what most people mean by "chat history" — everything said in the current session. The problem is that it grows linearly, and Claude's context window, while large, is not infinite, and larger context means slower, more expensive requests.
The standard fix is a sliding window with periodic summarization: keep the last N turns verbatim, and replace everything older with a compressed summary injected as a system or user message.
function buildMessages(history, summary) {
const recent = history.slice(-10);
const base = summary
? [{ role: "user", content: `Conversation summary so far: ${summary}` }]
: [];
return [...base, ...recent];
}
Generate the summary itself with a cheap, dedicated call to Claude whenever the history crosses a threshold (e.g., 20 turns or a token count), rather than doing it inline with every request.
3. Long-term / cross-session memory
This is state that needs to survive after the session ends: user preferences, facts learned about a customer, prior decisions in a long-running project. This should never live in the prompt by default — it should live in a database or vector store and be retrieved selectively.
A common pattern:
// 1. Store facts as they're learned
await db.memories.insert({
userId,
fact: "Prefers responses in metric units",
embedding: await embed(fact)
});
// 2. At request time, retrieve only relevant memories
const relevant = await db.memories.search(embedding(currentQuery), { userId, limit: 5 });
const systemPrompt = `User context:\n${relevant.map(m => m.fact).join("\n")}`;
This keeps your prompt small and relevant instead of dumping every fact you've ever learned about a user into every request.
Designing state objects for multi-step agents
For agents that execute multi-step plans (research, data pipelines, approvals), store state as a structured object, not just a message array. This makes it possible to pause, resume, retry, or inspect the agent at any point.
{
"taskId": "task_8821",
"status": "awaiting_tool_result",
"step": 3,
"plan": ["search", "extract", "summarize", "notify"],
"toolResults": {
"search": { "query": "...", "result": "..." }
},
"messages": [ /* trimmed conversation window */ ]
}
Persist this object (Postgres, Redis, or even a flat JSON blob) after every step. This is what makes agents resumable across process restarts, retries after rate limits, or handoffs between workers — which matters a lot once you're running agents in production rather than a notebook.
Managing state with tool use
When your agent calls external tools, tool results are themselves part of the state you need to manage. Don't re-send the full raw tool output on every subsequent turn if it's large — store it separately and reference a summary or ID in the conversation.
messages.push({
role: "user",
content: `Tool "search" returned 1,200 results. Top 5 summarized: ${summary}. Full result stored as ref:${resultId}.`
});
The agent can then explicitly request the full result by ID if it actually needs it, rather than carrying it in every subsequent call.
Where SubToAPI fits
If you're running Claude-backed agents behind an application rather than calling the API directly from a script, you still need the memory and state patterns above — SubToAPI doesn't replace that logic. What it does handle is the infrastructure around it: issuing scoped sub_live_... application keys per agent or environment, streaming responses for long-running agent steps (see /docs/streaming), structured tool use calls (/docs/tools), and usage metadata per key so you can see exactly which agent or session is consuming tokens.
A typical setup looks like:
curl https://api.subtoapi.app/v1/messages \
-H "Authorization: Bearer $SUBTOAPI_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-opus-4",
"max_tokens": 1024,
"messages": [{"role": "user", "content": "Continue task_8821, step 4"}]
}'
Your state object stays in your own database — SubToAPI just gives you a clean, metered API surface to call Claude from, with the request/response shape documented at /docs/messages. Full setup is in /docs/quickstart, and plans start at €9/month on /pricing.
Practical checklist
- Separate turn-level, session-level, and long-term memory — don't store them the same way.
- Summarize old history instead of truncating it silently.
- Persist agent state as a structured object you can inspect and resume, not just a growing message array.
- Store large tool results externally; reference them by ID in the conversation.
- Retrieve long-term memories selectively per request instead of injecting everything.
Questions
Does the Claude API have built-in session memory? No. Every API call is stateless; the model only sees what's in the messages array you send. Memory and state are entirely your application's responsibility.
How much conversation history should I keep in context? Keep enough recent turns for coherence (often 10–20) and summarize everything older into a compact note. This balances accuracy against token cost and latency.
Where should long-term agent memory be stored? In a database or vector store outside the prompt, retrieved selectively per request based on relevance — not injected wholesale into every call.