autogen_core.code_executor#
- class CodeExecutor[源代码]#
基类:
ABC,ComponentBase[BaseModel]执行代码块并返回结果。
这是代码执行器的抽象基类。它定义了执行代码块并返回结果的接口。应该提供此类的具体实现,以在特定环境中执行代码块。例如,
DockerCommandLineCodeExecutor在 Docker 容器中的命令行环境中执行代码块。建议将子类用作上下文管理器,以确保资源得到正确清理。为此,请实现
start()和stop()方法,这些方法将在进入和退出上下文管理器时调用。- component_type: ClassVar[ComponentType] = 'code_executor'#
组件的逻辑类型。
- abstract async execute_code_blocks(code_blocks: List[CodeBlock], cancellation_token: CancellationToken) CodeResult[源代码]#
执行代码块并返回结果。
此方法应由代码执行器实现。
- 参数:
code_blocks (List[CodeBlock]) – 要执行的代码块。
- 返回:
CodeResult – 代码执行的结果。
- 抛出:
ValueError – 用户输入中的错误
TimeoutError – 代码执行超时
CancelledError – 执行期间CancellationToken被撤销
- class ImportFromModule(module: 'str', imports: 'Union[Tuple[Union[str, Alias], ...], List[Union[str, Alias]]]')[源代码]#
基类:
object
- class FunctionWithRequirements(func: 'Callable[P, T]', python_packages: 'Sequence[str]' = <factory>, global_imports: 'Sequence[Import]' = <factory>)[源代码]#
基类:
Generic[T,P]- global_imports: Sequence[str | ImportFromModule | Alias]#
- classmethod from_callable(func: Callable[[P], T], python_packages: Sequence[str] = [], global_imports: Sequence[str | ImportFromModule | Alias] = []) FunctionWithRequirements[T, P][源代码]#
- static from_str(func: str, python_packages: Sequence[str] = [], global_imports: Sequence[str | ImportFromModule | Alias] = []) FunctionWithRequirementsStr[源代码]#
- class FunctionWithRequirementsStr(func: 'str', python_packages: 'Sequence[str]' = [], global_imports: 'Sequence[Import]' = [])[源代码]#
基类:
object- global_imports: Sequence[str | ImportFromModule | Alias]#
- with_requirements(python_packages: Sequence[str] = [], global_imports: Sequence[str | ImportFromModule | Alias] = []) Callable[[Callable[[P], T]], FunctionWithRequirements[T, P]][源代码]#
使用代码执行环境的包和导入要求装饰函数。
此装饰器通过将函数包装在一个 FunctionWithRequirements 对象中,该对象跟踪其依赖项,使函数可用于动态执行的代码块中的引用。当装饰后的函数传递给代码执行器时,它可以在执行的代码中按名称导入,所有依赖项都会自动处理。
- 参数:
python_packages (Sequence[str], optional) – 函数所需的 Python 包。可以包含版本规范(例如,[“pandas>=1.0.0”])。默认为 []。
global_imports (Sequence[Import], optional) – 函数所需的导入语句。可以是字符串(“numpy”)、ImportFromModule 对象或 Alias 对象。默认为 []。
- 返回:
Callable[[Callable[P, T]], FunctionWithRequirements[T, P]] – 一个装饰器,它包装目标函数,保留其功能同时注册其依赖项。
示例
import tempfile import asyncio from autogen_core import CancellationToken from autogen_core.code_executor import with_requirements, CodeBlock from autogen_ext.code_executors.local import LocalCommandLineCodeExecutor import pandas @with_requirements(python_packages=["pandas"], global_imports=["pandas"]) def load_data() -> pandas.DataFrame: """Load some sample data. Returns: pandas.DataFrame: A DataFrame with sample data """ data = { "name": ["John", "Anna", "Peter", "Linda"], "location": ["New York", "Paris", "Berlin", "London"], "age": [24, 13, 53, 33], } return pandas.DataFrame(data) async def run_example(): # The decorated function can be used in executed code with tempfile.TemporaryDirectory() as temp_dir: executor = LocalCommandLineCodeExecutor(work_dir=temp_dir, functions=[load_data]) code = f"""from {executor.functions_module} import load_data # Use the imported function data = load_data() print(data['name'][0])""" result = await executor.execute_code_blocks( code_blocks=[CodeBlock(language="python", code=code)], cancellation_token=CancellationToken(), ) print(result.output) # Output: John # Run the async example asyncio.run(run_example())