File size: 8,209 Bytes
5374a2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 |
#!/usr/bin/env python3
"""
Code Interpreter Examples for EvoAgentX
This module provides comprehensive examples for:
- PythonInterpreterToolkit: Execute Python code in a secure environment
- DockerInterpreterToolkit: Execute code within isolated Docker containers
The examples demonstrate various use cases including:
- Basic code execution (Hello World, Math operations)
- Platform information and system details
- Script file execution
- Dynamic code generation
- Visualization attempts (with import handling)
"""
import os
import sys
from pathlib import Path
# Add the parent directory to sys.path to import from evoagentx
sys.path.append(str(Path(__file__).parent.parent))
from evoagentx.tools import (
PythonInterpreterToolkit,
DockerInterpreterToolkit
)
def run_simple_hello_world(interpreter):
"""
Run a simple Hello World example using the provided interpreter.
Args:
interpreter: An instance of a code interpreter
"""
# Define a simple Hello World code
code = """
print("Hello, World!")
print("This code is running inside a secure Python interpreter.")
"""
# Execute the code
result = interpreter.execute(code, "python")
print("\nSimple Hello World Result:")
print("-" * 50)
print(result)
print("-" * 50)
def run_math_example(interpreter):
"""
Run a math example using the provided interpreter.
Args:
interpreter: An instance of a code interpreter
"""
# Define a simple math example
code = """
print("Running math operations...")
# Using math library
import math
print(f"The value of pi is: {math.pi:.4f}")
print(f"The square root of 16 is: {math.sqrt(16)}")
print(f"The value of e is: {math.e:.4f}")
"""
# Execute the code
result = interpreter.execute(code, "python")
print("\nMath Example Result:")
print("-" * 50)
print(result)
print("-" * 50)
def run_platform_info(interpreter):
"""
Run a platform info example using the provided interpreter.
Args:
interpreter: An instance of a code interpreter
"""
# Define code that prints platform information
code = """
print("Getting platform information...")
# System information
import platform
import sys
print(f"Python version: {platform.python_version()}")
print(f"Platform: {platform.system()} {platform.release()}")
print(f"Processor: {platform.processor()}")
print(f"Implementation: {platform.python_implementation()}")
"""
# Execute the code
result = interpreter.execute(code, "python")
print("\nPlatform Info Result:")
print("-" * 50)
print(result)
print("-" * 50)
def run_script_execution(interpreter):
"""
Run a script file using the execute_script method of the interpreter.
Args:
interpreter: An instance of a code interpreter
"""
# Get the path to the hello_world.py script
script_path = os.path.join(os.getcwd(), "examples", "tools", "hello_world.py")
# Make sure the file exists
if not os.path.exists(script_path):
print(f"Error: Script file not found at {script_path}")
return
print(f"Executing script file: {script_path}")
# Execute the script
result = interpreter.execute_script(script_path, "python")
print("\nScript Execution Result:")
print("-" * 50)
print(result)
print("-" * 50)
def run_dynamic_code_generation(interpreter):
"""
Run an example that demonstrates dynamic code generation and execution.
Args:
interpreter: An instance of a code interpreter
"""
# Define code that generates and executes more code
code = """
print("Generating and executing code dynamically...")
# Generate a function definition
function_code = '''
def calculate_factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * calculate_factorial(n-1)
'''
# Execute the generated code to define the function
exec(function_code)
# Now use the dynamically defined function
for i in range(1, 6):
print(f"Factorial of {i} is {calculate_factorial(i)}")
"""
# Execute the code
result = interpreter.execute(code, "python")
print("\nDynamic Code Generation Result:")
print("-" * 50)
print(result)
print("-" * 50)
def run_visualization_example(interpreter):
"""
Run an example that would generate a visualization if matplotlib was allowed.
This demonstrates handling imports that might not be allowed.
Args:
interpreter: An instance of a code interpreter
"""
# Define code that attempts to use matplotlib
code = """
print("Attempting to create a simple visualization...")
try:
import matplotlib.pyplot as plt
import numpy as np
# Generate some data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create a plot
plt.figure(figsize=(8, 4))
plt.plot(x, y)
plt.title("Sine Wave")
plt.xlabel("x")
plt.ylabel("sin(x)")
plt.grid(True)
# Save the plot (would work if matplotlib was available)
plt.savefig("examples/output/sine_wave.png")
plt.close()
print("Visualization created and saved as 'examples/output/sine_wave.png'")
except ImportError as e:
print(f"Import error: {e}")
print("Note: This example requires matplotlib to be in the allowed_imports.")
"""
# Execute the code
result = interpreter.execute(code, "python")
print("\nVisualization Example Result:")
print("-" * 50)
print(result)
print("-" * 50)
def run_python_interpreter_examples():
"""Run all examples using the Python InterpreterToolkit"""
print("\n===== PYTHON INTERPRETER EXAMPLES =====\n")
# Initialize the Python interpreter toolkit with the current directory as project path
# and allow common standard library imports
interpreter_toolkit = PythonInterpreterToolkit(
project_path=os.getcwd(),
directory_names=["examples", "evoagentx"],
allowed_imports={"os", "sys", "time", "datetime", "math", "random", "platform", "matplotlib.pyplot", "numpy"}
)
# Get the underlying interpreter instance for the examples
interpreter = interpreter_toolkit.python_interpreter
# Run the examples
run_simple_hello_world(interpreter)
run_math_example(interpreter)
run_platform_info(interpreter)
run_script_execution(interpreter)
run_dynamic_code_generation(interpreter)
run_visualization_example(interpreter)
def run_docker_interpreter_examples():
"""Run all examples using the Docker InterpreterToolkit"""
print("\n===== DOCKER INTERPRETER EXAMPLES =====\n")
print("Running Docker interpreter examples...")
try:
# Initialize the Docker interpreter toolkit with a standard Python image
interpreter_toolkit = DockerInterpreterToolkit(
image_tag="python:3.9-slim", # Using official Python image
print_stdout=True,
print_stderr=True,
container_directory="/app" # Better working directory for containerized apps
)
# Get the underlying interpreter instance for the examples
interpreter = interpreter_toolkit.docker_interpreter
# Run the examples
run_simple_hello_world(interpreter)
run_math_example(interpreter)
run_platform_info(interpreter)
run_script_execution(interpreter)
run_dynamic_code_generation(interpreter)
# run_visualization_example(interpreter) # Commented out for Docker examples
except Exception as e:
print(f"Error running Docker interpreter examples: {str(e)}")
print("Make sure Docker is installed and running on your system.")
print("You may need to pull the python:3.9-slim image first using: docker pull python:3.9-slim")
def main():
"""Main function to run interpreter examples"""
print("===== CODE INTERPRETER EXAMPLES =====")
# Run Python interpreter examples
run_python_interpreter_examples()
# Run Docker interpreter examples
run_docker_interpreter_examples()
print("\n===== ALL INTERPRETER EXAMPLES COMPLETED =====")
if __name__ == "__main__":
main()
|