OPEN AI - CHATBOT
Simon-Pierre Boucher
2024-09-14

This Python script uses OpenAI's API to build a chatbot capable of generating text-based responses. Here's a breakdown of its functionality:

1. Environment Setup:

  • load_dotenv(): This function loads environment variables from a .env file, specifically the API key (OPENAI_API_KEY), which is required to authenticate requests to the OpenAI API.

2. generate_openai_text() Function:

  • This function interacts with OpenAI's API to generate text using a conversation-based format.
  • Parameters:
    • api_key: API key for OpenAI.
    • model: Specifies which OpenAI model to use (e.g., gpt-4, gpt-4o).
    • messages: A list of conversation messages in the format required by OpenAI.
    • temperature, max_tokens, top_p, frequency_penalty, presence_penalty: Control various aspects of text generation like randomness, output length, diversity, word repetition, and new topics.
  • Response Handling:
    • Sends a POST request to OpenAI's chat/completions endpoint.
    • Returns the API's JSON response or None if an error occurs.

3. ChatBot Class:

  • This class encapsulates the chatbot's behavior and manages conversation flow with OpenAI's API.

  • Initialization (__init__):

    • Initializes the chatbot with parameters like API key, model choice (gpt-4o), temperature, and conversation history.
    • Allows customization of OpenAI API settings for more fine-tuned control of text generation.
  • add_message() Method:

    • Adds a message to the conversation history. This maintains the context of the chat by keeping track of both user and assistant responses.
  • get_response() Method:

    • Takes the user's input and adds it to the conversation history.
    • Calls the generate_openai_text() function to get a response from OpenAI.
    • The assistant's reply is added to the conversation history and returned to the user.

4. Main Program:

  • A ChatBot instance is created using the API key.
  • The bot is tasked with responding to the user input: "Can you suggest 5 dinner ideas for this week?"
  • The chatbot calls get_response() to generate a reply, which is then printed.

Example Usage:

The chatbot maintains the context of the conversation and provides interactive dialogue with the user. In this case, the bot suggests five dinner ideas when asked, but it could be used for various conversational tasks.

This setup allows for flexible, dynamic conversations, powered by OpenAI’s language models, with customizable parameters like response creativity and length.

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("OPENAI_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 [2]:
import requests
def generate_openai_text(api_key, model, messages, temperature=1.0, max_tokens=2000, top_p=1.0,
frequency_penalty=0.0, presence_penalty=0.0):
    """
    Generate text using OpenAI's API.
    Parameters:
    - api_key (str): The API key for OpenAI.
    - model (str): The model to use for text generation.
    - messages (list): A list of messages to pass to the API in a conversation format.
    - temperature (float): Controls randomness in the output (0-1).
    - max_tokens (int): The maximum number of tokens to generate in the completion.
    - top_p (float): Controls the diversity via nucleus sampling (0-1).
    - frequency_penalty (float): Controls the repetition of words (0-1).
    - presence_penalty (float): Controls the introduction of new topics (0-1).
    Returns:
    - response (dict): The API response as a dictionary.
    """
    url = "https://api.openai.com/v1/chat/completions"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }
    data = {
        "model": model,
        "messages": messages,
        "temperature": temperature,
        "max_tokens": max_tokens,
        "top_p": top_p,
        "frequency_penalty": frequency_penalty,
        "presence_penalty": presence_penalty
}
    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 [3]:
class ChatBot:
    def __init__(self, api_key, model="gpt-4o", temperature=1.0, max_tokens=2000, top_p=1.0, frequency_penalty=0.0, presence_penalty=0.0):
        """
        Initialize the ChatBot with API key and parameters.
        
        Parameters:
        - api_key (str): The API key for OpenAI.
        - model (str): The model to use for text generation.
        - temperature (float): Controls randomness in the output (0-1).
        - max_tokens (int): The maximum number of tokens to generate in the completion.
        - top_p (float): Controls the diversity via nucleus sampling (0-1).
        - frequency_penalty (float): Controls the repetition of words (0-1).
        - presence_penalty (float): Controls the introduction of new topics (0-1).
        """
        self.api_key = api_key
        self.model = model
        self.temperature = temperature
        self.max_tokens = max_tokens
        self.top_p = top_p
        self.frequency_penalty = frequency_penalty
        self.presence_penalty = presence_penalty
        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 OpenAI 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 OpenAI API to get a response
        response = generate_openai_text(
            self.api_key,
            self.model,
            self.conversation_history,
            temperature=self.temperature,
            max_tokens=self.max_tokens,
            top_p=self.top_p,
            frequency_penalty=self.frequency_penalty,
            presence_penalty=self.presence_penalty
        )

        if response:
            # Extract the assistant's reply
            assistant_reply = response["choices"][0]["message"]["content"]
            # 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."
In [4]:
bot = ChatBot(api_key)
In [5]:
user_input = "Can you suggest 5 dinner ideas for this week?"
response = bot.get_response(user_input)
print("Assistant:", response)
Assistant: Sure! Here are five dinner ideas for the week that offer a variety of flavors and are relatively easy to prepare:

1. **Monday: Lemon Herb Chicken with Roasted Vegetables**
   - **Main:** Lemon Herb Chicken Breasts
   - **Side:** Roasted Brussels Sprouts and Carrots
   - **Recipe Tip:** Marinate the chicken with lemon juice, olive oil, garlic, and mixed herbs before baking.

2. **Tuesday: Beef Tacos**
   - **Main:** Ground Beef Tacos
   - **Side:** Mexican Street Corn Salad
   - **Recipe Tip:** Use a mix of ground beef, taco seasoning, and sautéed onions for the filling. Serve with diced tomatoes, avocado, and salsa.

3. **Wednesday: Vegetarian Stir-Fry with Tofu**
   - **Main:** Mixed Vegetable and Tofu Stir-Fry
   - **Side:** Jasmine Rice
   - **Recipe Tip:** Use a variety of colorful vegetables like bell peppers, broccoli, and snap peas. Season with soy sauce, garlic, and a touch of ginger.

4. **Thursday: Shrimp Alfredo Pasta**
   - **Main:** Creamy Shrimp Alfredo
   - **Side:** Garlic Bread
   - **Recipe Tip:** Sauté shrimp in garlic butter, then toss with fettuccine in a creamy Alfredo sauce made from heavy cream, Parmesan cheese, and garlic.

5. **Friday: Margherita Pizza**
   - **Main:** Homemade Margherita Pizza
   - **Side:** Caesar Salad
   - **Recipe Tip:** Use fresh basil, mozzarella cheese, and ripe tomatoes. You can make your own pizza dough or use a pre-made one to save time.

Enjoy your dinners this week!
In [6]:
first_idea = "Could you give me the recipe for the first idea?"
response = bot.get_response(first_idea)
print("Assistant:", response)
Assistant: Certainly! Here’s a detailed recipe for Lemon Herb Chicken with Roasted Vegetables:

### Lemon Herb Chicken with Roasted Vegetables

#### Ingredients:

**For the Lemon Herb Chicken:**
- 4 boneless, skinless chicken breasts
- 3 tablespoons olive oil
- Juice of 2 lemons
- 3 cloves garlic, minced
- 1 tablespoon fresh thyme (or 1 teaspoon dried thyme)
- 1 tablespoon fresh rosemary (or 1 teaspoon dried rosemary)
- Salt and black pepper to taste

**For the Roasted Vegetables:**
- 1 pound Brussels sprouts, halved
- 3 large carrots, sliced
- 2 tablespoons olive oil
- Salt and black pepper to taste
- Optional: 1 teaspoon balsamic vinegar for added flavor

#### Instructions:

**1. Marinate the Chicken:**
   - In a small bowl, whisk together the olive oil, lemon juice, minced garlic, thyme, rosemary, salt, and pepper.
   - Place the chicken breasts in a resealable plastic bag or a shallow dish. Pour the marinade over the chicken, ensuring each piece is well-coated.
   - Seal the bag or cover the dish and refrigerate for at least 30 minutes, or up to 2 hours for better flavor.

**2. Preheat the Oven:**
   - Preheat your oven to 400°F (200°C).

**3. Prepare the Vegetables:**
   - In a large bowl, toss the halved Brussels sprouts and sliced carrots with olive oil, salt, and pepper.
   - Spread the vegetables in a single layer on a baking sheet.

**4. Cooking:**
   - Place the marinated chicken breasts on a separate baking sheet or oven-safe dish.
   - Put both the chicken and the vegetables in the preheated oven.
   - Roast the vegetables for about 25-30 minutes, or until they are tender and slightly caramelized, stirring halfway through.
   - Bake the chicken for about 20-25 minutes, or until the internal temperature reaches 165°F (74°C) and the juices run clear. You can also use a meat thermometer to check for doneness.

**5. Optional Step:**
   - If you wish, drizzle the roasted vegetables with a little balsamic vinegar for added flavor once they come out of the oven.

**6. Serve:**
   - Arrange the chicken breasts and roasted vegetables on plates.
   - Garnish with extra fresh herbs or lemon slices if desired.

Enjoy your Lemon Herb Chicken with Roasted Vegetables! This dish is not only delicious but also packed with nutrients.
In [7]:
second_idea = "Could you give me the recipe for the second idea?"
response = bot.get_response(second_idea)
print("Assistant:", response)
Assistant: Certainly! Here's a detailed recipe for Beef Tacos with Mexican Street Corn Salad:

### Beef Tacos with Mexican Street Corn Salad

#### Ingredients:

**For the Beef Tacos:**
- 1 pound ground beef
- 1 small onion, finely chopped
- 2-3 cloves garlic, minced
- 1 packet taco seasoning (or homemade mix: 1 tablespoon chili powder, 1 teaspoon cumin, 1 teaspoon paprika, 1/2 teaspoon oregano, 1/2 teaspoon salt, 1/2 teaspoon black pepper, 1/4 teaspoon crushed red pepper flakes)
- 1/2 cup water
- 8 small tortillas (corn or flour)
- Toppings: shredded lettuce, diced tomatoes, diced avocado, shredded cheese, salsa, sour cream, and chopped cilantro

**For the Mexican Street Corn Salad:**
- 4 ears of corn, husked (or 3 cups frozen corn kernels, thawed and drained)
- 1/4 cup mayonnaise
- 1/4 cup sour cream
- 1/2 cup crumbled Cotija cheese (or feta cheese)
- 1 clove garlic, minced
- 1/2 teaspoon chili powder
- Juice of 1 lime
- 2 tablespoons chopped fresh cilantro
- Salt and black pepper to taste

#### Instructions:

**1. Prepare the Mexican Street Corn Salad:**
   - If using fresh corn, boil or grill the corn until tender and slightly charred. Allow it to cool, then cut the kernels off the cobs.
   - In a large bowl, combine the mayonnaise, sour cream, Cotija cheese, minced garlic, chili powder, lime juice, and chopped cilantro. Mix well.
   - Add the corn kernels to the bowl and toss to coat evenly with the dressing.
   - Season with salt and black pepper to taste. Adjust seasoning as needed.
   - Cover and refrigerate until ready to serve.

**2. Cook the Beef:**
   - In a large skillet over medium heat, cook the ground beef until browned, breaking it apart with a spoon as it cooks.
   - Add the finely chopped onion and minced garlic to the skillet and sauté until the onion is soft and translucent.
   - Drain any excess fat from the skillet.
   - Stir in the taco seasoning and water. Cook for an additional 5-10 minutes, or until the sauce thickens and the beef is fully coated with the seasoning. 

**3. Warm the Tortillas:**
   - Heat the tortillas in a dry skillet over medium heat for about 30 seconds on each side, or until warm and pliable.
   - Alternatively, you can wrap them in a damp paper towel and microwave for 20-30 seconds.

**4. Assemble the Tacos:**
   - Spoon the seasoned beef mixture onto each tortilla.
   - Add your choice of toppings such as shredded lettuce, diced tomatoes, diced avocado, shredded cheese, salsa, sour cream, and chopped cilantro.

**5. Serve:**
   - Serve the beef tacos with the Mexican Street Corn Salad on the side.
   - Garnish the corn salad with extra Cotija cheese and cilantro if desired.

Enjoy your delicious Beef Tacos with Mexican Street Corn Salad!