autogen_ext.code_executors.local#

class LocalCommandLineCodeExecutor(timeout: int = 60, work_dir: Path | str | None = None, functions: Sequence[FunctionWithRequirements[Any, A] | Callable[[...], Any] | FunctionWithRequirementsStr] = [], functions_module: str = 'functions', cleanup_temp_files: bool = True, virtual_env_context: SimpleNamespace | None = None)[源代码]#

基类:CodeExecutor, Component[LocalCommandLineCodeExecutorConfig]

一个通过本地命令行环境执行代码的代码执行器类。

危险

这将在本地机器上执行代码。如果与LLM生成的代码一起使用,应谨慎操作。

每个代码块被保存为文件并在工作目录的单独进程中执行, 为每个代码块生成并保存唯一的文件到工作目录。 代码块按照接收顺序执行。 命令行代码通过正则表达式匹配危险命令列表进行清理,以防止执行可能影响用户环境的自毁性命令。 目前仅支持Python和shell脚本语言。 对于Python代码,在代码块中使用"python"语言标识。 对于shell脚本,在代码块中使用"bash"、"shell"、"sh"、"pwsh"、"powershell"或"ps1"语言标识。

备注

在Windows上,必须将事件循环策略设置为`WindowsProactorEventLoopPolicy`以避免子进程问题。

import sys
import asyncio

if sys.platform == "win32":
    asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
参数:

timeout (int): 单个代码块执行的超时时间。默认为60。 work_dir (str): 代码执行的工作目录。如果为None,

将使用默认工作目录。默认工作目录是一个临时目录。

functions (List[Union[FunctionWithRequirements[Any, A], Callable[..., Any]]]): 代码执行器可用的函数列表。默认为空列表。 functions_module (str, 可选): 用于存储函数的模块名称。默认为"functions"。 cleanup_temp_files (bool, 可选): 是否在执行后自动清理临时文件。默认为True。 virtual_env_context (Optional[SimpleNamespace], 可选): 虚拟环境上下文。默认为None。

备注

使用当前目录(".")作为工作目录已被弃用。使用它将引发弃用警告。

示例:

如何使用`LocalCommandLineCodeExecutor`与运行autogen应用程序不同的虚拟环境: 使用`venv`模块设置虚拟环境,并将其上下文传递给`LocalCommandLineCodeExecutor`的初始化器。这样,执行器将在新环境中运行代码。

import venv
from pathlib import Path
import asyncio

from autogen_core import CancellationToken
from autogen_core.code_executor import CodeBlock
from autogen_ext.code_executors.local import LocalCommandLineCodeExecutor


async def example():
    work_dir = Path("coding")
    work_dir.mkdir(exist_ok=True)

    venv_dir = work_dir / ".venv"
    venv_builder = venv.EnvBuilder(with_pip=True)
    venv_builder.create(venv_dir)
    venv_context = venv_builder.ensure_directories(venv_dir)

    local_executor = LocalCommandLineCodeExecutor(work_dir=work_dir, virtual_env_context=venv_context)
    await local_executor.execute_code_blocks(
        code_blocks=[
            CodeBlock(language="bash", code="pip install matplotlib"),
        ],
        cancellation_token=CancellationToken(),
    )


asyncio.run(example())
FUNCTION_PROMPT_TEMPLATE: ClassVar[str] = 'You have access to the following user defined functions. They can be accessed from the module called `$module_name` by their function names.\n\nFor example, if there was a function called `foo` you could import it by writing `from $module_name import foo`\n\n$functions'#
SUPPORTED_LANGUAGES: ClassVar[List[str]] = ['bash', 'shell', 'sh', 'pwsh', 'powershell', 'ps1', 'python']#
classmethod _from_config(config: LocalCommandLineCodeExecutorConfig) Self[源代码]#

从配置对象创建组件的新实例。

参数:

config (T) -- 配置对象。

Returns:

Self -- 组件的新实例。

_to_config() LocalCommandLineCodeExecutorConfig[源代码]#

导出当前组件实例的配置,该配置可用于创建具有相同配置的新组件实例。

Returns:

T -- 组件的配置。

property cleanup_temp_files: bool#

(实验性)是否在执行后自动清理临时文件。

component_config_schema#

LocalCommandLineCodeExecutorConfig 的别名

component_provider_override: ClassVar[str | None] = 'autogen_ext.code_executors.local.LocalCommandLineCodeExecutor'#

覆盖组件的provider字符串。这应该用于防止内部模块名称成为模块名称的一部分。

async execute_code_blocks(code_blocks: List[CodeBlock], cancellation_token: CancellationToken) CommandLineCodeResult[源代码]#

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

参数:
Returns:

CommandLineCodeResult -- 代码执行的结果。

format_functions_for_prompt(prompt_template: str = FUNCTION_PROMPT_TEMPLATE) str[源代码]#

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

模板包含两个变量: - $module_name: 模块名称。 - $functions: 格式化为存根的函数,每个函数之间有两个换行。

参数:

prompt_template (str): 提示模板。默认为类默认值。

返回:

str: 格式化后的提示。

property functions: List[str]#
property functions_module: str#

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

async restart() None[源代码]#

(实验性功能)重启代码执行器。

async start() None[源代码]#

(实验性功能)启动代码执行器。

初始化本地代码执行器,应在执行任何代码块前调用。 该方法会将执行器内部状态标记为已启动。 如果未提供工作目录,该方法会为执行器创建一个临时目录。

async stop() None[源代码]#

(实验性功能)停止代码执行器。

停止本地代码执行器并清理临时工作目录(如果该目录是创建的)。 执行器的内部状态会被标记为不再启动。

property timeout: int#

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

property work_dir: Path#

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