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 )
0 commit comments