本节导读:深入理解AutoGen代码执行器的核心机制,掌握不同执行器的配置方法和适用场景,构建安全高效的代码运行环境
AutoGen的代码执行系统是整个框架的核心组成部分,它提供了安全、可控的代码运行环境。执行器负责将智能体生成的代码转换为可执行的程序,并捕获执行结果。
本地命令行执行器是最基础的执行器类型,直接在宿主机上执行代码,适用于开发和测试环境。
from autogen.code_executor import LocalCommandLineCodeExecutor from autogen_agentchat.agents import AssistantAgent from autogen_ext.models.openai import OpenAIChatCompletionClient # 基础本地执行器配置 local_executor = LocalCommandLineCodeExecutor( timeout=300, # 总体超时时间(秒) work_dir="/tmp/autogen_work", # 工作目录 execution_timeout=30, # 单次执行超时时间 max_output=10000 # 最大输出字符数 ) # 创建使用本地执行器的智能体 coding_assistant = AssistantAgent( name="python_coder", model_client=OpenAIChatCompletionClient(model="gpt-4o"), code_execution_config={"executor": local_executor} ) # 使用执行器 async def basic_local_execution(): code = "print('Hello, AutoGen!'); import math; print(f'Sqrt(16) = {math.sqrt(16)}')" result = local_executor.execute_code(code, "test.py") return result
from autogen.code_executor import LocalCommandLineCodeExecutor import os import tempfile import shutil from typing import Optional, Dict, Any import subprocess import sys class AdvancedLocalExecutor(LocalCommandLineCodeExecutor): """高级本地执行器,支持更多配置选项""" def __init__( self, timeout: int = 300, work_dir: Optional[str] = None, execution_timeout: int = 30, max_output: int = 10000, environment: Optional[Dict[str, str]] = None, cwd: Optional[str] = None, use_temp_dir: bool = False, clean_on_exit: bool = True, **kwargs ): # 处理工作目录 if use_temp_dir: work_dir = tempfile.mkdtemp(prefix="autogen_") elif work_dir is None: work_dir = "/tmp/autogen_work" super().__init__( timeout=timeout, work_dir=work_dir, execution_timeout=execution_timeout, max_output=max_output, **kwargs ) self.environment = environment or {} self.cwd = cwd or os.getcwd() self.use_temp_dir = use_temp_dir self.clean_on_exit = clean_on_exit # 创建工作目录 os.makedirs(work_dir, exist_ok=True) def setup_environment(self) -> Dict[str, str]: """设置执行环境变量""" env = os.environ.copy() env.update(self.environment) env["PYTHONPATH"] = self.work_dir return env def execute_with_env(self, code: str, filename: str) -> Dict[str, Any]: """带环境变量支持的执行方法""" full_path = os.path.join(self.work_dir, filename) # 写入代码文件 with open(full_path, 'w', encoding='utf-8') as f: f.write(code) # 设置环境变量 env = self.setup_environment() try: # 执行代码 result = subprocess.run( [sys.executable, filename], cwd=self.work_dir, env=env, timeout=self.execution_timeout, capture_output=True, text=True ) return { "success": True, "output": result.stdout, "error": result.stderr, "return_code": result.returncode } except subprocess.TimeoutExpired: return { "success": False, "error": "执行超时", "output": "", "return_code": -1 } except Exception as e: return { "success": False, "error": str(e), "output": "", "return_code": -1 } finally: # 清理临时文件 if self.clean_on_exit and self.use_temp_dir: shutil.rmtree(self.work_dir, ignore_errors=True)
优势:
劣势:
Docker容器执行器提供更好的隔离性和安全性,是生产环境推荐的方式。
from autogen.code_executor import DockerCommandLineCodeExecutor # 基础Docker执行器配置 docker_executor = DockerCommandLineCodeExecutor( image="python:3.10-slim", # 基础镜像 timeout=600, # 10分钟超时 work_dir="/workspace", # 容器内工作目录 container_name="autogen-executor-{uuid}", # 容器名称模板 auto_remove=True, # 自动删除容器 network_mode="bridge", # 网络模式 port_bindings={8080: 8080}, # 端口映射 volume_mounts={ "/host/data": "/container/data", # 数据卷挂载 "/host/code": "/workspace/code" # 代码目录挂载 }, environment_vars={ "PYTHONPATH": "/workspace", "DATA_DIR": "/workspace/data", "AUTOKEN_VERSION": "1.0.0" }, resource_limits={ "memory": "2g", "cpu": "1.0", "pids": 100 } ) # 使用Docker执行器 async def docker_execution_example(): code = """ import pandas as pd import numpy as np import matplotlib.pyplot as plt # 生成数据分析代码 np.random.seed(42) data = pd.DataFrame({ 'timestamp': pd.date_range('2024-01-01', periods=100, freq='D'), 'value': np.random.randn(100).cumsum(), 'category': np.random.choice(['A', 'B', 'C'], 100) }) # 基础统计 print(data.head()) print(f"数据行数: {len(data)}") print(f"分类统计:\n{data['category'].value_counts()}") # 生成趋势图 plt.figure(figsize=(12, 6)) plt.plot(data['timestamp'], data['value'], label='趋势线') plt.title('时间序列数据分析') plt.xlabel('时间') plt.ylabel('数值') plt.legend() plt.grid(True) plt.tight_layout() plt.savefig('/workspace/trend_analysis.png') plt.close() print("分析完成,图表已保存") """ result = docker_executor.execute_code(code, "data_analysis.py") return result
优势:
劣势:
from autogen.code_executor import DockerCommandLineCodeExecutor, LocalCommandLineCodeExecutor from enum import Enum class ExecutionScenario(Enum): """执行场景枚举""" DEVELOPMENT = "development" # 开发环境 PRODUCTION = "production" # 生产环境 TESTING = "testing" # 测试环境 SANDBOX = "sandbox" # 沙盒环境 class ExecutorTemplateFactory: """执行器配置模板工厂""" @staticmethod def get_template(scenario: ExecutionScenario) -> Dict[str, Any]: """根据场景获取配置模板""" templates = { ExecutionScenario.DEVELOPMENT: { "type": "local", "config": { "timeout": 120, "work_dir": "/tmp/dev", "execution_timeout": 30, "auto_remove": False, "debug_mode": True }, "description": "开发环境:快速迭代,支持调试" }, ExecutionScenario.PRODUCTION: { "type": "docker", "config": { "image": "python:3.10-slim", "timeout": 1800, "work_dir": "/workspace", "auto_remove": True, "resource_limits": {"memory": "4g", "cpu": "2.0"}, "security_opts": ["no-new-privileges"], "read_only": True }, "description": "生产环境:安全隔离,资源控制" }, ExecutionScenario.TESTING: { "type": "docker", "config": { "image": "python:3.10-slim", "timeout": 300, "work_dir": "/workspace/test", "auto_remove": True }, "description": "测试环境:测试专用" }, ExecutionScenario.SANDBOX: { "type": "docker", "config": { "image": "python:3.10-slim", "timeout": 60, "work_dir": "/workspace/sandbox", "auto_remove": True, "blocked_imports": ["os", "subprocess", "sys"], "read_only": True }, "description": "沙盒环境:严格限制,安全隔离" } } return templates.get(scenario, templates[ExecutionScenario.DEVELOPMENT]) # 使用模板工厂 def create_executors_by_scenario() -> Dict[str, any]: """根据场景创建执行器""" executors = {} for scenario in ExecutionScenario: template = ExecutorTemplateFactory.get_template(scenario) if template["type"] == "local": executor = LocalCommandLineCodeExecutor(**template["config"]) elif template["type"] == "docker": executor = DockerCommandLineCodeExecutor(**template["config"]) else: raise ValueError(f"不支持的执行器类型: {template['type']}") executors[scenario.value] = executor return executors
import asyncio import pandas as pd import matplotlib.pyplot as plt from autogen import AssistantAgent, UserProxyAgent from autogen.code_executor import DockerCommandLineCodeExecutor # 创建数据分析执行器 data_analysis_executor = DockerCommandLineCodeExecutor( image="python:3.10-slim", timeout=900, # 15分钟 work_dir="/workspace/data_analysis", auto_remove=True, environment_vars={ "PYTHONPATH": "/workspace", "MPLCONFIGDIR": "/workspace/matplotlib_config" } ) # 创建数据分析师智能体 data_analyst = AssistantAgent( name="data_analyst", model_client=OpenAIChatCompletionClient(model="gpt-4o"), code_execution_config={"executor": data_analysis_executor} ) # 创建用户代理 user_proxy = UserProxyAgent( name="user_proxy", human_input_mode="NEVER", code_execution_config=False ) # 定义数据分析任务 async def perform_data_analysis(): task = """ 请帮我分析以下数据: 1. 生成包含日期、销售额、产品类别的模拟数据(100行) 2. 计算各类别的总销售额和平均值 3. 创建销售额趋势图 4. 生成简要分析报告 """ # 开始对话 await user_proxy.initiate_chat( data_analyst, message=task ) return "数据分析任务完成" # 执行任务 asyncio.run(perform_data_analysis())
A:根据具体需求选择:
A:合理设置timeout,使用异步监控,实现优雅的中断机制。对于计算密集型任务,考虑分块执行。
A:使用Docker容器隔离,限制模块导入,设置资源限制,实现代码审查机制,使用只读文件系统等。
A:为每个用户分配独立的执行环境,使用命名容器,隔离网络和存储,实现用户配额管理。
本节详细介绍了AutoGen代码执行器的核心机制,包括本地执行器、Docker执行器的配置方法。通过实际案例,我们学习了如何根据不同场景选择合适的执行器配置,以及如何进行性能监控和安全控制。
关键要点:
下一节将深入探讨Docker集成的具体实现,包括容器环境配置、网络管理和安全策略。
关键词:代码执行, 执行器配置, Docker容器, 安全控制, 性能监控, 智能管理
难度:进阶
预计阅读:30分钟