← Building with AI

A chatbot loop

Read input, reply, repeat until the user says quit.

Start this lesson

A chatbot is a loop: read what the user types, add it to history, ask the model, show and save the answer, and go round again. You also need a way out, like typing quit. Putting the pieces from this unit into a while loop gives you a working chatbot in about ten lines.

# To run on your own computer with an API key (it cannot run in this browser).
# First: pip install anthropic, and set the ANTHROPIC_API_KEY environment variable.
import anthropic
client = anthropic.Anthropic()
history = []

while True:
    text = input("You: ")
    if text.lower() in ("quit", "bye"):
        print("Goodbye!")
        break
    history.append({"role": "user", "content": text})
    reply = client.messages.create(model="claude-sonnet-5-5", max_tokens=400,
                                   system="You are a kind homework helper.", messages=history)
    answer = reply.content[0].text
    history.append({"role": "assistant", "content": answer})
    print("Bot:", answer)

while True runs forever until break. The quit check comes BEFORE the model call, so typing quit doesn't cost anything.

In these exercises the user's typing is filled in for you (it is listed with the exercise), so input() gets the same answers every time.