autogen_core.code_executor#
- class CodeExecutor[源代码]#
基础:
ABC
,ComponentBase
[BaseModel
]执行代码块并返回结果。
- component_type: ClassVar[ComponentType] = 'code_executor'#
组件的逻辑类型。
- abstract async execute_code_blocks(code_blocks: 列表[CodeBlock], cancellation_token: CancellationToken) CodeResult [源代码]#
执行代码块并返回结果。
该方法应由代码执行器实现。
- Parameters:
code_blocks (列表[CodeBlock]) – 要执行的代码块。
- Returns:
CodeResult – 代码执行的结果。
- Raises:
ValueError – 用户输入中的错误
TimeoutError – 代码执行超时
CancelledError – 在执行期间触发的CancellationToken
- class FunctionWithRequirements(func: 'Callable[P, T]', python_packages: 'Sequence[str]' = <factory>, global_imports: 'Sequence[Import]' = <factory>)[源代码]#
基础:
Generic
[T
,P
]- classmethod from_callable(func: Callable[[P], T], python_packages: Sequence[str] = [], global_imports: Sequence[str | ImportFromModule | 别名] = []) FunctionWithRequirements[T, P] [源代码]#
- static from_str(func: str, python_packages: Sequence[str] = [], global_imports: Sequence[str | ImportFromModule | 别名] = []) FunctionWithRequirementsStr [源代码]#
- global_imports: Sequence[str | ImportFromModule | 别名]#
- class FunctionWithRequirementsStr(func: 'str', python_packages: 'Sequence[str]' = [], global_imports: 'Sequence[Import]' = [])[源代码]#
基础:
object
- global_imports: Sequence[str | ImportFromModule | 别名]#
- class ImportFromModule(module: 'str', imports: 'Union[Tuple[Union[str, Alias], ...], List[Union[str, Alias]]]')[源代码]#
基础:
object
- with_requirements(python_packages: Sequence[str] = [], global_imports: Sequence[str | ImportFromModule | 别名] = []) Callable[[Callable[[P], T]], FunctionWithRequirements[T, P]] [源代码]#
为代码执行环境装饰一个函数,包含包和导入需求。
该装饰器通过将函数包装在跟踪其依赖项的FunctionWithRequirements对象中,使其可在动态执行的代码块中被引用。当装饰后的函数传递给代码执行器时,它可以按名称在执行代码中导入,并自动处理所有依赖项。
- Parameters:
python_packages (Sequence[str], optional) – 函数所需的Python包。 可以包括版本规格(例如,[“pandas>=1.0.0”])。默认为[]。
global_imports (Sequence[Import], optional) – 函数所需的导入语句。 可以是字符串(“numpy”)、ImportFromModule对象或Alias对象。默认为[]。
- Returns:
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())