Skip to content

Commit ccb4a34

Browse files
Merge pull request #745 from MervinPraison/claude/issue-744-20250707_174818
feat: Add examples for documented features
2 parents d7fcaf8 + cac7014 commit ccb4a34

File tree

6 files changed

+1213
-0
lines changed

6 files changed

+1213
-0
lines changed
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
"""
2+
Code Agent Example
3+
4+
This example demonstrates a comprehensive code agent that can write, analyze, debug, and execute code.
5+
It includes self-reflection for improving code quality and multiple specialized tools.
6+
"""
7+
8+
from praisonaiagents import Agent, Task, PraisonAIAgents
9+
from praisonaiagents.tools import CodeInterpreter
10+
11+
# Initialize code execution tool
12+
code_interpreter = CodeInterpreter()
13+
14+
# Custom code analysis tool
15+
def analyze_code_complexity(code: str) -> str:
16+
"""Analyze code complexity and provide feedback."""
17+
lines = code.strip().split('\n')
18+
num_lines = len(lines)
19+
num_functions = sum(1 for line in lines if line.strip().startswith('def '))
20+
num_classes = sum(1 for line in lines if line.strip().startswith('class '))
21+
22+
return f"""Code Analysis:
23+
- Lines of code: {num_lines}
24+
- Functions: {num_functions}
25+
- Classes: {num_classes}
26+
- Complexity: {'Simple' if num_lines < 50 else 'Moderate' if num_lines < 200 else 'Complex'}"""
27+
28+
# Create specialized code agents
29+
code_writer = Agent(
30+
name="CodeWriter",
31+
role="Expert Python developer",
32+
goal="Write clean, efficient, and well-documented Python code",
33+
backstory="You are a senior Python developer with 10+ years of experience in writing production-quality code.",
34+
instructions="Write Python code that follows PEP 8 standards, includes proper error handling, and has clear documentation.",
35+
self_reflect=True,
36+
min_reflect=2,
37+
max_reflect=5
38+
)
39+
40+
code_reviewer = Agent(
41+
name="CodeReviewer",
42+
role="Code quality expert",
43+
goal="Review code for bugs, security issues, and best practices",
44+
backstory="You are a code review specialist who ensures code quality and maintainability.",
45+
instructions="Review the provided code for potential issues, suggest improvements, and ensure it follows best practices.",
46+
tools=[analyze_code_complexity]
47+
)
48+
49+
code_executor = Agent(
50+
name="CodeExecutor",
51+
role="Code execution specialist",
52+
goal="Safely execute and test Python code",
53+
backstory="You are responsible for running code and reporting results or errors.",
54+
instructions="Execute the provided code safely and report the output or any errors encountered.",
55+
tools=[code_interpreter]
56+
)
57+
58+
# Example tasks
59+
def demonstrate_code_agent():
60+
# Task 1: Write a function
61+
write_task = Task(
62+
name="write_function",
63+
description="Write a Python function that calculates the Fibonacci sequence up to n terms",
64+
expected_output="A well-documented Python function with error handling",
65+
agent=code_writer
66+
)
67+
68+
# Task 2: Review the code
69+
review_task = Task(
70+
name="review_code",
71+
description="Review the Fibonacci function for quality and suggest improvements",
72+
expected_output="Detailed code review with suggestions",
73+
agent=code_reviewer,
74+
context=[write_task]
75+
)
76+
77+
# Task 3: Execute and test
78+
execute_task = Task(
79+
name="execute_code",
80+
description="Execute the Fibonacci function with n=10 and verify it works correctly",
81+
expected_output="Execution results showing the first 10 Fibonacci numbers",
82+
agent=code_executor,
83+
context=[write_task]
84+
)
85+
86+
# Create workflow
87+
workflow = PraisonAIAgents(
88+
agents=[code_writer, code_reviewer, code_executor],
89+
tasks=[write_task, review_task, execute_task],
90+
process="sequential",
91+
verbose=True
92+
)
93+
94+
# Run the workflow
95+
result = workflow.start()
96+
return result
97+
98+
# Standalone code agent for general programming tasks
99+
general_code_agent = Agent(
100+
name="GeneralCodeAgent",
101+
role="Full-stack programming assistant",
102+
goal="Help with any programming task including writing, debugging, and explaining code",
103+
backstory="You are an AI programming assistant with expertise in multiple languages and frameworks.",
104+
instructions="""You can:
105+
1. Write code in any programming language
106+
2. Debug and fix code issues
107+
3. Explain code concepts
108+
4. Refactor code for better performance
109+
5. Add tests and documentation""",
110+
tools=[code_interpreter, analyze_code_complexity],
111+
self_reflect=True,
112+
min_reflect=1,
113+
max_reflect=3
114+
)
115+
116+
if __name__ == "__main__":
117+
# Example 1: Run the multi-agent workflow
118+
print("=== Multi-Agent Code Workflow ===")
119+
result = demonstrate_code_agent()
120+
print(f"Workflow Result: {result}")
121+
122+
# Example 2: Use the general code agent
123+
print("\n=== General Code Agent ===")
124+
response = general_code_agent.start("""
125+
Write a Python class for a simple Calculator with methods for:
126+
- Addition
127+
- Subtraction
128+
- Multiplication
129+
- Division (with error handling for division by zero)
130+
131+
Then create a simple test to verify it works.
132+
""")
133+
print(response)
Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
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)
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
"""
2+
Chat with PDF Example
3+
4+
This example demonstrates how to create an agent that can read and answer questions about PDF documents.
5+
It uses the knowledge parameter to load PDF files and provides interactive Q&A capabilities.
6+
"""
7+
8+
from praisonaiagents import Agent
9+
10+
# Configure vector store for PDF storage
11+
config = {
12+
"vector_store": {
13+
"provider": "chroma",
14+
"config": {
15+
"collection_name": "pdf_chat",
16+
"path": ".praison_pdf_chat",
17+
}
18+
}
19+
}
20+
21+
# Create a PDF chat agent
22+
pdf_agent = Agent(
23+
name="PDF Assistant",
24+
role="PDF document expert",
25+
goal="Help users understand and extract information from PDF documents",
26+
backstory="You are an expert at reading, analyzing, and answering questions about PDF documents. You provide accurate, detailed answers based on the document content.",
27+
instructions="Read the provided PDF document and answer questions about its content. Be specific and cite relevant sections when possible.",
28+
knowledge=["document.pdf"], # Replace with your PDF file path
29+
knowledge_config=config,
30+
self_reflect=True,
31+
min_reflect=1,
32+
max_reflect=3
33+
)
34+
35+
# Example usage
36+
if __name__ == "__main__":
37+
# Single question
38+
response = pdf_agent.start("What are the main topics covered in this document?")
39+
print(response)
40+
41+
# Interactive chat
42+
print("\nPDF Chat Assistant Ready! Type 'quit' to exit.")
43+
while True:
44+
question = input("\nYour question: ")
45+
if question.lower() == 'quit':
46+
break
47+
48+
response = pdf_agent.start(question)
49+
print(f"\nAnswer: {response}")

0 commit comments

Comments
 (0)