Try the below
import os
import logging
from typing import Optional
from dataclasses import dataclass, field
from dotenv import load_dotenv
import openai
Load environment variables from .env file
load_dotenv()
Configure logging
logging.basicConfig(
level=logging.INFO,
format=‘%(asctime)s [%(levelname)s] %(message)s’,
handlers=[
logging.FileHandler(“chatbot.log”),
logging.StreamHandler()
]
)
logger = logging.getLogger(name)
Initialize OpenAI API
openai.api_key = os.getenv(“OPENAI_API_KEY”)
@dataclass
class ChatbotConfig:
model: str = “gpt-4”
temperature: float = 0.7
top_p: float = 0.95
frequency_penalty: float = 0.0
presence_penalty: float = 0.0
max_retries: int = 3
retry_delay: int = 2 # seconds
@dataclass
class UserSession:
user_name: str
area_of_interest: str
def generate_prompt(user_session: UserSession) → str:
“”"
Generates a dynamic prompt based on the user’s name and area of interest.
“”"
prompt = f"“”
You are a friendly and helpful chatbot designed to provide personalized information to users.
User Name: {user_session.user_name}
Area of Interest: {user_session.area_of_interest}
Example Conversation:
Chatbot: Hi {user_session.user_name}! I’m here to help you learn about {user_session.area_of_interest}. We can explore topics like A, B, and C. Which one would you like to dive into today?
User: I want to know more about A. Can you describe it?
Chatbot: Sure! A is a fundamental concept in {user_session.area_of_interest}. It involves X, Y, and Z. What do you already know about X?
User: I know that X is related to P and Q. Is that correct?
Chatbot: Yes, that's absolutely right! X is indeed related to P and Q. It’s also connected to R. How do you think X, P, and Q interact?
User: I’m not sure about that.
Chatbot: No problem! X, P, and Q are related through the process of S. Do you have any thoughts on what S might involve?
Instructions:
1. Greet the user by name.
2. Offer assistance related to their area of interest.
3. Provide at least three initial topics within their area of interest.
4. Ask clarifying questions based on the user’s chosen topic.
5. If unsure about a user’s question, respond with “I’m still learning about that. Can you tell me more?”
6. Maintain a friendly and helpful tone throughout the conversation.
7. Follow the pattern of the example conversation, encouraging user engagement through follow-up questions.
"""
return prompt
def get_chatbot_response(
user_session: UserSession,
user_input: str,
config: ChatbotConfig = ChatbotConfig()
) → Optional[str]:
“”"
Generates a response from the chatbot based on user input and session.
Implements retry logic and error handling.
“”"
prompt = generate_prompt(user_session)
messages = [
{“role”: “system”, “content”: prompt},
{“role”: “user”, “content”: user_input}
]
for attempt in range(1, config.max_retries + 1):
try:
logger.info(f"Attempt {attempt}: Sending request to OpenAI API.")
response = openai.ChatCompletion.create(
model=config.model,
messages=messages,
temperature=config.temperature,
top_p=config.top_p,
frequency_penalty=config.frequency_penalty,
presence_penalty=config.presence_penalty
)
chatbot_message = response.choices[0].message.content.strip()
logger.info("Received response from OpenAI API.")
return chatbot_message
except openai.error.RateLimitError as e:
logger.warning(f"Rate limit exceeded: {e}. Retrying in {config.retry_delay} seconds...")
except openai.error.OpenAIError as e:
logger.error(f"OpenAI API error: {e}.")
break # Non-retriable error
except Exception as e:
logger.exception(f"Unexpected error: {e}.")
break # Non-retriable error
# Wait before retrying
import time
time.sleep(config.retry_delay)
logger.error("Failed to get a response from OpenAI API after multiple attempts.")
return "Sorry, I'm experiencing some issues right now. Please try again later."
def main():
“”"
Example usage of the chatbot.
“”"
# Initialize user session
user_session = UserSession(
user_name=“Alice”,
area_of_interest=“Machine Learning”
)
# Example user inputs
user_inputs = [
"Hi there!",
"I want to know more about supervised learning. Can you explain it?",
"What is the difference between supervised and unsupervised learning?",
"Can you give me an example of a supervised learning algorithm?",
"I'm not sure how gradient descent works."
]
# Initialize chatbot configuration
config = ChatbotConfig(
model="ft:gpt-4o-2024-08-06:...", # Replace with your fine-tuned model ID
temperature=0.7,
top_p=0.95,
frequency_penalty=0.0,
presence_penalty=0.0,
max_retries=3,
retry_delay=2
)
# Iterate through user inputs and get chatbot responses
for user_input in user_inputs:
logger.info(f"User: {user_input}")
response = get_chatbot_response(user_session, user_input, config)
if response:
logger.info(f"Chatbot: {response}")
print(f"Chatbot: {response}")
else:
logger.error("No response received from chatbot.")
print("Chatbot: Sorry, I'm unable to respond at the moment.")
if name == “main”:
main()
Sure! key components and functionalities:
- Environment Setup:
Libraries: Imports necessary libraries such as os, logging, dotenv, and openai.
API Key: Loads the OpenAI API key from a .env file using python-dotenv.
- Logging Configuration:
Sets up logging to output messages to both a log file (chatbot.log) and the console, aiding in monitoring and debugging.
- Data Classes:
ChatbotConfig: Defines configuration parameters like model type, temperature, top_p, penalties, and retry settings for API requests.
UserSession: Stores user-specific information such as the user’s name and their area of interest, enabling personalized interactions.
- Prompt Generation (generate_prompt):
Creates a dynamic prompt tailored to the user’s name and area of interest.
Includes an example conversation and clear instructions to guide the chatbot’s responses, ensuring consistency and relevance.
- Chatbot Response Function (get_chatbot_response):
Message Construction: Combines the system prompt with the user’s input into a message list.
API Interaction: Sends the messages to the OpenAI ChatCompletion API using the specified model and hyperparameters.
Retry Logic: Implements retries for transient errors like rate limits, enhancing reliability.
Error Handling: Logs errors and provides fallback responses if API requests fail.
- Main Function (main):
User Session Initialization: Sets up a sample user session with a name and area of interest.
Example Inputs: Defines a list of sample user inputs to simulate a conversation.
Configuration: Specifies chatbot settings, including the fine-tuned model ID.
Conversation Loop: Iterates through user inputs, obtains chatbot responses, logs them, and prints them to the console.
- Future Integrations:
DPO & RAG: Notes on potential future enhancements like Direct Preference Optimization and Retrieval-Augmented Generation for improved response quality.
Scalability & UI: Suggestions for deploying the chatbot in production environments and developing user-friendly interfaces.
- Execution:
Runs the main function when the script is executed, demonstrating the chatbot’s functionality with predefined interactions.
Summary:
The script sets up a personalized, robust chatbot by loading configurations, generating dynamic prompts based on user data, handling API interactions with retries and error logging, and demonstrating usage with sample conversations. It’s designed for easy customization and future enhancements to achieve more human-like and reliable interactions.