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

Chat exercise

Summary audio

No audio recap for this lesson.

Study notes

Core Workflow

  • Prompt user for text input using the built-in input() function
  • Add user message to a messages list
  • Pass messages list to the chat API function
  • Receive generated response from Claude
  • Add assistant response to messages list
  • Print the response
  • Loop back to step 1 indefinitely (using while True)

Key Implementation Steps

  • Initialize an empty messages list at the start
  • Use add_user_message() to append user input to the messages list
  • Call the chat() function with the messages list to get Claude's response
  • Use add_assistant_message() to append Claude's response to the messages list
  • Print responses with optional formatting (e. g. , dashes) for clarity

Important Concept

  • The messages list maintains conversation history and context, allowing Claude to reference previous exchanges in subsequent responses
  • This enables multi-turn conversations where later responses are aware of earlier messages

Loop Control

  • The chatbot runs indefinitely until manually interrupted by the user (using the interrupt button and escape key)

Takeaways

  • The chatbot maintains a messages list that stores the full conversation history, enabling Claude to reference previous exchanges in multi-turn conversations
  • Core workflow loops indefinitely: get user input → add to messages list → call chat API → add response to messages list → print response
  • Use add_user_message() and add_assistant_message() helper functions to properly append messages to the list before passing to the chat function
  • The messages list is initialized empty at startup and persists throughout the session to preserve context across all exchanges
Flashcards 8 cards
Question
click to reveal · ←/→
Answer
click to flip back
Export to Anki (.tsv) ↓
Knowledge check 1 questions