100xdemo / app.py
abhilashnl2006's picture
Update app.py
eefc6b5 verified
raw
history blame
5.94 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:
messages = [{"role": "system", "content": "You are an AI tutor specialized in teaching Python programming. Your task is to create exercise questions based on the given topic. Provide clear, concise, and informative exercises. Include a specific task for the user to implement, along with example input and expected output."}]
messages.append({"role": "user", "content": f"Create an exercise question on {topic} with a specific task, example input, and expected output."})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages,
max_tokens=250,
n=1,
stop=None,
temperature=0.7,
)
question = response.choices[0].message['content'].strip()
return question
except Exception as e:
return f"Error: {str(e)}"
def check_answer(topic, exercise, user_code):
try:
messages = [{"role": "system", "content": "You are an AI tutor specialized in teaching Python programming. Your task is to evaluate the user's code for the given exercise. Provide feedback on correctness and suggest improvements if needed."}]
messages.append({"role": "user", "content": f"Evaluate this answer for the exercise on {topic}: \nExercise: {exercise}\nUser's code: {user_code}"})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages,
max_tokens=250,
n=1,
stop=None,
temperature=0.7,
)
feedback = response.choices[0].message['content'].strip()
return feedback
except Exception as e:
return f"Error: {str(e)}"
def get_solution(topic, exercise):
try:
messages = [{"role": "system", "content": "You are an AI tutor specialized in teaching Python programming. Your task is to provide a correct solution for the given exercise."}]
messages.append({"role": "user", "content": f"Provide the correct solution code for this exercise on {topic}: {exercise}"})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages,
max_tokens=250,
n=1,
stop=None,
temperature=0.7,
)
solution = response.choices[0].message['content'].strip()
return solution
except Exception as e:
return f"Error: {str(e)}"
def respond(message, chat_history, topic, show_code_editor):
if not chat_history:
topic = message
question = generate_exercise_question(topic)
chat_history.append((message, question))
return "", chat_history, topic, True
else:
if message.lower() == "next":
question = generate_exercise_question(topic)
chat_history.append((message, question))
return "", chat_history, topic, True
else:
chat_history.append((message, "Please submit your code using the code editor below."))
return "", chat_history, topic, show_code_editor
def submit_code(topic, user_code, chat_history):
exercise = chat_history[-2][1] # Get the last exercise question
feedback = check_answer(topic, exercise, user_code)
if "correct" in feedback.lower():
response = f"{feedback}\n\nGreat job! Type 'next' to see the next question."
else:
solution = get_solution(topic, exercise)
response = f"{feedback}\n\nHere's the correct solution:\n\n{solution}\n\nType 'next' to see the next question."
chat_history.append((user_code, response))
return "", chat_history, False # Hide code editor after submission
def undo(chat_history, show_code_editor):
if chat_history:
chat_history.pop()
return chat_history, True if len(chat_history) > 0 else False
def clear():
return [], "", False
with gr.Blocks() as demo:
gr.Markdown("# Python Practice Bot")
gr.Markdown("Learn Python through exercises. Start by entering a topic you want to practice.")
chatbot = gr.Chatbot(label="Python Tutor")
topic = gr.State("")
show_code_editor = gr.State(False)
with gr.Row():
with gr.Column(scale=3):
user_input = gr.Textbox(
show_label=False,
placeholder="Enter a Python topic or type 'next' for a new question...",
lines=1
)
code_input = gr.Code(language="python", label="Your Solution", visible=False)
with gr.Column(scale=1):
submit_button = gr.Button("Submit")
code_submit_button = gr.Button("Submit Code", visible=False)
undo_button = gr.Button("Undo")
clear_button = gr.Button("Clear")
submit_button.click(
respond,
[user_input, chatbot, topic, show_code_editor],
[user_input, chatbot, topic, show_code_editor],
queue=False
).then(
lambda x: gr.update(visible=x),
[show_code_editor],
[code_input, code_submit_button]
)
code_submit_button.click(
submit_code,
[topic, code_input, chatbot],
[code_input, chatbot, show_code_editor]
).then(
lambda x: gr.update(visible=x),
[show_code_editor],
[code_input, code_submit_button]
)
undo_button.click(undo, [chatbot, show_code_editor], [chatbot, show_code_editor])
clear_button.click(clear, None, [chatbot, topic, show_code_editor])
gr.Examples(
examples=[["lists"], ["decorators"], ["dictionaries"], ["file handling"], ["classes and objects"]],
inputs=[user_input]
)
demo.launch()