ConnectOnion
5

Math Tutor Agent

Intermediate

Learn educational AI patterns and step-by-step explanation generation with a comprehensive math tutoring system.

What You'll Learn

Educational Patterns

Pedagogy and teaching methodologies

Step-by-Step

Breaking down complex problems

Answer Validation

Checking and feedback systems

Encouragement

Motivation and confidence building

Basic Math Tutor

1from connectonion import Agent
2
3def solve_equation(equation: str) -> str:
4    """Solve a mathematical equation step by step."""
5    try:
6        # Simple linear equations for demo
7        if "x" in equation and "=" in equation:
8            left, right = equation.split("=")
9            # Example: 2x + 5 = 15
10            return f"Let's solve {equation} step by step:\n1. Subtract from both sides\n2. Divide by coefficient\nSolution: x = 5"
11        return "I can help with linear equations containing 'x' and '='"
12    except:
13        return "Please provide a valid equation format"
14
15def explain_concept(topic: str) -> str:
16    """Explain mathematical concepts clearly."""
17    explanations = {
18        "fractions": "Fractions represent parts of a whole. Think of pizza slices!",
19        "percentages": "Percentages are fractions out of 100. 25% = 25/100 = 0.25",
20        "algebra": "Algebra uses letters to represent unknown numbers we need to find"
21    }
22    return explanations.get(topic.lower(), f"I'd be happy to explain {topic}!")
23
24# Create math tutor agent
25agent = Agent(
26    name="math_tutor",
27    system_prompt="You are a patient, encouraging math tutor.",
28    tools=[solve_equation, explain_concept]
29)

Complete Math Tutor

1# math_tutor_agent.py
2import os
3import re
4from connectonion import Agent
5
6# Set your OpenAI API key
7os.environ['OPENAI_API_KEY'] = 'your-api-key-here'
8
9def solve_linear_equation(equation: str) -> str:
10    """Solve linear equations step by step with detailed explanations."""
11    try:
12        # Clean the equation
13        equation = equation.replace(" ", "").replace("=", " = ")
14        
15        if "x" not in equation or "=" not in equation:
16            return "โŒ I can only solve equations with 'x' and '=' for now. Try something like '2x + 5 = 15'"
17        
18        # Parse simple linear equations (ax + b = c format)
19        left, right = equation.split(" = ")
20        
21        # Example solutions for common patterns
22        if equation in ["2x+5=15", "2x + 5 = 15"]:
23            return """๐Ÿ“š Let's solve 2x + 5 = 15 step by step:
24
25๐ŸŽฏ **Goal**: Isolate x by undoing operations in reverse order
26
27**Step 1**: Start with the equation
28   2x + 5 = 15
29
30**Step 2**: Subtract 5 from both sides (undo the +5)
31   2x + 5 - 5 = 15 - 5
32   2x = 10
33
34**Step 3**: Divide both sides by 2 (undo the ร—2)  
35   2x รท 2 = 10 รท 2
36   x = 5
37
38โœ… **Answer**: x = 5
39
40**Check**: 2(5) + 5 = 10 + 5 = 15 โœ“
41
42๐ŸŽ‰ Great job! The key is to undo operations in reverse order of PEMDAS."""
43        
44        elif equation in ["3x-7=14", "3x - 7 = 14"]:
45            return """๐Ÿ“š Let's solve 3x - 7 = 14 step by step:
46
47**Step 1**: Start with the equation
48   3x - 7 = 14
49
50**Step 2**: Add 7 to both sides (undo the -7)
51   3x - 7 + 7 = 14 + 7
52   3x = 21
53
54**Step 3**: Divide both sides by 3 (undo the ร—3)
55   3x รท 3 = 21 รท 3
56   x = 7
57
58โœ… **Answer**: x = 7
59
60**Check**: 3(7) - 7 = 21 - 7 = 14 โœ“"""
61        
62        else:
63            return f"""๐Ÿค” I see you want to solve: {equation}
64
65I can provide detailed step-by-step solutions for these equations:
66โ€ข 2x + 5 = 15
67โ€ข 3x - 7 = 14  
68โ€ข x + 8 = 20
69โ€ข 4x = 12
70
71Try one of these, or ask me to explain the general process for solving linear equations!"""
72    
73    except Exception as e:
74        return f"โŒ I had trouble parsing that equation. Please use format like '2x + 5 = 15'"
75
76def explain_math_concept(concept: str) -> str:
77    """Provide clear explanations of mathematical concepts with examples."""
78    concept = concept.lower().strip()
79    
80    explanations = {
81        "fractions": """๐Ÿ• **Fractions - Parts of a Whole**
82
83**What are fractions?**
84Fractions represent parts of something whole. Think of a pizza!
85
86**Examples:**
87โ€ข 1/4 = 1 piece out of 4 total pieces
88โ€ข 3/4 = 3 pieces out of 4 total pieces
89โ€ข 1/2 = half of something
90
91**Key Terms:**
92โ€ข **Numerator** (top number): How many pieces you have
93โ€ข **Denominator** (bottom number): Total pieces the whole is divided into
94
95**Real Life:**
96โ€ข 1/2 cup of flour in a recipe
97โ€ข 3/4 of students passed the test
98โ€ข 2/3 of the pizza was eaten
99
100Would you like me to explain adding fractions or converting to decimals?""",
101
102        "percentages": """๐Ÿ“Š **Percentages - Out of 100**
103
104**What are percentages?**  
105Percentages are just fractions with 100 as the denominator!
106
107**The Magic Number: 100**
108โ€ข 25% = 25/100 = 0.25
109โ€ข 50% = 50/100 = 0.50
110โ€ข 75% = 75/100 = 0.75
111
112**Easy Conversions:**
113โ€ข To convert fraction โ†’ percentage: (numerator รท denominator) ร— 100
114โ€ข Example: 3/4 = (3 รท 4) ร— 100 = 0.75 ร— 100 = 75%
115
116**Real Life Examples:**
117โ€ข 20% tip at restaurant
118โ€ข 50% off sale price  
119โ€ข 90% grade on test
120โ€ข Phone battery at 25%
121
122**Quick Calculation Trick:**
123To find 10% of anything, just move the decimal point left one place!
124โ€ข 10% of 50 = 5.0 = 5
125โ€ข 10% of 230 = 23.0 = 23""",
126
127        "algebra": """๐Ÿ”ค **Algebra - Finding the Unknown**
128
129**What is Algebra?**
130Algebra uses letters (like x, y, z) to represent unknown numbers we need to find.
131
132**Why use letters?**
133Instead of saying "some unknown number," we just write "x"
134
135**Basic Idea:**
136โ€ข x + 5 = 8  means  "what number plus 5 equals 8?"
137โ€ข Answer: x = 3 (because 3 + 5 = 8)
138
139**The Golden Rule:**
140Whatever you do to one side of the equation, do to the other side too!
141
142**Example Process:**
143   x + 5 = 8
144   x + 5 - 5 = 8 - 5  โ† subtract 5 from both sides
145   x = 3
146
147**Real Life Applications:**
148โ€ข If I save $x per month and want $120 after 4 months: 4x = 120
149โ€ข If pizza costs $y and I paid $15 with $3 change: y + 3 = 15
150โ€ข Age problems, distance problems, money problems
151
152The key is turning word problems into equations with letters!""",
153
154        "linear equations": """โš–๏ธ **Linear Equations - Keeping Balance**
155
156**What are Linear Equations?**
157Equations with variables (like x) where the highest power is 1.
158
159**Examples:**
160โ€ข 2x + 3 = 9 โœ… (Linear)  
161โ€ข xยฒ + 5 = 10 โŒ (Not linear - has xยฒ)
162
163**Solving Strategy - Think "Undo":**
1641. **Identify** what operations are being done to x
1652. **Undo** them in reverse order (like getting dressed in reverse)
166
167**Example**: 2x + 5 = 15
168โ€ข Operations on x: multiply by 2, then add 5
169โ€ข To undo: subtract 5 first, then divide by 2
170
171**Step by Step:**
172   2x + 5 = 15
173   2x = 10      โ† undid the +5
174   x = 5        โ† undid the ร—2
175
176**Always Check:** 2(5) + 5 = 10 + 5 = 15 โœ“
177
178**Memory Trick:** "Whatever you do to one side, do to the other - keep the equation balanced like a scale!" โš–๏ธ"""
179    }
180    
181    if concept in explanations:
182        return explanations[concept]
183    else:
184        available = list(explanations.keys())
185        return f"""๐Ÿค” I don't have that concept ready yet, but I can explain:
186        
187๐Ÿ”น {' โ€ข '.join(available)}
188
189Which one would you like me to explain, or ask me about a specific math problem you're working on!"""
190
191def check_answer(problem: str, student_answer: str) -> str:
192    """Check if a student's answer is correct and provide feedback."""
193    # Simple answer checking for demo problems
194    correct_answers = {
195        "2x + 5 = 15": "5",
196        "3x - 7 = 14": "7", 
197        "x + 8 = 20": "12",
198        "4x = 12": "3",
199        "what is 25% of 80": "20",
200        "what is 3/4 as a percentage": "75%"
201    }
202    
203    problem_key = problem.lower().strip()
204    student_ans = student_answer.lower().strip().replace("x=", "").replace("x =", "")
205    
206    if problem_key in correct_answers:
207        correct = correct_answers[problem_key]
208        if student_ans == correct.lower():
209            return f"๐ŸŽ‰ **Excellent!** That's exactly right! {problem} has the answer {correct}. You're getting the hang of this!"
210        else:
211            return f"""๐Ÿค” Not quite! For {problem}, you answered '{student_answer}' but the correct answer is {correct}.
212
213๐Ÿ’ก **Hint**: Would you like me to show you the step-by-step solution? I can help you see where the confusion might be coming from."""
214    
215    return f"""I'd be happy to check that for you! 
216
217For the problem: {problem}
218Your answer: {student_answer}
219
220Let me work through it step by step to see if we get the same result..."""
221
222def give_encouragement(context: str = "") -> str:
223    """Provide encouraging feedback and motivation."""
224    encouragements = [
225        "๐ŸŒŸ You're doing great! Math takes practice, and every mistake is a learning opportunity.",
226        "๐Ÿ’ช Keep going! The more you practice, the more confident you'll become with math.",
227        "๐ŸŽฏ Remember: every math expert was once a beginner. You're on the right path!",
228        "โœจ Great question! Asking questions is how we learn and grow in mathematics.",
229        "๐Ÿง  Your brain is like a muscle - the more you exercise it with math, the stronger it gets!"
230    ]
231    
232    import random
233    base_encouragement = random.choice(encouragements)
234    
235    if "struggling" in context.lower() or "hard" in context.lower():
236        return f"""{base_encouragement}
237
238๐Ÿ’ก **Remember**: 
239โ€ข It's okay to make mistakes - that's how we learn!
240โ€ข Break big problems into smaller steps
241โ€ข Draw pictures or use real examples when possible
242โ€ข Ask for help when you need it
243
244What specific part is giving you trouble? I'm here to help! ๐Ÿค"""
245    
246    return base_encouragement
247
248# Create the math tutor agent
249agent = Agent(
250    name="math_tutor",
251    system_prompt="""You are an expert math tutor who is patient, encouraging, and great at explaining concepts clearly. Your teaching style:
252
253๐ŸŽฏ **Always**:
254โ€ข Break down complex problems into simple steps
255โ€ข Use real-world examples and analogies  
256โ€ข Celebrate student progress and effort
257โ€ข Ask if they understand before moving on
258โ€ข Provide encouragement when students struggle
259
260๐Ÿ“š **Teaching Method**:
2611. Understand what the student is confused about
2622. Explain the concept with examples
2633. Show step-by-step solutions 
2644. Let them practice similar problems
2655. Give positive, constructive feedback
266
267๐Ÿ’ก **Remember**: Every student learns differently, so adapt your explanations to their needs!""",
268    tools=[solve_linear_equation, explain_math_concept, check_answer, give_encouragement]
269)
270
271if __name__ == "__main__":
272    print("=== Math Tutor Agent Demo ===\n")
273    
274    # Demo conversation
275    test_cases = [
276        "I'm struggling with fractions. Can you help me understand them?",
277        "How do I solve 2x + 5 = 15?", 
278        "What are percentages and how do they work?",
279        "Can you check my answer? For 3x - 7 = 14, I got x = 7",
280        "I'm having a hard time with algebra. It's so confusing!"
281    ]
282    
283    for i, question in enumerate(test_cases, 1):
284        print(f"Student Question {i}: {question}")
285        response = agent.input(question)
286        print(f"Tutor Response: {response}\n")
287        print("-" * 70)

Expected Output

=== Math Tutor Agent Demo ===

Student Question 1: I'm struggling with fractions. Can you help me understand them?
Tutor Response: ๐Ÿ• **Fractions - Parts of a Whole**

**What are fractions?**
Fractions represent parts of something whole. Think of a pizza!

**Examples:**
โ€ข 1/4 = 1 piece out of 4 total pieces
โ€ข 3/4 = 3 pieces out of 4 total pieces
โ€ข 1/2 = half of something

**Key Terms:**
โ€ข **Numerator** (top number): How many pieces you have
โ€ข **Denominator** (bottom number): Total pieces the whole is divided into

Student Question 2: How do I solve 2x + 5 = 15?
Tutor Response: ๐Ÿ“š Let's solve 2x + 5 = 15 step by step:

๐ŸŽฏ **Goal**: Isolate x by undoing operations in reverse order

**Step 1**: Start with the equation
   2x + 5 = 15

**Step 2**: Subtract 5 from both sides (undo the +5)
   2x + 5 - 5 = 15 - 5
   2x = 10

**Step 3**: Divide both sides by 2 (undo the ร—2)  
   2x รท 2 = 10 รท 2
   x = 5

โœ… **Answer**: x = 5

**Check**: 2(5) + 5 = 10 + 5 = 15 โœ“

๐ŸŽ‰ Great job! The key is to undo operations in reverse order of PEMDAS.

Educational AI Patterns

๐ŸŽฏ Scaffolded Learning

Break complex problems into manageable steps students can follow.

๐Ÿง  Analogies & Examples

Use real-world examples (pizza for fractions) to make abstract concepts concrete.

โœ… Immediate Feedback

Check answers and provide constructive feedback to guide learning.

Teaching Features

๐Ÿ“š Concept Library

Fractions, percentages, algebra, and linear equations with examples

๐Ÿ” Step-by-Step Solutions

Detailed equation solving with verification steps

๐Ÿ’ช Encouragement System

Motivational feedback and confidence-building responses

Try It Yourself

Download Complete Example

Complete math tutor with step-by-step solutions and encouragement