Multi-turn conversations

Claude API · Essentials · 9 min

Every chat app, and every tool loop later on, is built by appending to this history list.

The Messages API is stateless: it does not remember earlier requests. Each call is like talking to someone with no memory of the last minute. To hold a conversation, your program keeps the history and sends all of it every time.

The history is just the messages list. After each reply you append two things: Claude's answer as an assistant message, and the user's next question as a user message. Roles must alternate, starting with user.

The easiest way to store Claude's answer is to append response.content as is. It is a list of blocks, and the API accepts it straight back. This matters later, because tool calls and thinking blocks must be returned unchanged.

Because you resend everything, each turn costs more input tokens than the last, and a very long chat will eventually not fit in the context window (the most text the model can consider at once). Common fixes are to drop or summarise old turns, or to cache the unchanging start of the conversation (a later lesson).

You can also write assistant turns yourself. That is useful in tests or to show the model an example exchange, but on current models you cannot end the list with a half-written assistant message to force how the reply starts (this old trick, "prefill", is rejected).

Example

import anthropic

client = anthropic.Anthropic()
history = []

def ask(text: str) -> str:
    history.append({"role": "user", "content": text})
    reply = client.messages.create(
        model="claude-opus-5-5", max_tokens=300, messages=history
    )
    history.append({"role": "assistant", "content": reply.content})
    return "".join(b.text for b in reply.content if b.type == "text")

print(ask("My name is Ana and I like chess."))
print(ask("What is my name and hobby?"))   # works: history was resent
print(len(history))                        # 4 messages

Remember

  • The API keeps no state; resend the full history
  • Append response.content as the assistant turn
  • Long histories cost more and can overflow the context window

Watch out for

  • Sending only the newest question and expecting Claude to remember the rest.

Check yourself

  1. Why does the second question in the example work?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: platform.claude.com/docs/en/build-with-claude/working-with-messages