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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import os
|
3 |
+
import re
|
4 |
+
import markdown
|
5 |
+
from openai import OpenAI
|
6 |
+
import time
|
7 |
+
|
8 |
+
# Function to generate math solution using the Phi-4-reasoning-plus model
|
9 |
+
def generate_math_solution(api_key, problem_text, history=None):
|
10 |
+
if not api_key.strip():
|
11 |
+
return "Please enter your OpenRouter API key.", history
|
12 |
+
|
13 |
+
if not problem_text.strip():
|
14 |
+
return "Please enter a math problem.", history
|
15 |
+
|
16 |
+
try:
|
17 |
+
client = OpenAI(
|
18 |
+
base_url="https://openrouter.ai/api/v1",
|
19 |
+
api_key=api_key,
|
20 |
+
)
|
21 |
+
|
22 |
+
messages = [
|
23 |
+
{"role": "system", "content":
|
24 |
+
"""You are an expert math tutor who explains concepts clearly and thoroughly.
|
25 |
+
Analyze the given math problem and provide a detailed step-by-step solution.
|
26 |
+
For each step:
|
27 |
+
1. Show the mathematical operation
|
28 |
+
2. Explain why this step is necessary
|
29 |
+
3. Connect it to relevant mathematical concepts
|
30 |
+
|
31 |
+
Format your response with clear section headers using markdown.
|
32 |
+
Begin with an "Initial Analysis" section, follow with numbered steps,
|
33 |
+
and conclude with a "Final Answer" section."""},
|
34 |
+
]
|
35 |
+
|
36 |
+
# Add conversation history if it exists
|
37 |
+
if history:
|
38 |
+
for exchange in history:
|
39 |
+
messages.append({"role": "user", "content": exchange[0]})
|
40 |
+
if exchange[1]: # Check if there's a response
|
41 |
+
messages.append({"role": "assistant", "content": exchange[1]})
|
42 |
+
|
43 |
+
# Add the current problem
|
44 |
+
messages.append({"role": "user", "content": f"Solve this math problem step-by-step: {problem_text}"})
|
45 |
+
|
46 |
+
# Create the completion
|
47 |
+
completion = client.chat.completions.create(
|
48 |
+
model="microsoft/phi-4-reasoning-plus:free",
|
49 |
+
messages=messages,
|
50 |
+
extra_headers={
|
51 |
+
"HTTP-Referer": "https://advancedmathtutor.edu",
|
52 |
+
"X-Title": "Advanced Math Tutor",
|
53 |
+
}
|
54 |
+
)
|
55 |
+
|
56 |
+
solution = completion.choices[0].message.content
|
57 |
+
|
58 |
+
# Update history
|
59 |
+
if history is None:
|
60 |
+
history = []
|
61 |
+
history.append((problem_text, solution))
|
62 |
+
|
63 |
+
return solution, history
|
64 |
+
|
65 |
+
except Exception as e:
|
66 |
+
error_message = f"Error: {str(e)}"
|
67 |
+
return error_message, history
|
68 |
+
|
69 |
+
# Function to generate practice problems
|
70 |
+
def generate_practice_problem(api_key, topic, difficulty, history=None):
|
71 |
+
if not api_key.strip():
|
72 |
+
return "Please enter your OpenRouter API key.", history
|
73 |
+
|
74 |
+
if not topic.strip():
|
75 |
+
return "Please specify a math topic.", history
|
76 |
+
|
77 |
+
try:
|
78 |
+
client = OpenAI(
|
79 |
+
base_url="https://openrouter.ai/api/v1",
|
80 |
+
api_key=api_key,
|
81 |
+
)
|
82 |
+
|
83 |
+
prompt = f"""Generate a {difficulty} level math problem related to {topic}.
|
84 |
+
The problem should be challenging but solvable, and relevant to a student studying {topic}.
|
85 |
+
Only provide the problem statement, not the solution."""
|
86 |
+
|
87 |
+
completion = client.chat.completions.create(
|
88 |
+
model="microsoft/phi-4-reasoning-plus:free",
|
89 |
+
messages=[
|
90 |
+
{"role": "system", "content": "You are an expert math teacher who creates engaging practice problems."},
|
91 |
+
{"role": "user", "content": prompt}
|
92 |
+
],
|
93 |
+
extra_headers={
|
94 |
+
"HTTP-Referer": "https://advancedmathtutor.edu",
|
95 |
+
"X-Title": "Advanced Math Tutor",
|
96 |
+
}
|
97 |
+
)
|
98 |
+
|
99 |
+
practice_problem = completion.choices[0].message.content
|
100 |
+
|
101 |
+
return practice_problem, history
|
102 |
+
|
103 |
+
except Exception as e:
|
104 |
+
error_message = f"Error: {str(e)}"
|
105 |
+
return error_message, history
|
106 |
+
|
107 |
+
# Function to verify API key format
|
108 |
+
def validate_api_key(api_key):
|
109 |
+
# This is a simple check - OpenRouter keys typically start with "sk-or-"
|
110 |
+
if api_key.startswith("sk-or-") and len(api_key) > 20:
|
111 |
+
return True
|
112 |
+
return False
|
113 |
+
|
114 |
+
# Function to process LaTeX in the solution
|
115 |
+
def process_solution(solution):
|
116 |
+
# Replace $...$ with $$...$$ for better rendering in Gradio markdown
|
117 |
+
solution = re.sub(r'(?<!\$)\$(?!\$)(.+?)(?<!\$)\$(?!\$)', r'$$\1$$', solution)
|
118 |
+
return solution
|
119 |
+
|
120 |
+
# Define the Gradio interface
|
121 |
+
def create_demo():
|
122 |
+
with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as demo:
|
123 |
+
gr.Markdown("# 📚 Advanced Math Tutor")
|
124 |
+
gr.Markdown("""
|
125 |
+
This application uses Microsoft's Phi-4-reasoning-plus model to provide step-by-step solutions
|
126 |
+
to math problems. Enter your math problem, and get a detailed explanation with clear reasoning steps.
|
127 |
+
""")
|
128 |
+
|
129 |
+
# Main tabs
|
130 |
+
with gr.Tabs():
|
131 |
+
with gr.TabItem("Problem Solver"):
|
132 |
+
with gr.Row():
|
133 |
+
with gr.Column(scale=1):
|
134 |
+
api_key_input = gr.Textbox(
|
135 |
+
label="OpenRouter API Key",
|
136 |
+
placeholder="Enter your OpenRouter API key (starts with sk-or-)",
|
137 |
+
type="password"
|
138 |
+
)
|
139 |
+
problem_input = gr.Textbox(
|
140 |
+
label="Math Problem",
|
141 |
+
placeholder="Enter your math problem here...",
|
142 |
+
lines=5
|
143 |
+
)
|
144 |
+
with gr.Row():
|
145 |
+
submit_btn = gr.Button("Solve Problem", variant="primary")
|
146 |
+
clear_btn = gr.Button("Clear")
|
147 |
+
|
148 |
+
with gr.Column(scale=2):
|
149 |
+
solution_output = gr.Markdown(label="Solution")
|
150 |
+
|
151 |
+
# Store conversation history (invisible to user)
|
152 |
+
conversation_history = gr.State(value=None)
|
153 |
+
|
154 |
+
# Button actions
|
155 |
+
submit_btn.click(
|
156 |
+
fn=generate_math_solution,
|
157 |
+
inputs=[api_key_input, problem_input, conversation_history],
|
158 |
+
outputs=[solution_output, conversation_history]
|
159 |
+
)
|
160 |
+
|
161 |
+
clear_btn.click(
|
162 |
+
fn=lambda: ("", None),
|
163 |
+
inputs=[],
|
164 |
+
outputs=[solution_output, conversation_history]
|
165 |
+
)
|
166 |
+
|
167 |
+
with gr.TabItem("Practice Problems"):
|
168 |
+
with gr.Row():
|
169 |
+
with gr.Column(scale=1):
|
170 |
+
practice_api_key = gr.Textbox(
|
171 |
+
label="OpenRouter API Key",
|
172 |
+
placeholder="Enter your OpenRouter API key (starts with sk-or-)",
|
173 |
+
type="password"
|
174 |
+
)
|
175 |
+
topic_input = gr.Textbox(
|
176 |
+
label="Math Topic",
|
177 |
+
placeholder="e.g., Algebra, Calculus, Geometry...",
|
178 |
+
)
|
179 |
+
difficulty_input = gr.Dropdown(
|
180 |
+
label="Difficulty Level",
|
181 |
+
choices=["Easy", "Medium", "Hard", "Challenge"],
|
182 |
+
value="Medium"
|
183 |
+
)
|
184 |
+
generate_btn = gr.Button("Generate Practice Problem", variant="primary")
|
185 |
+
|
186 |
+
with gr.Column(scale=2):
|
187 |
+
practice_problem_output = gr.Markdown(label="Practice Problem")
|
188 |
+
solve_practice_btn = gr.Button("Solve This Practice Problem")
|
189 |
+
|
190 |
+
# Store practice problem history
|
191 |
+
practice_history = gr.State(value=None)
|
192 |
+
|
193 |
+
# Button actions for practice problems
|
194 |
+
generate_btn.click(
|
195 |
+
fn=generate_practice_problem,
|
196 |
+
inputs=[practice_api_key, topic_input, difficulty_input, practice_history],
|
197 |
+
outputs=[practice_problem_output, practice_history]
|
198 |
+
)
|
199 |
+
|
200 |
+
# Button to transfer practice problem to solver
|
201 |
+
solve_practice_btn.click(
|
202 |
+
fn=lambda problem: problem,
|
203 |
+
inputs=[practice_problem_output],
|
204 |
+
outputs=[problem_input],
|
205 |
+
_js="() => {document.querySelector('button[id^=\"tabitem\"]').click();}"
|
206 |
+
)
|
207 |
+
|
208 |
+
with gr.TabItem("Help"):
|
209 |
+
gr.Markdown("""
|
210 |
+
## How to Use the Advanced Math Tutor
|
211 |
+
|
212 |
+
### Getting Started
|
213 |
+
1. You'll need an API key from OpenRouter to use this app
|
214 |
+
2. Sign up at [OpenRouter](https://openrouter.ai/) to get your API key
|
215 |
+
3. Enter your API key in the designated field
|
216 |
+
|
217 |
+
### Solving Math Problems
|
218 |
+
- Type or paste your math problem in the input field
|
219 |
+
- Click "Solve Problem" to get a detailed step-by-step solution
|
220 |
+
- The solution will include explanations for each step
|
221 |
+
|
222 |
+
### Practice Problems
|
223 |
+
- Go to the Practice Problems tab
|
224 |
+
- Enter a math topic (e.g., "Integration", "Linear Equations")
|
225 |
+
- Select a difficulty level
|
226 |
+
- Click "Generate Practice Problem" to get a new problem
|
227 |
+
- Use "Solve This Practice Problem" to transfer it to the solver
|
228 |
+
|
229 |
+
### Tips for Best Results
|
230 |
+
- Be specific in your problem description
|
231 |
+
- Include all necessary information
|
232 |
+
- For complex equations, use clear notation
|
233 |
+
|
234 |
+
### Example Problems
|
235 |
+
Try these example problems:
|
236 |
+
- Solve the quadratic equation: 3x² + 5x - 2 = 0
|
237 |
+
- Find the derivative of f(x) = x³ln(x)
|
238 |
+
- Calculate the area of a circle with radius 5 cm
|
239 |
+
""")
|
240 |
+
|
241 |
+
# Footer
|
242 |
+
gr.Markdown("""
|
243 |
+
---
|
244 |
+
### About
|
245 |
+
This application uses Microsoft's Phi-4-reasoning-plus model via OpenRouter to generate step-by-step solutions.
|
246 |
+
Your API key is required but not stored permanently.
|
247 |
+
""")
|
248 |
+
|
249 |
+
return demo
|
250 |
+
|
251 |
+
# Launch the app
|
252 |
+
if __name__ == "__main__":
|
253 |
+
demo = create_demo()
|
254 |
+
demo.launch()
|