Find helpful tutorials or share inspiring use cases on AI technology for higher education.

Shared content may not reflect the policies of Tilburg University on the use of AI. 

Create Your Own AI Chatbot with the Anthropic API

Ever wanted to create your own AI chatbot? Today’s your lucky day! In this article, we’ll walk through building a chatbot using Anthropic’s Claude API. Don’t worry if you’re new to this, we’ll take it step by step, and before you know it, you’ll have your very own AI assistant running on your computer!

Getting Started

Before we dive into the fun part, make sure you have your Anthropic API credentials ready and the necessary Python environment set up.

  1. Python installed on your computer (Python 3.7 or newer)
  2. An Anthropic API key (obtainable from Anthropic’s website)
  3. Basic familiarity with running Python code
  4. A terminal or command prompt

If you haven’t set these up yet, check out our API setup guide first.

Let’s Create Your Own AI Chatbot

Step 1: Setting Up Our Project

Let’s start with the foundation of our chatbot. Create a new Python file called chatbot.py and add this code.

Python
from anthropic import Anthropic

# Create our connection to Claude
client = Anthropic()

# Choose which version of Claude we want to talk to
MODEL_NAME = "claude-3-5-sonnet-20241022"

Step 2: Your First Conversation

Let’s start with something simple, getting Claude to write if it does know something about us, Tilburg.ai! This is a great way to test that everything’s working:

Python
response = client.messages.create(
  model=MODEL_NAME,
  max_tokens=1000,
  messages=[
    {"role": "user", "content": "Could you tell me something about Tilburg.ai"}]
  
  print(response.content[0].text)

Step 3: Building the Real Chatbot

Now for the exciting part, creating our interactive chatbot!

Let’s examine each part of the chatbot code to understand how it creates an interactive conversation with Claude. We’ll break it down into logical sections and explore how they work together.

1. Creating Our Memory Storage

First, we create a place to store our conversation:

Python
print("Simple Chatbot (type 'quit' to exit)")

# Initialize our conversation history
messages = []

Think of this empty list as a blank notebook. Right now it’s empty, but soon it will contain our entire conversation with the chatbot. Every time someone speaks (whether it’s you or the chatbot), we’ll write it down in this notebook.

2. Setting Up the Conversation Loop

Python
while True:
    user_input = input("You: ")

This creates a continuous loop that keeps the chatbot running. The input() function waits for the you to type something and stores whatever they type in the user_input variable. This forms the basic interaction point between the you and the chatbot.

3. Exit Mechanism

Python
if user_input.lower() == 'quit':
    print("Goodbye!")
    break

This code checks if the you want to end the conversation. When you type in “quit” (in any combination of upper or lower case), the program will display a goodbye message and end the chat session by breaking out of the main loop.

4. Message Management

Python
messages.append({"role": "user", "content": user_input})

This adds the user’s message to the conversation history. It creates a dictionary with two pieces of information: the role (marking this as a user message) and the content (the actual text the user typed). This structured format helps the AI understand who said what in the conversation. The “role” tells Claude who is speaking, and the “content” contains the actual message. Each interaction adds to this history, allowing Claude to maintain context and provide more relevant responses.

For an example look at the following code, of an example interaction you could have with your chatbot.

Python
messages = [
    {"role": "user", "content": "Hello! How are you today?"},
    {"role": "assistant", "content": "I'm doing well, thank you! How can I help you today?"},
    {"role": "user", "content": "Can you help me write a poem about spring?"},
    {"role": "assistant", "content": "Here's a short poem about spring:/n Buds break through soil,\nWarm sunshine brings new life,\nNature awakens."}
]

5. Getting Claude’s Response

Python
try:
    response = client.messages.create(
        model=MODEL_NAME,
        max_tokens=200,
        messages=messages
    )

This section communicates with Claude’s API. Let’s break down each parameter:

  • model=MODEL_NAME: Specifies which version of Claude to use.
  • max_tokens=200: Sets a limit on how long the response can be.
  • messages=messages: Sends our entire conversation history.

6. Handling the Response

Python
asst_message = response.content[0].text
print("Assistant:", asst_message)
messages.append({"role": "assistant", "content": asst_message})

This section processes Claude’s response:

  1. response.content[0].text extracts the actual text from Claude’s response.
  2. The response is printed for you to see on your display .
  3. The response is added to our conversation history, so the chatbot will stay on topic.

Pasting it together

Python
print("Simple Chatbot (type 'quit' to exit)")

# We'll store our conversation here, like keeping a record of our chat</em>
messages = []

while True:
   # Get what the user wants to say
    user_input = input("You: ")
    
    # Check if the user wants to leave
    if user_input.lower() == 'quit':
        print("Goodbye!")
        break
    
    # Add the user's message to our conversation history
    messages.append({"role": "user", "content": user_input})
    
    try:
        # Get Claude's response
        response = client.messages.create(
            model=MODEL_NAME,
            max_tokens=200,
            messages=messages
        )
        
        # Show what Claude said</em>
        asst_message = response.content[0].text
        print("Assistant:", asst_message)
        
        # Remember Claude's response for context
        messages.append({"role": "assistant", "content": asst_message})
        
    except Exception as e:
        print(f"Oops! Something went wrong: {e}")

Time to Play!

Now it’s your turn! Try running the code and start chatting with your very own AI assistant. Here are some fun things to try:

  • Ask it to tell you a joke
  • Have it help you brainstorm ideas
  • See if it can write a short story
  • Ask for help with a homework problem
Code Formatted
Python
from anthropic import Anthropic
import os

# Create our connection to Claude
client = Anthropic(api_key=os.environ.get("CLAUDE_API_KEY"))

# Specify the Claude model version
MODEL_NAME = "claude-3-5-sonnet-20241022"

def run_chatbot():
    """Runs a simple chatbot that interacts with the Claude API."""
    print("\nWelcome to the Claude Chatbot! (type 'quit' to exit)")
    print("---------------------------------------------")
    print("Status: Connected and ready to chat!")
    print("Tips:")
    print("  - Ask questions naturally")
    print("  - Explore complex topics")
    print("  - Type 'quit' to end the chat\n")

    # Initialize conversation history
    messages = []

    while True:
        # Prompt user for input
        user_input = input("\nYou: ")
        
        # Exit the chatbot if the user types 'quit'
        if user_input.strip().lower() == 'quit':
            print("\nGoodbye! Thanks for chatting!")
            break

        # Add the user's message to the conversation history
        messages.append({"role": "user", "content": user_input})

        try:
            # Send the conversation history to Claude for a response
            response = client.messages.create(
                model=MODEL_NAME,
                max_tokens=1000,  # Adjust to control response length
                messages=messages,
            )
            
            # Extract and display the assistant's response
            asst_message = response.content[0].text
            print("Assistant:", asst_message)
            
            # Add the assistant's response to the conversation history
            messages.append({"role": "assistant", "content": asst_message})

        except Exception as e:
            # Handle API errors gracefully
            print(f"\nError: {e}")
            print("Don't worry! Your previous conversation is still saved.")

if __name__ == "__main__":
    try:
        # Run the chatbot
        run_chatbot()
    except KeyboardInterrupt:
        # Handle abrupt termination with a user-friendly message
        print("\nGoodbye! Thanks for chatting!")