Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Pass checks
  • Loading branch information
zrquan committed Aug 1, 2025
commit 721ce7c189aa42db196fe3c096755b23033e4525
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"source": [
"## Built-in Tools\n",
"\n",
"One of the built-in tools is the {py:class}`~autogen_ext.tools.code_execution.PythonCodeExecutionTool`,\n",
"One of the built-in tools is the {py:class}`~autogen_ext.tools.code_execution.CodeExecutionTool`,\n",
"which allows agents to execute Python code snippets.\n",
"\n",
"Here is how you create the tool and use it."
Expand All @@ -45,17 +45,17 @@
"source": [
"from autogen_core import CancellationToken\n",
"from autogen_ext.code_executors.docker import DockerCommandLineCodeExecutor\n",
"from autogen_ext.tools.code_execution import PythonCodeExecutionTool\n",
"from autogen_ext.tools.code_execution import CodeExecutionTool\n",
"\n",
"# Create the tool.\n",
"code_executor = DockerCommandLineCodeExecutor()\n",
"await code_executor.start()\n",
"code_execution_tool = PythonCodeExecutionTool(code_executor)\n",
"code_execution_tool = CodeExecutionTool(code_executor)\n",
"cancellation_token = CancellationToken()\n",
"\n",
"# Use the tool directly without an agent.\n",
"code = \"print('Hello, world!')\"\n",
"result = await code_execution_tool.run_json({\"code\": code}, cancellation_token)\n",
"result = await code_execution_tool.run_json({\"language\":\"python\", \"code\": code}, cancellation_token)\n",
"print(code_execution_tool.return_value_as_string(result))"
]
},
Expand All @@ -66,7 +66,7 @@
"The {py:class}`~autogen_ext.code_executors.docker.DockerCommandLineCodeExecutor`\n",
"class is a built-in code executor that runs Python code snippets in a subprocess\n",
"in the command line environment of a docker container.\n",
"The {py:class}`~autogen_ext.tools.code_execution.PythonCodeExecutionTool` class wraps the code executor\n",
"The {py:class}`~autogen_ext.tools.code_execution.CodeExecutionTool` class wraps the code executor\n",
"and provides a simple interface to execute Python code snippets.\n",
"\n",
"Examples of other built-in tools\n",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
"from autogen_core.tools import ToolSchema\n",
"from autogen_ext.code_executors.docker import DockerCommandLineCodeExecutor\n",
"from autogen_ext.models.openai import OpenAIChatCompletionClient\n",
"from autogen_ext.tools.code_execution import PythonCodeExecutionTool"
"from autogen_ext.tools.code_execution import CodeExecutionTool"
]
},
{
Expand Down Expand Up @@ -169,7 +169,7 @@
"First, we create a Docker-based command-line code executor\n",
"using {py:class}`~autogen_ext.code_executors.docker.DockerCommandLineCodeExecutor`,\n",
"and then use it to instantiate a built-in Python code execution tool\n",
"{py:class}`~autogen_core.tools.PythonCodeExecutionTool`\n",
"{py:class}`~autogen_core.tools.CodeExecutionTool`\n",
"that runs code in a Docker container."
]
},
Expand All @@ -182,8 +182,8 @@
"# Create the docker executor for the Python code execution tool.\n",
"docker_executor = DockerCommandLineCodeExecutor()\n",
"\n",
"# Create the Python code execution tool.\n",
"python_tool = PythonCodeExecutionTool(executor=docker_executor)"
"# Create the code execution tool.\n",
"execution_tool = CodeExecutionTool(executor=docker_executor)"
]
},
{
Expand Down Expand Up @@ -216,7 +216,7 @@
" \"tool_executor_agent\",\n",
" lambda: ToolAgent(\n",
" description=\"Tool Executor Agent\",\n",
" tools=[python_tool],\n",
" tools=[execution_tool],\n",
" ),\n",
")\n",
"model_client = OpenAIChatCompletionClient(model=\"gpt-4o-mini\")\n",
Expand All @@ -227,7 +227,7 @@
" description=\"Tool Use Agent\",\n",
" system_messages=[SystemMessage(content=\"You are a helpful AI Assistant. Use your tools to solve problems.\")],\n",
" model_client=model_client,\n",
" tool_schema=[python_tool.schema],\n",
" tool_schema=[execution_tool.schema],\n",
" tool_agent_type=tool_agent_type,\n",
" ),\n",
")"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,7 @@ def _add_builtin_tool(self, tool_name: str) -> None:
f"Tool 'local_shell' is only supported with model 'codex-mini-latest', "
f"but current model is '{self._model}'. "
f"This tool is available exclusively through the Responses API and has severe limitations. "
f"Consider using autogen_ext.tools.code_execution.PythonCodeExecutionTool with "
f"Consider using autogen_ext.tools.code_execution.CodeExecutionTool with "
f"autogen_ext.code_executors.local.LocalCommandLineCodeExecutor for shell execution instead."
)
self._tools.append({"type": "local_shell"})
Expand Down Expand Up @@ -580,7 +580,7 @@ def _add_configured_tool(self, tool_config: BuiltinToolConfig) -> None:
f"Tool 'local_shell' is only supported with model 'codex-mini-latest', "
f"but current model is '{self._model}'. "
f"This tool is available exclusively through the Responses API and has severe limitations. "
f"Consider using autogen_ext.tools.code_execution.PythonCodeExecutionTool with "
f"Consider using autogen_ext.tools.code_execution.CodeExecutionTool with "
f"autogen_ext.code_executors.local.LocalCommandLineCodeExecutor for shell execution instead."
)
tool_def = {"type": "local_shell"}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,21 +97,21 @@ async def main() -> None:

asyncio.run(main())

Example of using it with :class:`~autogen_ext.tools.code_execution.PythonCodeExecutionTool`:
Example of using it with :class:`~autogen_ext.tools.code_execution.CodeExecutionTool`:

.. code-block:: python

import asyncio
from autogen_agentchat.agents import AssistantAgent
from autogen_ext.code_executors.docker_jupyter import DockerJupyterCodeExecutor, DockerJupyterServer
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_ext.tools.code_execution import PythonCodeExecutionTool
from autogen_ext.tools.code_execution import CodeExecutionTool


async def main() -> None:
async with DockerJupyterServer() as jupyter_server:
async with DockerJupyterCodeExecutor(jupyter_server=jupyter_server) as executor:
tool = PythonCodeExecutionTool(executor)
tool = CodeExecutionTool(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.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,20 +72,20 @@ async def main() -> None:

asyncio.run(main())

Example of using it with :class:`~autogen_ext.tools.code_execution.PythonCodeExecutionTool`:
Example of using it with :class:`~autogen_ext.tools.code_execution.CodeExecutionTool`:

.. code-block:: python

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
from autogen_ext.tools.code_execution import CodeExecutionTool


async def main() -> None:
async with JupyterCodeExecutor() as executor:
tool = PythonCodeExecutionTool(executor)
tool = CodeExecutionTool(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.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ class CodeExecutionToolConfig(BaseModel):
description: str = "Execute code blocks."


class CodeExecutionTool(
BaseTool[CodeExecutionInput, CodeExecutionResult], Component[CodeExecutionToolConfig]
):
class CodeExecutionTool(BaseTool[CodeExecutionInput, CodeExecutionResult], Component[CodeExecutionToolConfig]):
"""A tool that executes code in a code executor and returns output.

Example executors:
Expand Down
22 changes: 16 additions & 6 deletions python/packages/autogen-ext/tests/tools/test_code_executor_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ async def test_code_execution_tool(caplog: pytest.LogCaptureFixture) -> None:
with caplog.at_level(logging.INFO):
# Test simple code execution
code = "print('hello world!')"
result = await tool.run_json(args={"code": code, "language": "python"}, cancellation_token=CancellationToken())
result = await tool.run_json(
args={"code": code, "language": "python"}, cancellation_token=CancellationToken()
)
# Check log output
assert "hello world!" in caplog.text

Expand All @@ -30,32 +32,40 @@ async def test_code_execution_tool(caplog: pytest.LogCaptureFixture) -> None:
# Test code with computation
code = """a = 100 + 200 \nprint(f'Result: {a}')
"""
result = await tool.run(args=CodeExecutionInput(language="python", code=code), cancellation_token=CancellationToken())
result = await tool.run(
args=CodeExecutionInput(language="python", code=code), cancellation_token=CancellationToken()
)

# Verify computation result
assert result.success is True
assert "Result: 300" in result.output

# Test error handling
code = "print(undefined_variable)"
result = await tool.run(args=CodeExecutionInput(language="python", code=code), cancellation_token=CancellationToken())
result = await tool.run(
args=CodeExecutionInput(language="python", code=code), cancellation_token=CancellationToken()
)

# Verify error handling
assert result.success is False
assert "NameError" in result.output

# Test shell command execution
code = "echo 'hello world!'"
result = await tool.run(args=CodeExecutionInput(language="sh", code=code), cancellation_token=CancellationToken())
result = await tool.run(
args=CodeExecutionInput(language="sh", code=code), cancellation_token=CancellationToken()
)

assert result.success is True
assert "hello world!" in result.output

code = "fake_command"
result = await tool.run(args=CodeExecutionInput(language="sh", code=code), cancellation_token=CancellationToken())
result = await tool.run(
args=CodeExecutionInput(language="sh", code=code), cancellation_token=CancellationToken()
)

assert result.success is False
assert "fake_command: command not found" in result.output
assert "fake_command: not found" in result.output


def test_code_execution_tool_serialization() -> None:
Expand Down
Loading