Claude With The Anthropic Api
← All lessons
Lesson 06Claude With The Anthropic Api

Multi-Turn conversations

Summary audio

No audio recap for this lesson.

Study notes

Key Problem: No Message Storage

  • The Anthropic API and Claude do not store any messages sent to them
  • Each API request is independent with no memory of previous interactions
  • Without intervention, follow-up messages have no context about earlier conversation

Solution: Manual Message History Management

  • You must manually maintain a list of all messages in your code
  • You must include the entire message history with every follow-up request
  • This allows Claude to see the full conversation context

Message Structure

  • Messages are stored as a list of dictionaries
  • Each message has two fields:
  • role: either "user" or "assistant"
  • content: the text of the message
  • Order matters—messages should reflect the chronological flow of conversation

Three Helper Functions for Conversation Management

add_user_message(messages, text)

  • Takes a message list and user text
  • Creates a user message dictionary and appends it to the list

add_assistant_message(messages, text)

  • Takes a message list and assistant text
  • Creates an assistant message dictionary and appends it to the list

chat(messages)

  • Wrapper around the messages. create API call
  • Takes the full message history as input
  • Returns just the text content of the response

Conversation Flow Pattern

  • Create empty messages list
  • Add user message with initial question
  • Call chat() with messages list
  • Add returned assistant response to messages list
  • Add follow-up user message to messages list
  • Call chat() again with updated full history
  • Repeat steps 4-6 for continued conversation

Takeaways

  • The Claude API doesn't store messages—you must manually maintain the full conversation history in your code and include it with every request
  • Messages are stored as a list of dictionaries with role ("user" or "assistant") and content fields, in chronological order
  • Use helper functions to add user/assistant messages to the list and call the API, then always pass the complete updated history for follow-up requests
  • The conversation pattern is: create empty list → add user message → call chat() → add assistant response → add next user message → call chat() again with full history
Flashcards 9 cards
Question
click to reveal · ←/→
Answer
click to flip back
Export to Anki (.tsv) ↓
Knowledge check 5 questions