MathProfessionalDevelopment/mathchatbot-v9-simple
0
1import os2import gradio as gr3from dotenv import load_dotenv4from openai import OpenAI5from prompts.initial_prompt import INITIAL_PROMPT6from prompts.main_prompt import MAIN_PROMPT7 8# Load OpenAI API Key from .env file9if os.path.exists(".env"):10 load_dotenv(".env")11 12OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")13client = OpenAI(api_key=OPENAI_API_KEY)14 15# Define the function to call GPT model16def gpt_call(history, user_message, model="gpt-4o-mini", max_tokens=512, temperature=0.7, top_p=0.95):17 """18 Calls OpenAI Chat API to generate responses.19 - history: [(user_text, assistant_text), ...]20 - user_message: latest message from user21 """22 messages = [{"role": "system", "content": MAIN_PROMPT}]23 24 # Add conversation history25 for user_text, assistant_text in history:26 if user_text:27 messages.append({"role": "user", "content": user_text})28 if assistant_text:29 messages.append({"role": "assistant", "content": assistant_text})30 31 messages.append({"role": "user", "content": user_message})32 33 # OpenAI API Call34 completion = client.chat.completions.create(35 model=model,36 messages=messages,37 max_tokens=max_tokens,38 temperature=temperature,39 top_p=top_p40 )41 42 return completion.choices[0].message.content43 44# Reflection steps appear one-by-one45REFLECTION_STEPS = [46 {47 "title": "Pre-Video Reflection",48 "question": "Before watching the video, how did you approach solving the task? What strategies did you use?",49 "follow_up": "You used **{response}**—interesting! Why do you think this strategy is effective for solving proportional reasoning problems?",50 "next_step": "Watch the Video"51 },52 {53 "title": "Watch the Video",54 "question": "Now, please watch the video at the provided link. Let me know when you're done watching.",55 "follow_up": "Great! Now that you've watched the video, let's reflect on key aspects of the lesson.",56 "next_step": "Observing Creativity-Directed Practices"57 },58 {59 "title": "Observing Creativity-Directed Practices",60 "question": "Let's start with **Creativity-Directed Practices**. What stood out to you about how the teacher encouraged student creativity?",61 "follow_up": "You mentioned **{response}**. Can you explain how that supported students' creative problem-solving?",62 "next_step": "Small Group Interactions"63 },64 {65 "title": "Small Group Interactions",66 "question": "Now, let's reflect on **Small Group Interactions**. What did you notice about how the teacher guided student discussions?",67 "follow_up": "Interesting! You noted **{response}**. How do you think that helped students deepen their understanding?",68 "next_step": "Student Reasoning and Connections"69 },70 {71 "title": "Student Reasoning and Connections",72 "question": "Next, let’s discuss **Student Reasoning and Connections**. How did students reason through the task?",73 "follow_up": "That’s a great point about **{response}**. Can you explain why this was significant in their problem-solving?",74 "next_step": "Common Core Practice Standards"75 },76 {77 "title": "Common Core Practice Standards",78 "question": "Now, let’s reflect on **Common Core Practice Standards**. Which ones do you think were emphasized in the lesson?",79 "follow_up": "You mentioned **{response}**. How do you see this practice supporting students' proportional reasoning?",80 "next_step": "Problem Posing Activity"81 },82 {83 "title": "Problem Posing Activity",84 "question": "Let’s engage in a **Problem-Posing Activity**. Pose a problem that encourages students to use visuals and proportional reasoning.",85 "follow_up": "That's an interesting problem! Does it allow for multiple solution paths? How does it connect to Common Core practices we discussed?",86 "next_step": "Final Reflection"87 },88 {89 "title": "Final Reflection",90 "question": "📚 **Final Reflection**\n\nWhat’s one change you will make in your own teaching based on this module?",91 "follow_up": "That’s a great insight! How do you think implementing **{response}** will impact student learning?",92 "next_step": "End" # Final step93 }94]95 96def respond(user_message, history):97 if not user_message:98 return "", history99 100 # Find the last reflection step completed101 completed_steps = [h for h in history if "Reflection Step" in h[1]]102 reflection_index = len(completed_steps)103 104 if reflection_index < len(REFLECTION_STEPS):105 current_step = REFLECTION_STEPS[reflection_index]106 next_reflection = current_step["question"]107 else:108 # If it's the last step, check the user's response109 if user_message.strip().lower() in ["no", "no thanks", "i'm done"]:110 assistant_reply = "Thank you for engaging in this reflection! If you ever have more thoughts or questions, feel free to return. Happy teaching! 🎉"111 history.append((user_message, assistant_reply))112 return "", history113 else:114 next_reflection = "You've completed the reflections. Would you like to discuss anything further?"115 116 assistant_reply = gpt_call(history, user_message)117 118 # Follow-up question before moving on119 if reflection_index > 0 and reflection_index < len(REFLECTION_STEPS):120 follow_up_prompt = REFLECTION_STEPS[reflection_index - 1]["follow_up"].format(response=user_message)121 assistant_reply += f"\n\n{follow_up_prompt}"122 123 # Append the assistant's response and introduce the next reflection question124 history.append((user_message, assistant_reply))125 history.append(("", f"**Reflection Step {reflection_index + 1}:** {next_reflection}"))126 127 return "", history128 129with gr.Blocks() as demo:130 gr.Markdown("## AI-Guided Math PD Chatbot")131 132 chatbot = gr.Chatbot(value=[("", INITIAL_PROMPT)], height=600)133 state_history = gr.State([("", INITIAL_PROMPT)])134 user_input = gr.Textbox(placeholder="Type your message here...", label="Your Input")135 136 user_input.submit(respond, inputs=[user_input, state_history], outputs=[user_input, chatbot]).then(fn=lambda _, h: h, inputs=[user_input, chatbot], outputs=[state_history])137 138if __name__ == "__main__":139 demo.launch(server_name="0.0.0.0", server_port=7860, share=True)140 