CoolFace
Apppublic

MathProfessionalDevelopment/mathchatbot-v7-simple

sourceHugging Faceapache-2.0updated 22d agoView on Hugging Face
0likes
app.py106 linesDownload Raw Back to root
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 15def gpt_call(history, user_message,16             model="gpt-4o-mini",17             max_tokens=1024,18             temperature=0.7,19             top_p=0.95):20    """21    Calls OpenAI Chat API to generate responses.22    - history: [(user_text, assistant_text), ...]23    - user_message: latest message from user24    """25    messages = [{"role": "system", "content": MAIN_PROMPT}]26    27    # Add conversation history28    for user_text, assistant_text in history:29        if user_text:30            messages.append({"role": "user", "content": user_text})31        if assistant_text:32            messages.append({"role": "assistant", "content": assistant_text})33 34    messages.append({"role": "user", "content": user_message})35    36    # OpenAI API Call37    completion = client.chat.completions.create(38        model=model,39        messages=messages,40        max_tokens=max_tokens,41        temperature=temperature,42        top_p=top_p43    )44    45    response = completion.choices[0].message.content46    47    # Ensure AI always asks for reasoning first before answering48    if any(keyword in user_message.lower() for keyword in ["problem 2", "problem 3"]):49        response = "Interesting! Before we move on, what do you think about this problem? Is it proportional? Why or why not? Let's explore your reasoning first.\n\n" + response50    51    # Push for deeper explanations—even if the answer is correct52    if any(keyword in user_message.lower() for keyword in ["correct", "right", "exactly"]):53        response = "That’s a great insight! But let’s push further—can you explain it another way? Could someone misunderstand this concept? Let’s explore that.\n\n" + response54    55    # Ensure the AI always asks a follow-up before moving to the next question56    if any(keyword in user_message.lower() for keyword in ["move on", "next question"]):57        response = "Before we continue, let’s reflect for a moment—what was the biggest takeaway from this problem? Could we change something and still get a non-proportional relationship?\n\n" + response58    59    # Make the Problem-Posing Activity more interactive60    if "pose a problem" in user_message.lower():61        response += "\n\nThat's a great start! But let's refine it—does your problem truly show a non-proportional relationship? What would happen if we removed the fixed cost? Try adjusting it and see if it still works!"62 63    return response64 65def respond(user_message, history):66    """67    Handles user input and chatbot responses.68    """69    if not user_message:70        return "", history71 72    assistant_reply = gpt_call(history, user_message)73    history.append((user_message, assistant_reply))74    return "", history75 76##############################77#  Gradio Blocks UI78##############################79with gr.Blocks() as demo:80    gr.Markdown("## AI-Guided Math PD Chatbot")81 82    chatbot = gr.Chatbot(83        value=[("", INITIAL_PROMPT)],84        height=60085    )86 87    state_history = gr.State([("", INITIAL_PROMPT)])88 89    user_input = gr.Textbox(90        placeholder="Type your message here...",91        label="Your Input"92    )93 94    user_input.submit(95        respond,96        inputs=[user_input, state_history],97        outputs=[user_input, chatbot]98    ).then(99        fn=lambda _, h: h,100        inputs=[user_input, chatbot],101        outputs=[state_history]102    )103 104if __name__ == "__main__":105    demo.launch(server_name="0.0.0.0", server_port=7860, share=True)106