coding.local_commandline_code_executor
LocalCommandLineCodeExecutor
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。
用于提示的格式函数
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
(实验性)函数的模块名称。
功能
@property
def functions() -> List[Union[FunctionWithRequirements[Any, A], Callable[
..., Any], FunctionWithRequirementsStr]]
(实验性)可供代码执行器使用的函数。
超时
@property
def timeout() -> int
(实验性的)代码执行的超时时间。
工作目录
@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或可能选择不使用它。因此,拥有一个基础级别的保护有助于减轻那些出于选择或必要性在沙盒环境之外运行代码的用户的风险。
执行代码块
def execute_code_blocks(code_blocks: List[CodeBlock]) -> CommandLineCodeResult
(实验性)执行代码块并返回结果。
参数:
code_blocks
List[CodeBlock] - 要执行的代码块。
返回:
CommandLineCodeResult
- 代码执行的结果。
重启
def restart() -> None
(实验性)重启代码执行器。
本地命令行代码执行器
class LocalCommandlineCodeExecutor(metaclass=_DeprecatedClassMeta)
LocalCommandlineCodeExecutor 重命名为 LocalCommandLineCodeExecutor
命令行代码结果
class CommandlineCodeResult(metaclass=_DeprecatedClassMeta)
CommandlineCodeResult 更名为 CommandLineCodeResult