nextchat / ai /chat.py
Syed Khizar
Updated chat.py
b23ba73 unverified
import openai
import os
from dotenv import load_dotenv
import random
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
if not OPENAI_API_KEY:
raise ValueError("OpenAI API key not found. Please check your .env file.")
openai.api_key = OPENAI_API_KEY
greetings = [
"Hello! How are you today? What's new?",
"Hi there! How may I assist you today?",
"Hello! What's on your mind?",
"Hey! What can I do for you today?",
"Hi! How can I help you today?",
"Greetings! How's it going?",
"Hey there! What can I assist you with?",
"Hello! What are you thinking about today?",
"Hi! How's your day going so far?",
"Hey! What's up? How can I assist you?",
"Hello! What brings you here today?",
"Hi! Need help with something today?",
"Good day! How can I be of service?",
"Hello! What would you like to discuss today?",
"Hey! Ready to chat? What’s on your mind?"
]
def start_chat_message() -> str:
try:
greeting = random.choice(greetings)
return greeting
except Exception as e:
print(f"Error in start_chat_message: {e}")
raise ValueError("Failed to generate greeting.")
def respond_to_user(user_input: str) -> str:
try:
client = openai.OpenAI()
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant. Please keep your answers short, complete, and under 512 tokens. Avoid long elaborations unless absolutely necessary."},
{"role": "user", "content": user_input}
],
max_tokens=512,
temperature=0.5
)
return response.choices[0].message.content.strip()
except Exception as e:
print(f"OpenAI API Error: {e}")
return "Sorry, I couldn't get a response from the AI. Please try again later."