Careeroza
Multi-turn Conversations
The API Is Stateless
The model does not remember earlier calls. To have a conversation, your app keeps a list of messages and sends the whole list every time: user, assistant, user, assistant, ... After each reply, append it to the list.
History in Action
Example
A stand-in for the model replies from simple rules, but the history handling is exactly what real code does. Watch the list grow:
def fake_model(messages):
"""Stand-in for the model: it can only 'remember' what is in messages."""
last = messages[-1]["content"].lower()
names = [m["content"].split("is ")[-1] for m in messages
if m["role"] == "user" and "my name is" in m["content"].lower()]
if "my name" in last and "?" in last:
return f"Your name is {names[0]}." if names else "I don't know your name yet."
return "Nice to meet you!" if names else "Hello! How can I help?"
history = []
def chat(text):
history.append({"role": "user", "content": text})
reply = fake_model(history)
history.append({"role": "assistant", "content": reply})
print(f"user: {text}\nbot: {reply} (messages sent: {len(history) - 1})")
chat("Hi")
chat("My name is Priya")
chat("What is my name?")
print("\nWithout history:", fake_model([{"role": "user", "content": "What is my name?"}]))Output
user: Hi bot: Hello! How can I help? (messages sent: 1) user: My name is Priya bot: Nice to meet you! (messages sent: 3) user: What is my name? bot: Your name is Priya. (messages sent: 5) Without history: I don't know your name yet.
With the Real API
history = []
def chat(user_text: str) -> str:
history.append({"role": "user", "content": user_text})
response = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=500,
system="You are the ShopEase support assistant.",
messages=history,
)
reply = next(b.text for b in response.content if b.type == "text")
history.append({"role": "assistant", "content": reply})
return reply
print(chat("I ordered running shoes, size 9."))
print(chat("Can I exchange them for size 10?")) # the model sees the first message tooTip: Every turn resends the whole history, so input tokens (and cost) grow with each turn. Long chats need trimming or summarizing (medium level).