How to save Claude conversation history in python
Quick answer
To save Claude conversation history in Python, maintain a list of message dictionaries representing the chat turns and pass this list to
client.messages.create with the system parameter. Append each user and assistant message to this list to preserve context across calls.PREREQUISITES
Python 3.8+Anthropic API keypip install anthropic>=0.20
Setup
Install the Anthropic Python SDK and set your API key as an environment variable.
pip install anthropic>=0.20 Step by step
Use a Python list to store the conversation history as message dictionaries. Pass this list to client.messages.create on each request to maintain context. Append new user and assistant messages to the list to save the full conversation.
import os
import anthropic
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
# Initialize conversation history
conversation_history = []
# Function to send a message and save history
def chat_with_claude(user_input):
# Append user message
conversation_history.append({"role": "user", "content": user_input})
# Call Claude with full conversation history
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1000,
system="You are a helpful assistant.",
messages=conversation_history
)
# Extract assistant reply
assistant_message = response.choices[0].message.content
# Append assistant message
conversation_history.append({"role": "assistant", "content": assistant_message})
return assistant_message
# Example usage
reply = chat_with_claude("Hello Claude, how are you?")
print("Claude:", reply)
# Conversation history is saved in conversation_history list
print("Conversation history:", conversation_history) output
Claude: Hello! I'm doing well, thank you. How can I assist you today?
Conversation history: [{'role': 'user', 'content': 'Hello Claude, how are you?'}, {'role': 'assistant', 'content': "Hello! I'm doing well, thank you. How can I assist you today?"}] Common variations
- Use different Claude models by changing the
modelparameter, e.g.,claude-3-5-haiku-20241022. - Implement async calls with
asyncioandclient.messages.acreatefor concurrency. - Save conversation history to a file or database by serializing the
conversation_historylist as JSON.
Troubleshooting
- If you get truncated responses, increase
max_tokens. - If conversation context is lost, ensure you pass the full
conversation_historylist on every request. - Check your
ANTHROPIC_API_KEYenvironment variable is set correctly to avoid authentication errors.
Key Takeaways
- Maintain a list of messages to preserve Claude conversation history in Python.
- Pass the full conversation history on each API call to keep context.
- Append both user and assistant messages to the history list after each turn.