Prerequisites

  • Python 3.10 or higher
  • PraisonAI Agents package installed
  • Basic understanding of Python programming

Python Tools

Use Python Tools to execute and manage Python code with AI agents.

1

Install Dependencies

First, install the required package:

pip install praisonaiagents
2

Import Components

Import the necessary components:

from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import (
    execute_code, analyze_code, format_code,
    lint_code, disassemble_code
)
3

Create Agent

Create a Python execution agent:

python_agent = Agent(
    name="PythonExecutor",
    role="Python Code Specialist",
    goal="Execute Python code efficiently and safely.",
    backstory="Expert in Python programming and code execution.",
    tools=[
        execute_code, analyze_code, format_code,
        lint_code, disassemble_code
    ],
    self_reflect=False
)
4

Define Task

Define the Python execution task:

python_task = Task(
    description="Execute and manage Python code.",
    expected_output="Code execution results.",
    agent=python_agent,
    name="code_execution"
)
5

Run Agent

Initialize and run the agent:

agents = PraisonAIAgents(
    agents=[python_agent],
    tasks=[python_task],
    process="sequential"
)
agents.start()

Available Functions

from praisonaiagents.tools import execute_code
from praisonaiagents.tools import analyze_code
from praisonaiagents.tools import format_code
from praisonaiagents.tools import lint_code
from praisonaiagents.tools import disassemble_code

Function Details

execute_code(code: str, globals_dict: Optional[Dict[str, Any]] = None, locals_dict: Optional[Dict[str, Any]] = None, timeout: int = 30, max_output_size: int = 10000)

Safely executes Python code:

  • Isolated execution environment
  • Output capture
  • Error handling
  • Timeout protection
  • Output size limits
# Basic execution
result = execute_code("print('Hello, World!')")

# With custom environment
result = execute_code(
    """
    x = 10
    y = 20
    print(f'Sum: {x + y}')
    """,
    globals_dict={'__builtins__': __builtins__},
    timeout=5
)

# Returns: Dict[str, Any]
# Example output:
# {
#     'result': None,
#     'stdout': 'Hello, World!\n',
#     'stderr': '',
#     'success': True
# }

analyze_code(code: str)

Analyzes Python code structure:

  • Import statements
  • Function definitions
  • Class definitions
  • Variable usage
  • Code complexity
# Analyze code structure
analysis = analyze_code("""
def greet(name):
    return f"Hello, {name}!"

class Person:
    def __init__(self, name):
        self.name = name
""")

# Returns: Dict[str, Any]
# Example output:
# {
#     'imports': [],
#     'functions': [
#         {
#             'name': 'greet',
#             'args': ['name'],
#             'decorators': []
#         }
#     ],
#     'classes': [
#         {
#             'name': 'Person',
#             'bases': [],
#             'decorators': []
#         }
#     ],
#     'variables': ['name'],
#     'complexity': {
#         'lines': 6,
#         'functions': 2,
#         'classes': 1,
#         'branches': 0
#     }
# }

format_code(code: str, style: str = ‘black’, line_length: int = 88)

Formats Python code:

  • Multiple style options
  • Line length control
  • PEP 8 compliance
  • Consistent formatting
# Format with black
formatted = format_code("""
def messy_function(x,y,   z):
    if x>0:
     return y+z
    else:
     return y-z
""")

# Format with PEP 8
formatted = format_code(
    """
    def messy_function(x,y,   z):
        if x>0:
         return y+z
        else:
         return y-z
    """,
    style='pep8',
    line_length=79
)

# Returns: str
# Example output:
# def messy_function(x, y, z):
#     if x > 0:
#         return y + z
#     else:
#         return y - z

lint_code(code: str)

Lints Python code for issues:

  • Code quality checks
  • Style violations
  • Potential bugs
  • Best practices
# Lint code for issues
results = lint_code("""
def bad_function():
    unused_var = 42
    return 'result'
""")

# Returns: Dict[str, List[Dict[str, Any]]]
# Example output:
# {
#     'errors': [],
#     'warnings': [
#         {
#             'type': 'warning',
#             'module': 'bad_function',
#             'obj': 'unused_var',
#             'line': 2,
#             'column': 4,
#             'path': '<string>',
#             'symbol': 'unused-variable',
#             'message': 'Unused variable "unused_var"',
#             'message-id': 'W0612'
#         }
#     ],
#     'conventions': []
# }

disassemble_code(code: str)

Disassembles Python code to bytecode:

  • Bytecode inspection
  • Performance analysis
  • Code optimization
  • Debugging support
# Disassemble code to bytecode
bytecode = disassemble_code("""
def add(a, b):
    return a + b
""")

# Returns: str
# Example output:
#  1           0 LOAD_CONST               0 (<code object add at ...>)
#              2 LOAD_CONST               1 ('add')
#              4 MAKE_FUNCTION            0
#              6 STORE_NAME               0 (add)
#              8 LOAD_CONST               2 (None)
#             10 RETURN_VALUE

Example Agent Configuration

from praisonaiagents import Agent
from praisonaiagents.tools import (
    execute_code, analyze_code, format_code,
    lint_code, disassemble_code
)

agent = Agent(
    name="PythonDeveloper",
    description="An agent that helps with Python development",
    tools=[
        execute_code, analyze_code, format_code,
        lint_code, disassemble_code
    ]
)

Dependencies

The Python tools require the following packages:

  • black: For code formatting (black style)
  • autopep8: For code formatting (PEP 8 style)
  • pylint: For code linting

These will be automatically installed when needed.

Error Handling

All functions include comprehensive error handling:

  • Code execution errors
  • Syntax errors
  • Import errors
  • Timeout errors
  • Memory errors

Errors are handled consistently:

  • Success cases return expected data type
  • Error cases return None or error details
  • All errors are logged for debugging

Common Use Cases

  1. Code Testing:
# Test code execution
test_code = """
def factorial(n):
    return 1 if n <= 1 else n * factorial(n - 1)

result = factorial(5)
print(f"Factorial: {result}")
"""
result = execute_code(test_code)
print(f"Output: {result['stdout']}")
  1. Code Quality:
# Check code quality
code = """
def process_data(data):
    processed = []
    for item in data:
        if item > 0:
            processed.append(item * 2)
    return processed
"""
analysis = analyze_code(code)
lint_results = lint_code(code)
formatted = format_code(code)
  1. Code Analysis:
# Analyze code structure
code = """
class DataProcessor:
    def __init__(self, data):
        self.data = data
    
    def process(self):
        return [x * 2 for x in self.data]
"""
structure = analyze_code(code)
bytecode = disassemble_code(code)
print(f"Classes: {structure['classes']}")
print(f"Functions: {structure['functions']}")

Understanding Python Tools

What are Python Tools?

Python Tools provide code execution capabilities for AI agents:

  • Code execution
  • Module management
  • Error handling
  • Output capture
  • Environment control

Examples

Basic Python Execution Agent

from praisonaiagents import Agent, Task, PraisonAIAgents
from praisonaiagents.tools import (
    execute_code, analyze_code, format_code,
    lint_code, disassemble_code
)

# Create Python agent
python_agent = Agent(
    name="PythonExpert",
    role="Code Execution Specialist",
    goal="Execute Python code efficiently and safely.",
    backstory="Expert in Python programming and execution.",
    tools=[
        execute_code, analyze_code, format_code,
        lint_code, disassemble_code
    ],
    self_reflect=False
)

# Define Python task
python_task = Task(
    description="Execute data processing scripts.",
    expected_output="Processing results.",
    agent=python_agent,
    name="data_processing"
)

# Run agent
agents = PraisonAIAgents(
    agents=[python_agent],
    tasks=[python_task],
    process="sequential"
)
agents.start()

Advanced Python Operations with Multiple Agents

# Create execution agent
executor_agent = Agent(
    name="CodeExecutor",
    role="Code Execution Specialist",
    goal="Execute Python code efficiently.",
    tools=[
        execute_code, analyze_code, format_code,
        lint_code, disassemble_code
    ],
    self_reflect=False
)

# Create monitoring agent
monitor_agent = Agent(
    name="CodeMonitor",
    role="Execution Monitor",
    goal="Monitor code execution and handle errors.",
    backstory="Expert in code monitoring and error handling.",
    self_reflect=False
)

# Define tasks
execution_task = Task(
    description="Execute Python scripts.",
    agent=executor_agent,
    name="code_execution"
)

monitoring_task = Task(
    description="Monitor execution and handle errors.",
    agent=monitor_agent,
    name="execution_monitoring"
)

# Run agents
agents = PraisonAIAgents(
    agents=[executor_agent, monitor_agent],
    tasks=[execution_task, monitoring_task],
    process="sequential"
)
agents.start()

Best Practices

Common Patterns

Python Execution Pipeline

# Execution agent
executor = Agent(
    name="Executor",
    role="Code Executor",
    tools=[
        execute_code, analyze_code, format_code,
        lint_code, disassemble_code
    ]
)

# Monitor agent
monitor = Agent(
    name="Monitor",
    role="Execution Monitor"
)

# Define tasks
execute_task = Task(
    description="Execute Python code",
    agent=executor
)

monitor_task = Task(
    description="Monitor execution",
    agent=monitor
)

# Run workflow
agents = PraisonAIAgents(
    agents=[executor, monitor],
    tasks=[execute_task, monitor_task]
)

Was this page helpful?