Extend a single API request into a safe, multi-turn chatbot exercise.

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

Practice turning the request example into a loop while preserving message history. Complete 001_requests first; know Python loops, functions, lists, and exceptions. Install the same packages as the previous lesson, set ANTHROPIC_API_KEY and ANTHROPIC_MODEL, and never print the token.

Before using while True, test one fixed input. Add an explicit exit command, handle an empty input, and catch only the provider errors you can explain. Save a redacted transcript and a note about how unbounded history affects cost.

# 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, content, role):
    message = {"role": role, "content": content}
    messages.append(message)

def chat(messages):
    message = client.messages.create(
        model=model,
        max_tokens=1000,
        messages=messages,
    )

    return message.content[0].text
# Make an initial list of messages
messages = []

# Use a 'while True' loop to run the chatbot forever
while True:
    # Get user input
    user_input = input("> ")
    print(">", user_input)

    # Add it to a list of messages
    add_message(messages, user_input, role="user")

    # Call the API
    answer = chat(messages)

    # Add generated text to the list messages
    add_message(messages, answer, role="assistant")

    # Print the generated text
    print("---")
    print(answer)
    print("---")

Evidence and references