Learn how message history turns separate API calls into a multi-turn conversation.
Download the runnable notebook
This complete lesson was converted from the matching notebook stored locally in the TechClub repository. Outputs are cleared; never add API keys or private data.
Goal, prerequisites, and setup
Learn the request/response cycle and how to preserve conversation state. Know Python lists, dictionaries, functions, and environment variables. Create a virtual environment, install anthropic and python-dotenv, set ANTHROPIC_API_KEY and ANTHROPIC_MODEL, and verify the selected notebook interpreter.
Run the one-question example first. Then change the follow-up message and inspect the complete messages list. Save the redacted request sequence and explain why the assistant message must be added before the next user message.
# Optional - Install dependencies
%pip install anthropic python-dotenv
# Load environment variables
from dotenv import load_dotenv
load_dotenv()
# Create an API client
import os
from anthropic import Anthropic
client = Anthropic()
model = os.getenv("ANTHROPIC_MODEL")
def add_message(messages, role, content):
message = {"role": role, "content": content}
messages.append(message)
def add_user_message(messages, content):
add_message(messages, "user", content)
def add_assistant_message(messages, content):
add_message(messages, "assistant", content)
def chat(messages):
message = client.messages.create(
model=model,
max_tokens=1000,
messages=messages,
)
return message.content[0].text
# Make a starting list of messages
messages = []
# Add in the initial user question of "Define quantum computing in one sentence."
add_user_message(messages, "Define quantum computing in one sentence.")
# Pass the list of message into 'chat' to get an answer
answer = chat(messages)
# Take the answer and add it as an assistant message into our list
add_assistant_message(messages, answer)
# Add in the user's follow-up question
add_user_message(messages, "Write another sentence")
# Call chat again with the list of messages to get a final answer
answer = chat(messages)
# Take the answer and add it as an assistant message into our list
add_assistant_message(messages, answer)
print(messages)
Evidence and references
- Submit the notebook, a redacted two-turn message list, and a short explanation of message roles.
- Anthropic Messages API
- Python environment variables