Skip to content

PythonCodeExecutionTool

autogen.tools.experimental.PythonCodeExecutionTool #

PythonCodeExecutionTool(*, timeout=30, working_directory=None, python_environment=None)

Bases: Tool

Executes Python code in a given environment and returns the result.

Initialize the PythonCodeExecutionTool.

CAUTION: If provided a local environment, this tool will execute code in your local environment, which can be dangerous if the code is untrusted.

PARAMETER DESCRIPTION
timeout

Maximum execution time allowed in seconds, will raise a TimeoutError exception if exceeded.

TYPE: int DEFAULT: 30

working_directory

Optional WorkingDirectory context manager to use.

TYPE: Optional[WorkingDirectory] DEFAULT: None

python_environment

Optional PythonEnvironment to use. If None, will auto-detect or create based on other parameters.

TYPE: Optional[PythonEnvironment] DEFAULT: None

Source code in autogen/tools/experimental/code_execution/python_code_execution.py
def __init__(
    self,
    *,
    timeout: int = 30,
    working_directory: Optional[WorkingDirectory] = None,
    python_environment: Optional[PythonEnvironment] = None,
) -> None:
    """
    Initialize the PythonCodeExecutionTool.

    **CAUTION**: If provided a local environment, this tool will execute code in your local environment, which can be dangerous if the code is untrusted.

    Args:
        timeout: Maximum execution time allowed in seconds, will raise a TimeoutError exception if exceeded.
        working_directory: Optional WorkingDirectory context manager to use.
        python_environment: Optional PythonEnvironment to use. If None, will auto-detect or create based on other parameters.
    """
    # Store configuration parameters
    self.timeout = timeout
    self.working_directory = WorkingDirectory.get_current_working_directory(working_directory)
    tool_python_environment = PythonEnvironment.get_current_python_environment(python_environment)

    assert self.working_directory, "No Working directory found"
    assert tool_python_environment, "No Python environment found"

    self.python_environment = tool_python_environment

    # Pydantic model to contain the code and list of libraries to execute
    class CodeExecutionRequest(BaseModel):
        code: Annotated[str, Field(description="Python code to execute")]
        libraries: Annotated[list[str], Field(description="List of libraries to install before execution")]

    # The tool function, this is what goes to the LLM
    async def execute_python_code(
        code_execution_request: Annotated[CodeExecutionRequest, "Python code and the libraries required"],
    ) -> dict[str, Any]:
        """
        Executes Python code in the attached environment and returns the result.

        Args:
            code_execution_request (CodeExecutionRequest): The Python code and libraries to execute
        """
        code = code_execution_request.code

        # NOTE: Libraries are not installed (something to consider for future versions)

        # Prepare a script file path
        script_dir = self._get_script_directory()
        script_path = os.path.join(script_dir, "script.py")

        # Execute the code
        return await self.python_environment.execute_code(code=code, script_path=script_path, timeout=self.timeout)

    super().__init__(
        name="python_execute_code",
        description="Executes Python code and returns the result.",
        func_or_tool=execute_python_code,
    )

name property #

name

description property #

description

func property #

func

tool_schema property #

tool_schema

Get the schema for the tool.

This is the preferred way of handling function calls with OpeaAI and compatible frameworks.

function_schema property #

function_schema

Get the schema for the function.

This is the old way of handling function calls with OpenAI and compatible frameworks. It is provided for backward compatibility.

realtime_tool_schema property #

realtime_tool_schema

Get the schema for the tool.

This is the preferred way of handling function calls with OpeaAI and compatible frameworks.

timeout instance-attribute #

timeout = timeout

working_directory instance-attribute #

working_directory = get_current_working_directory(working_directory)

python_environment instance-attribute #

python_environment = tool_python_environment

register_for_llm #

register_for_llm(agent)

Registers the tool for use with a ConversableAgent's language model (LLM).

This method registers the tool so that it can be invoked by the agent during interactions with the language model.

PARAMETER DESCRIPTION
agent

The agent to which the tool will be registered.

TYPE: ConversableAgent

Source code in autogen/tools/tool.py
def register_for_llm(self, agent: "ConversableAgent") -> None:
    """Registers the tool for use with a ConversableAgent's language model (LLM).

    This method registers the tool so that it can be invoked by the agent during
    interactions with the language model.

    Args:
        agent (ConversableAgent): The agent to which the tool will be registered.
    """
    if self._func_schema:
        agent.update_tool_signature(self._func_schema, is_remove=False)
    else:
        agent.register_for_llm()(self)

register_for_execution #

register_for_execution(agent)

Registers the tool for direct execution by a ConversableAgent.

This method registers the tool so that it can be executed by the agent, typically outside of the context of an LLM interaction.

PARAMETER DESCRIPTION
agent

The agent to which the tool will be registered.

TYPE: ConversableAgent

Source code in autogen/tools/tool.py
def register_for_execution(self, agent: "ConversableAgent") -> None:
    """Registers the tool for direct execution by a ConversableAgent.

    This method registers the tool so that it can be executed by the agent,
    typically outside of the context of an LLM interaction.

    Args:
        agent (ConversableAgent): The agent to which the tool will be registered.
    """
    agent.register_for_execution()(self)

register_tool #

register_tool(agent)

Register a tool to be both proposed and executed by an agent.

Equivalent to calling both register_for_llm and register_for_execution with the same agent.

Note: This will not make the agent recommend and execute the call in the one step. If the agent recommends the tool, it will need to be the next agent to speak in order to execute the tool.

PARAMETER DESCRIPTION
agent

The agent to which the tool will be registered.

TYPE: ConversableAgent

Source code in autogen/tools/tool.py
def register_tool(self, agent: "ConversableAgent") -> None:
    """Register a tool to be both proposed and executed by an agent.

    Equivalent to calling both `register_for_llm` and `register_for_execution` with the same agent.

    Note: This will not make the agent recommend and execute the call in the one step. If the agent
    recommends the tool, it will need to be the next agent to speak in order to execute the tool.

    Args:
        agent (ConversableAgent): The agent to which the tool will be registered.
    """
    self.register_for_llm(agent)
    self.register_for_execution(agent)