autogen_ext.code_executors.jupyter#
- class JupyterCodeExecutor(kernel_name: str = 'python3', timeout: int = 60, output_dir: str | Path | None = None)[source]#
Bases:
CodeExecutor
,Component
[JupyterCodeExecutorConfig
]一个代码执行器类,它使用 [nbclient](jupyter/nbclient) 有状态地执行代码。
危险
这将在本地计算机上执行代码。如果与 LLM 生成的代码一起使用,应谨慎。
直接使用的例子
import asyncio from autogen_core import CancellationToken from autogen_core.code_executor import CodeBlock from autogen_ext.code_executors.jupyter import JupyterCodeExecutor async def main() -> None: async with JupyterCodeExecutor() as executor: cancel_token = CancellationToken() code_blocks = [CodeBlock(code="print('hello world!')", language="python")] code_result = await executor.execute_code_blocks(code_blocks, cancel_token) print(code_result) asyncio.run(main())
与
PythonCodeExecutionTool
一起使用的例子import asyncio from autogen_agentchat.agents import AssistantAgent from autogen_ext.code_executors.jupyter import JupyterCodeExecutor from autogen_ext.models.openai import OpenAIChatCompletionClient from autogen_ext.tools.code_execution import PythonCodeExecutionTool async def main() -> None: async with JupyterCodeExecutor() as executor: tool = PythonCodeExecutionTool(executor) model_client = OpenAIChatCompletionClient(model="gpt-4o") agent = AssistantAgent("assistant", model_client=model_client, tools=[tool]) result = await agent.run(task="What is the 10th Fibonacci number? Use Python to calculate it.") print(result) asyncio.run(main())
在
CodeExecutorAgent
中使用的例子import asyncio from autogen_agentchat.agents import CodeExecutorAgent from autogen_agentchat.messages import TextMessage from autogen_ext.code_executors.jupyter import JupyterCodeExecutor from autogen_core import CancellationToken async def main() -> None: async with JupyterCodeExecutor() as executor: code_executor_agent = CodeExecutorAgent("code_executor", code_executor=executor) task = TextMessage( content='''Here is some code ```python print('Hello world') ``` ''', source="user", ) response = await code_executor_agent.on_messages([task], CancellationToken()) print(response.chat_message) asyncio.run(main())
- 参数:
注意
不建议使用当前目录(“.”)作为输出目录。 使用它会引发弃用警告。
- component_config_schema#
JupyterCodeExecutorConfig
的别名
- component_provider_override: ClassVar[str | None] = 'autogen_ext.code_executors.jupyter.JupyterCodeExecutor'#
覆盖组件的 provider 字符串。 这应该用于防止内部模块名称成为模块名称的一部分。
- async execute_code_blocks(code_blocks: list[CodeBlock], cancellation_token: CancellationToken) JupyterCodeResult [source]#
执行代码块并返回结果。