1
+ """
2
+ Math Agent Example
3
+
4
+ This example demonstrates a mathematical problem-solving agent that can handle various math tasks
5
+ including calculations, equation solving, and step-by-step explanations.
6
+ """
7
+
8
+ from praisonaiagents import Agent , Task , PraisonAIAgents
9
+ from typing import Dict , Any
10
+ import math
11
+ import re
12
+
13
+ # Custom math tools
14
+ def basic_calculator (expression : str ) -> str :
15
+ """Evaluate basic mathematical expressions safely."""
16
+ try :
17
+ # Remove any non-mathematical characters for safety
18
+ safe_expr = re .sub (r'[^0-9+\-*/().,\s]' , '' , expression )
19
+ result = eval (safe_expr )
20
+ return f"Result: { result } "
21
+ except Exception as e :
22
+ return f"Error in calculation: { str (e )} "
23
+
24
+ def solve_quadratic (a : float , b : float , c : float ) -> str :
25
+ """Solve quadratic equation ax² + bx + c = 0."""
26
+ discriminant = b ** 2 - 4 * a * c
27
+
28
+ if discriminant > 0 :
29
+ x1 = (- b + math .sqrt (discriminant )) / (2 * a )
30
+ x2 = (- b - math .sqrt (discriminant )) / (2 * a )
31
+ return f"Two real solutions: x₁ = { x1 :.4f} , x₂ = { x2 :.4f} "
32
+ elif discriminant == 0 :
33
+ x = - b / (2 * a )
34
+ return f"One real solution: x = { x :.4f} "
35
+ else :
36
+ real_part = - b / (2 * a )
37
+ imag_part = math .sqrt (- discriminant ) / (2 * a )
38
+ return f"Two complex solutions: x₁ = { real_part :.4f} + { imag_part :.4f} i, x₂ = { real_part :.4f} - { imag_part :.4f} i"
39
+
40
+ def calculate_statistics (numbers : list ) -> str :
41
+ """Calculate basic statistics for a list of numbers."""
42
+ if not numbers :
43
+ return "No numbers provided"
44
+
45
+ n = len (numbers )
46
+ mean = sum (numbers ) / n
47
+ sorted_nums = sorted (numbers )
48
+ median = sorted_nums [n // 2 ] if n % 2 else (sorted_nums [n // 2 - 1 ] + sorted_nums [n // 2 ]) / 2
49
+ variance = sum ((x - mean )** 2 for x in numbers ) / n
50
+ std_dev = math .sqrt (variance )
51
+
52
+ return f"""Statistics:
53
+ - Count: { n }
54
+ - Mean: { mean :.4f}
55
+ - Median: { median :.4f}
56
+ - Standard Deviation: { std_dev :.4f}
57
+ - Min: { min (numbers )}
58
+ - Max: { max (numbers )} """
59
+
60
+ # Create specialized math agents
61
+ calculation_agent = Agent (
62
+ name = "CalculationAgent" ,
63
+ role = "Mathematical calculation specialist" ,
64
+ goal = "Perform accurate mathematical calculations and computations" ,
65
+ backstory = "You are an expert mathematician who can handle complex calculations with precision." ,
66
+ instructions = "Perform the requested calculations step by step, showing your work clearly." ,
67
+ tools = [basic_calculator , solve_quadratic , calculate_statistics ],
68
+ self_reflect = True ,
69
+ min_reflect = 1 ,
70
+ max_reflect = 2
71
+ )
72
+
73
+ problem_solver_agent = Agent (
74
+ name = "ProblemSolver" ,
75
+ role = "Mathematical problem solver" ,
76
+ goal = "Solve complex math problems with detailed explanations" ,
77
+ backstory = "You are a math teacher who excels at breaking down complex problems into understandable steps." ,
78
+ instructions = """When solving math problems:
79
+ 1. Identify the type of problem
80
+ 2. List the given information
81
+ 3. Determine what needs to be found
82
+ 4. Show each step of the solution
83
+ 5. Verify the answer makes sense""" ,
84
+ self_reflect = True ,
85
+ min_reflect = 2 ,
86
+ max_reflect = 4
87
+ )
88
+
89
+ math_tutor_agent = Agent (
90
+ name = "MathTutor" ,
91
+ role = "Mathematics tutor and explainer" ,
92
+ goal = "Explain mathematical concepts clearly and help users understand math" ,
93
+ backstory = "You are a patient math tutor who can explain concepts at any level from elementary to advanced." ,
94
+ instructions = "Explain mathematical concepts using simple language, provide examples, and check for understanding."
95
+ )
96
+
97
+ # Example workflow for solving complex problems
98
+ def solve_math_problem_workflow ():
99
+ # Task 1: Understand the problem
100
+ understand_task = Task (
101
+ name = "understand_problem" ,
102
+ description = """A farmer has a rectangular field. The length is 3 meters more than twice the width.
103
+ If the perimeter is 96 meters, what are the dimensions of the field?""" ,
104
+ expected_output = "Clear problem statement with identified variables and equations" ,
105
+ agent = problem_solver_agent
106
+ )
107
+
108
+ # Task 2: Solve the problem
109
+ solve_task = Task (
110
+ name = "solve_problem" ,
111
+ description = "Solve for the dimensions using the equations identified" ,
112
+ expected_output = "The width and length of the field with calculations shown" ,
113
+ agent = calculation_agent ,
114
+ context = [understand_task ]
115
+ )
116
+
117
+ # Task 3: Verify and explain
118
+ verify_task = Task (
119
+ name = "verify_solution" ,
120
+ description = "Verify the solution is correct and explain why it makes sense" ,
121
+ expected_output = "Verification that the solution satisfies all conditions" ,
122
+ agent = math_tutor_agent ,
123
+ context = [solve_task ]
124
+ )
125
+
126
+ workflow = PraisonAIAgents (
127
+ agents = [problem_solver_agent , calculation_agent , math_tutor_agent ],
128
+ tasks = [understand_task , solve_task , verify_task ],
129
+ process = "sequential" ,
130
+ verbose = True
131
+ )
132
+
133
+ return workflow .start ()
134
+
135
+ # General math assistant combining all capabilities
136
+ math_assistant = Agent (
137
+ name = "MathAssistant" ,
138
+ role = "Comprehensive mathematics assistant" ,
139
+ goal = "Help with any mathematical task from basic arithmetic to complex problem solving" ,
140
+ backstory = "You are an AI math assistant with expertise in all areas of mathematics." ,
141
+ instructions = """You can help with:
142
+ 1. Basic arithmetic and calculations
143
+ 2. Algebra and equation solving
144
+ 3. Geometry and trigonometry
145
+ 4. Calculus and advanced mathematics
146
+ 5. Statistics and probability
147
+ 6. Math tutoring and explanations
148
+
149
+ Always show your work step by step.""" ,
150
+ tools = [basic_calculator , solve_quadratic , calculate_statistics ],
151
+ self_reflect = True ,
152
+ min_reflect = 1 ,
153
+ max_reflect = 3
154
+ )
155
+
156
+ if __name__ == "__main__" :
157
+ # Example 1: Basic calculation
158
+ print ("=== Basic Calculation ===" )
159
+ result = calculation_agent .start ("Calculate: (15 + 23) * 4 - 18 / 3" )
160
+ print (result )
161
+
162
+ # Example 2: Quadratic equation
163
+ print ("\n === Quadratic Equation ===" )
164
+ result = calculation_agent .start ("Solve the equation: 2x² - 5x + 3 = 0" )
165
+ print (result )
166
+
167
+ # Example 3: Statistics
168
+ print ("\n === Statistics ===" )
169
+ result = calculation_agent .start ("Calculate statistics for: [12, 15, 18, 20, 22, 25, 28, 30]" )
170
+ print (result )
171
+
172
+ # Example 4: Complex problem workflow
173
+ print ("\n === Complex Problem Workflow ===" )
174
+ result = solve_math_problem_workflow ()
175
+ print (f"Workflow Result: { result } " )
176
+
177
+ # Example 5: General math assistance
178
+ print ("\n === General Math Assistance ===" )
179
+ result = math_assistant .start ("""
180
+ I need help with this problem:
181
+ A ball is thrown upward with an initial velocity of 20 m/s.
182
+ The height h(t) = 20t - 5t² where t is time in seconds.
183
+
184
+ 1. When does the ball reach maximum height?
185
+ 2. What is the maximum height?
186
+ 3. When does the ball hit the ground?
187
+ """ )
188
+ print (result )
0 commit comments