Skip to main content

coding.local_commandline_code_executor

本地命令行代码执行器

class LocalCommandLineCodeExecutor(CodeExecutor)

__init__

def __init__(timeout: int = 60,
virtual_env_context: Optional[SimpleNamespace] = None,
work_dir: Union[Path, str] = Path("."),
functions: List[Union[FunctionWithRequirements[Any, A],
Callable[..., Any],
FunctionWithRequirementsStr]] = [],
functions_module: str = "functions",
execution_policies: Optional[Dict[str, bool]] = None)

(实验性)一个代码执行器类,用于在本地命令行环境中执行或保存 LLM 生成的代码。

这将在本地机器上执行或保存 LLM 生成的代码。

每个代码块都保存为一个文件在工作目录中。根据执行策略的不同,代码可能会在单独的进程中执行。 代码块按接收到的顺序执行或保存。 命令行代码会根据一份危险命令列表进行清理,以防止执行自毁性命令,可能会影响用户的环境。支持的语言包括 Python、shell 脚本(bash、shell、sh)、PowerShell(pwsh、powershell、ps1)、HTML、CSS 和 JavaScript。 执行策略确定是否仅执行或保存每种语言的代码块。

使用 Python 虚拟环境进行执行

可以使用 Python 虚拟环境来执行代码和安装依赖项。这样做的好处是不会污染基础环境。

from autogen.code_utils import create_virtual_env
from autogen.coding import LocalCommandLineCodeExecutor

venv_dir = ".venv"
venv_context = create_virtual_env(venv_dir)

executor = LocalCommandLineCodeExecutor(virtual_env_context=venv_context)

参数

  • timeout int - 代码执行的超时时间,默认为 60 秒。
  • virtual_env_context Optional[SimpleNamespace] - 要使用的虚拟环境上下文。
  • work_dir Union[Path, str] - 代码执行的工作目录,默认为当前目录。
  • functions List[Union[FunctionWithRequirements[Any, A], Callable[..., Any], FunctionWithRequirementsStr]] - 可供执行器使用的可调用函数列表。
  • functions_module str - 函数可访问的模块名称。
  • execution_policies Optional[Dict[str, bool]] - 将语言映射到执行策略的字典(True 表示执行,False 表示仅保存)。默认为类的 DEFAULT_EXECUTION_POLICY。

format_functions_for_prompt

def format_functions_for_prompt(
prompt_template: str = FUNCTION_PROMPT_TEMPLATE) -> str

(实验性)为提示符格式化函数。

模板包括两个变量:

  • $module_name:模块名称。
  • $functions: 以两个换行符分隔的存根形式的函数。

参数

  • prompt_template str - 提示模板。默认为类的默认值。

返回值

  • str - 格式化后的提示。

functions_module

@property
def functions_module() -> str

(实验性)函数的模块名称。

functions

@property
def functions() -> List[Union[FunctionWithRequirements[Any, A], Callable[
..., Any], FunctionWithRequirementsStr]]

(实验性)可供代码执行器使用的函数。

timeout

@property
def timeout() -> int

(实验性)代码执行的超时时间。

work_dir

@property
def work_dir() -> Path

(实验性)代码执行的工作目录。

code_extractor

@property
def code_extractor() -> CodeExtractor

(实验性)导出一个可供代理使用的代码提取器。

sanitize_command

@staticmethod
def sanitize_command(lang: str, code: str) -> None

清理代码块以防止危险命令。 这种方法承认,虽然 Docker 或类似的容器化/沙盒技术提供了强大的安全层,但并非所有用户都安装了 Docker 或选择使用它。 因此,具有基本级别的保护有助于减轻那些出于选择或必要性而在非沙盒环境中运行代码的用户的风险。

execute_code_blocks

def execute_code_blocks(code_blocks: List[CodeBlock]) -> CommandLineCodeResult

(实验性)执行代码块并返回结果。

参数

  • code_blocks List[CodeBlock] - 要执行的代码块。

返回值

  • CommandLineCodeResult - 代码执行的结果。

restart

def restart() -> None

(实验性)重新启动代码执行器。

LocalCommandlineCodeExecutor

class LocalCommandlineCodeExecutor(metaclass=_DeprecatedClassMeta)

LocalCommandlineCodeExecutor 重命名为 LocalCommandLineCodeExecutor

CommandlineCodeResult

class CommandlineCodeResult(metaclass=_DeprecatedClassMeta)

CommandlineCodeResult 重命名为 CommandLineCodeResult