pratikshahp's picture
Rename app.py to openai-app.py
576129c verified
from openai import OpenAI
from dotenv import load_dotenv
import os
# Load environment variables
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")
# Initialize OpenAI client
client = OpenAI(api_key=api_key)
import gradio as gr
# Set OpenAI API key
# Allowed educational topics
ALLOWED_TOPICS = ["math", "science", "geography", "history", "english"]
def moderate_content(input_text):
"""Check if input text is appropriate."""
response = client.moderations.create(
model="text-moderation-latest",
input=input_text
)
results = response["results"][0]
if results["flagged"]:
return False, results["categories"]
return True, None
def is_educational_query(input_text):
"""Check if the query is relevant to allowed educational topics."""
input_lower = input_text.lower()
for topic in ALLOWED_TOPICS:
if topic in input_lower:
return True
return False
def generate_response(input_text):
"""Generate a safe and moderated response to the input."""
# Moderate input
is_safe_input, categories = moderate_content(input_text)
if not is_safe_input:
return "Your question couldn't be processed due to inappropriate content. Please try asking something else."
# Check if the query is educational
if not is_educational_query(input_text):
return (
"This chatbot is designed to answer questions on educational topics like "
"math, science, geography, history, and English. Please ask something related to these subjects."
)
# Generate response using LLM
try:
response = client.chat.completions.create(
model="gpt-4o-mini", # Replace with preferred model
messages=[{"role": "user", "content": input_text}],
max_tokens=50,
)
generated_text = response.choices[0].message.content.strip()
# Moderate output
is_safe_output, categories = moderate_content(generated_text)
if not is_safe_output:
return "The response generated contained inappropriate content. Please try rephrasing your question."
return generated_text
except Exception as e:
return f"An error occurred: {str(e)}"
# Gradio interface
def chatbot_interface(input_text):
return generate_response(input_text)
interface = gr.Interface(
fn=chatbot_interface,
inputs="text",
outputs="text",
title="Educational Chatbot",
description=(
"Ask me questions about educational topics such as math, science, geography, "
"history, and English. Please ensure your questions are within these subjects!"
)
)
# Launch interface
interface.launch()