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.
- Sends a POST request to OpenAI's
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.
- Initializes the chatbot with parameters like API key, model choice (
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")
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)
In [6]:
first_idea = "Could you give me the recipe for the first idea?"
response = bot.get_response(first_idea)
print("Assistant:", response)
In [7]:
second_idea = "Could you give me the recipe for the second idea?"
response = bot.get_response(second_idea)
print("Assistant:", response)