100xdemo / app.py
abhilashnl2006's picture
Update app.py
0e0bb8c verified
raw
history blame
2.46 kB
import gradio as gr
import openai
import os
# Fetch the API key from Gradio secrets
api_key = os.getenv("OPENAI_API_KEY")
if api_key is None:
raise ValueError("API key not found. Please set the OPENAI_API_KEY secret.")
openai.api_key = api_key
def generate_exercise_question(topic):
try:
# Construct the initial message for exercise generation
messages = [{"role": "system", "content": "You are an AI tutor specialized in teaching Python programming. Your primary task is to create exercise questions based on the topics users want to learn. Provide clear, concise, and informative exercises. Ensure that all your responses strictly adhere to the subject of Python programming and do not engage in any discussions that are insensitive, sexual, casual, comedic, or unrelated to Python programming."}]
messages.append({"role": "user", "content": f"Create an exercise question on {topic}."})
# Generate a response using gpt-3.5-turbo
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages,
max_tokens=150,
n=1,
stop=None,
temperature=0.7,
stream=False
)
question = response.choices[0].message['content'].strip()
return question
except Exception as e:
return f"Error: {str(e)}"
def check_answer(topic, user_code):
try:
# Construct the messages for checking the answer
messages = [{"role": "system", "content": "You are an AI tutor specialized in teaching Python programming. Your primary task is to create and evaluate exercise questions based on the topics users want to learn. Ensure that all your responses strictly adhere to the subject of Python programming and do not engage in any discussions that are insensitive, sexual, casual, comedic, or unrelated to Python programming."}]
messages.append({"role": "user", "content": f"Check this answer for an exercise on {topic}: {user_code}."})
# Generate a response using gpt-3.5-turbo
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages,
max_tokens=150,
n=1,
stop=None,
temperature=0.7,
stream=False
)
feedback = response.choices[0].message['content'].strip()
return feedback
except Exception as e:
return f"Error: {s