ANTHROPIC - CHATBOT
Simon-Pierre Boucher
2024-09-14

This Python script defines a ChatBot class that interacts with the Anthropic API to generate responses based on user input. Here's a detailed explanation of how it works:

1. Environment Setup

  • The script uses the dotenv library to load environment variables, including the Anthropic API key (ANTHROPIC_API_KEY), from a .env file.

2. Class ChatBot

  • Initialization (__init__):

    • The ChatBot class is initialized with the API key, the model (claude-3-5-sonnet-20240620), and parameters such as max_tokens, temperature, and top_p. These parameters control the text generation behavior:

      • max_tokens: Limits the length of the generated text.
      • temperature: Controls randomness in the output.
      • top_p: Affects diversity via nucleus sampling.
    • A conversation history list (self.conversation_history) is used to maintain the ongoing chat context between the user and the assistant.

  • add_message():

    • This method adds a message to the conversation history, either from the user or the assistant.
    • It accepts two parameters: the role (either "user" or "assistant") and the content (the message text).
  • get_response():

    • This method handles the user input, sending it to the Anthropic API and returning the assistant's response.
    • The method first adds the user’s message to the conversation history, then calls the generate_anthropic_text() method to send the conversation history to the Anthropic API.
    • It extracts the assistant’s reply from the API response, adds the reply to the conversation history, and returns it.
  • generate_anthropic_text():

    • This method interacts with the Anthropic API. It sends the conversation history along with the model, max_tokens, temperature, and top_p to the API.
    • The method sends a POST request to https://api.anthropic.com/v1/messages with the necessary headers and data.
    • It returns the API's response as a dictionary or prints an error message if the request fails.

3. Usage

  • An instance of the ChatBot class is created (bot) using the API key and default parameters for the model, max_tokens, temperature, and top_p.
  • The user’s input ("Can you suggest 5 dinner ideas for this week?") is passed to the get_response() method, which returns the assistant’s generated response.

Summary:

  • Modular ChatBot: The class handles both user and assistant messages, maintains a conversation history, and interacts with Anthropic’s API.
  • Parameters: Allows control over token limits, randomness, and text diversity using max_tokens, temperature, and top_p.
  • Error Handling: Gracefully handles request exceptions by printing errors if the API call fails.

This structure allows for multiple interactions, keeping a continuous conversation context for better responses from the API.

In [1]:
import os
import requests
from dotenv import load_dotenv
from IPython.display import display, HTML
import re

# Charger les variables d'environnement depuis le fichier .env
load_dotenv()

# Obtenir la clé API depuis les variables d'environnement
api_key = os.getenv("ANTHROPIC_API_KEY")
/Users/simon-pierreboucher/Desktop/notebook/venv/lib/python3.9/site-packages/urllib3/__init__.py:35: NotOpenSSLWarning: urllib3 v2 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'LibreSSL 2.8.3'. See: https://github.com/urllib3/urllib3/issues/3020
  warnings.warn(
In [3]:
import requests

class ChatBot:
    def __init__(self, api_key, model="claude-3-5-sonnet-20240620", max_tokens=1024, temperature=0.7, top_p=0.9):
        """
        Initialize the ChatBot with API key and parameters.
        
        Parameters:
        - api_key (str): The API key for Anthropic.
        - model (str): The model to use for text generation.
        - max_tokens (int): The maximum number of tokens to generate in the completion.
        - temperature (float): Controls randomness in the output (0-1).
        - top_p (float): Controls the diversity via nucleus sampling (0-1).
        """
        self.api_key = api_key
        self.model = model
        self.max_tokens = max_tokens
        self.temperature = temperature
        self.top_p = top_p
        self.conversation_history = []

    def add_message(self, role, content):
        """
        Add a message to the conversation history.
        
        Parameters:
        - role (str): The role of the sender ("user" or "assistant").
        - content (str): The content of the message.
        """
        self.conversation_history.append({"role": role, "content": content})

    def get_response(self, user_input):
        """
        Get a response from the Anthropic API based on the user input.
        
        Parameters:
        - user_input (str): The user's input message.
        
        Returns:
        - assistant_reply (str): The assistant's generated response.
        """
        # Add user input to conversation history
        self.add_message("user", user_input)

        # Call the Anthropic API to get a response
        response = self.generate_anthropic_text(
            self.api_key,
            self.model,
            self.conversation_history,
            max_tokens=self.max_tokens,
            temperature=self.temperature,
            top_p=self.top_p
        )

        if response:
            # Extract the assistant's reply correctly based on response structure
            content = response.get("content", [])
            if content and isinstance(content, list) and len(content) > 0 and "text" in content[0]:
                assistant_reply = content[0]["text"]
            else:
                assistant_reply = "Sorry, I couldn't generate a response."

            # Add assistant's reply to conversation history
            self.add_message("assistant", assistant_reply)
            return assistant_reply
        else:
            return "Sorry, I couldn't generate a response."

    def generate_anthropic_text(self, api_key, model, messages, max_tokens=1024, temperature=0.7, top_p=0.9):
        """
        Generate text using Anthropic's API.
        
        Parameters:
        - api_key (str): The API key for Anthropic.
        - model (str): The model to use for text generation.
        - messages (list): A list of messages to pass to the API in a conversation format.
        - max_tokens (int): The maximum number of tokens to generate in the completion.
        - temperature (float): Controls randomness in the output (0-1).
        - top_p (float): Controls the diversity via nucleus sampling (0-1).
        
        Returns:
        - response (dict): The API response as a dictionary.
        """
        url = "https://api.anthropic.com/v1/messages"
        headers = {
            "Content-Type": "application/json",
            "x-api-key": api_key,
            "anthropic-version": "2023-06-01"
        }
        data = {
            "model": model,
            "max_tokens": max_tokens,
            "temperature": temperature,
            "top_p": top_p,
            "messages": messages
        }

        try:
            response = requests.post(url, headers=headers, json=data)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            print(f"An error occurred: {e}")
            return None
In [4]:
bot = ChatBot(api_key, model="claude-3-5-sonnet-20240620", max_tokens=1024, temperature=0.7, top_p=0.9)
In [5]:
user_input = "Can you suggest 5 dinner ideas for this week?"
response = bot.get_response(user_input)
print("Assistant:", response)
Assistant: Here are 5 dinner ideas for your week:

1. Grilled Lemon Herb Chicken with roasted vegetables and quinoa

2. Vegetarian Chili with cornbread and a side salad

3. Baked Salmon with asparagus and sweet potato mash

4. Stir-fry Beef and Broccoli with brown rice

5. Homemade Margherita Pizza with a mixed green salad

These meals offer a variety of flavors and nutritional balance throughout the week. You can adjust ingredients or sides based on your preferences and dietary needs.
In [6]:
user_input = "Can you give me the recipe for the first idea?"
response = bot.get_response(user_input)
print("Assistant:", response)
Assistant: Certainly! Here's a recipe for Grilled Lemon Herb Chicken with roasted vegetables and quinoa:

Ingredients:
For the chicken:
- 4 boneless, skinless chicken breasts
- 2 lemons, juiced and zested
- 3 cloves garlic, minced
- 2 tbsp olive oil
- 1 tsp dried oregano
- 1 tsp dried thyme
- Salt and pepper to taste

For the roasted vegetables:
- 2 bell peppers, sliced
- 1 zucchini, sliced
- 1 red onion, cut into wedges
- 2 tbsp olive oil
- Salt and pepper to taste

For the quinoa:
- 1 cup quinoa
- 2 cups water or chicken broth
- Salt to taste

Instructions:
1. Marinate the chicken: Mix lemon juice, zest, garlic, olive oil, oregano, thyme, salt, and pepper. Add chicken and marinate for 30 minutes to 2 hours.

2. Preheat oven to 425°F (220°C) for vegetables.

3. Toss vegetables with olive oil, salt, and pepper. Spread on a baking sheet and roast for 20-25 minutes, stirring halfway through.

4. Cook quinoa: Rinse quinoa, combine with water/broth in a pot. Bring to a boil, reduce heat, cover, and simmer for 15 minutes. Remove from heat and let stand for 5 minutes, then fluff with a fork.

5. Grill the chicken: Preheat grill to medium-high. Grill chicken for 6-8 minutes per side or until internal temperature reaches 165°F (74°C).

6. Serve grilled chicken with roasted vegetables and quinoa.

Enjoy your meal!
In [7]:
user_input = "Can you give me the recipe for the second idea?"
response = bot.get_response(user_input)
print("Assistant:", response)
Assistant: Certainly! Here's a recipe for Vegetarian Chili with cornbread:

Vegetarian Chili:

Ingredients:
- 2 tbsp olive oil
- 1 large onion, diced
- 3 cloves garlic, minced
- 2 bell peppers, diced
- 2 carrots, diced
- 2 celery stalks, diced
- 2 cans (15 oz each) kidney beans, drained and rinsed
- 1 can (15 oz) black beans, drained and rinsed
- 1 can (28 oz) crushed tomatoes
- 2 cups vegetable broth
- 1 can (4 oz) diced green chilies
- 2 tbsp chili powder
- 1 tbsp cumin
- 1 tsp oregano
- Salt and pepper to taste
- Optional toppings: shredded cheese, sour cream, cilantro

Instructions:
1. Heat oil in a large pot over medium heat. Add onion, garlic, peppers, carrots, and celery. Cook until vegetables are soft, about 5-7 minutes.

2. Add beans, tomatoes, broth, green chilies, and spices. Stir well.

3. Bring to a boil, then reduce heat and simmer for 30-40 minutes, stirring occasionally.

4. Taste and adjust seasoning as needed.

5. Serve hot with cornbread and optional toppings.

Simple Cornbread:

Ingredients:
- 1 cup cornmeal
- 1 cup all-purpose flour
- 1/4 cup sugar
- 4 tsp baking powder
- 1/2 tsp salt
- 1 cup milk
- 1/3 cup vegetable oil
- 1 large egg

Instructions:
1. Preheat oven to 400°F (200°C). Grease an 8-inch square baking dish.

2. In a large bowl, mix cornmeal, flour, sugar, baking powder, and salt.

3. In another bowl, whisk together milk, oil, and egg.

4. Add wet ingredients to dry ingredients and stir until just combined.

5. Pour batter into prepared dish and bake for 20-25 minutes, until a toothpick inserted in the center comes out clean.

Serve the chili hot with a side of warm cornbread and a simple green salad if desired.