How Conversation History Works with a Stateless Chat API
The Claude API is stateless. It does not remember your previous requests, so for a multi-turn conversation your code must send the full history in the messages array on every call. The "memory" of a chat is nothing more than the list your application keeps and re-sends, which is why history size is the first thing to manage in any long-running conversation.
What the history looks like
Messages alternate between roles user and assistant. Each call you add the new user message, send the whole list, then append the assistant's reply so it is part of the next call.
import anthropic
client = anthropic.Anthropic()
MODEL = "claude-sonnet-5-5"
SYSTEM = "You are a friendly assistant. Keep answers under 40 words."
history = []
def chat(user_text: str) -> str:
history.append({"role": "user", "content": user_text})
response = client.messages.create(
model=MODEL,
max_tokens=2000,
system=SYSTEM,
messages=history,
)
reply = "".join(b.text for b in response.content if b.type == "text")
history.append({"role": "assistant", "content": reply})
print(f"[input tokens this call: {response.usage.input_tokens}]")
return reply
print(chat("My name is Priya and I am learning Rust."))
print(chat("What is my name?"))
print(chat("Suggest a first project for me."))
Run this and watch the bracketed numbers. The input token count rises with every call, because each call re-sends everything that came before. The second answer will correctly say your name is Priya, not because the model remembered, but because the first exchange was in the list.
Cost grows faster than you think
If each turn adds about 300 tokens, then turn 1 sends around 300, turn 10 sends about 3,000, and turn 50 sends around 15,000. The total tokens you pay for across 50 turns is the sum of all those calls, which is much more than 15,000. This quadratic-like growth is why long conversations get expensive, and why prompt caching (post 43) is so valuable: the repeated prefix is billed at a lower rate when cached.
Rules for the messages array
- The first message must have the
userrole. - Keep tool calls and their results together: every
tool_useblock must be followed by a matchingtool_result. If you trim history, never split such a pair. - Preserve assistant content blocks as the API returned them when your conversation involves tools or other special blocks. Appending only the text can lose information.
- Your system prompt is separate from
messages. It is sent every call but does not live in the list.
The history is your data, not the API's
Because you own the list, you can change it. You can drop old turns, replace them with a summary, remove bulky tool results, or inject facts. All of these are context engineering moves, and the rest of this course builds on this idea. The model only ever sees what you put in the request.
Persisting a conversation
If users return later, store the list in your database and load it. Keep each conversation's list under its own id, and be careful with privacy: history can contain personal information. A simple approach is to save JSON after each turn.
import json
from pathlib import Path
def save(conversation_id: str, history: list) -> None:
Path(f"{conversation_id}.json").write_text(json.dumps(history), encoding="utf-8")
def load(conversation_id: str) -> list:
path = Path(f"{conversation_id}.json")
return json.loads(path.read_text(encoding="utf-8")) if path.exists() else []
This works for plain text turns. If your history contains SDK objects such as content blocks returned by a tool-using call, convert them to plain dictionaries before saving, for example with each block's model_dump() method.
When history becomes a problem
Watch for three signs: rising cost per turn, rising latency and falling answer quality as the chat gets long. When you see them, the next posts give you options: sliding windows (post 32), rolling summaries (post 33), clearing old tool results (post 52) and server-side compaction (post 53).
Roles, system messages and what you can insert
Beginners often ask where a "memory" feature would live. In the plain Messages API there is none; any memory is something you build by choosing what to put in system and messages. That is good news, because it means you can inspect and test every piece. If a user says "remember that I prefer short answers", you can store that preference in your database and add it to the system prompt on later calls, which is a transparent and controllable form of memory (posts 34 to 38).
It also means you can correct mistakes. If an earlier assistant reply contained a wrong statement that keeps influencing later turns, you can edit or remove it from your stored list. Be aware that some features, such as extended reasoning blocks that must be passed back unchanged, have rules about editing history, so check the SDK documentation for the model you use before rewriting earlier turns in a tool-using agent.
Summary
- No server-side chat memory exists; your list is the memory.
- Every call pays for the whole list again.
- You are free, and expected, to edit the list wisely.
Comments
No comments yet. Have a question or a tip? Be the first to share it.