Skip to content

A programming framework for agentic AI

Changed Code Executors default directory to temporary directory (#6143)

Federico Villa9915b6592903
diff --git a/python/packages/autogen-ext/src/autogen_ext/code_executors/azure/_azure_container_code_executor.py b/python/packages/autogen-ext/src/autogen_ext/code_executors/azure/_azure_container_code_executor.py
index 5691d21ba..41b23c658 100644
--- a/python/packages/autogen-ext/src/autogen_ext/code_executors/azure/_azure_container_code_executor.py
+++ b/python/packages/autogen-ext/src/autogen_ext/code_executors/azure/_azure_container_code_executor.py
@@ -4,6 +4,8 @@ from __future__ import annotations
import asyncio
import os
+import tempfile
+import warnings
from pathlib import Path
from string import Template
from typing import TYPE_CHECKING, Any, Callable, ClassVar, List, Optional, Protocol, Sequence, Union
@@ -68,9 +70,12 @@ class ACADynamicSessionsCodeExecutor(CodeExecutor):
timeout (int): The timeout for the execution of any single code block. Default is 60.
work_dir (str): The working directory for the code execution. If None,
a default working directory will be used. The default working
- directory is the current directory ".".
+ directory is a temporal directory.
functions (List[Union[FunctionWithRequirements[Any, A], Callable[..., Any]]]): A list of functions that are available to the code executor. Default is an empty list.
suppress_result_output bool: By default the executor will attach any result info in the execution response to the result outpu. Set this to True to prevent this.
+
+ .. note::
+ Using the current directory (".") as working directory is deprecated. Using it will raise a deprecation warning.
"""
SUPPORTED_LANGUAGES: ClassVar[List[str]] = [
@@ -87,7 +92,7 @@ $functions"""
pool_management_endpoint: str,
credential: TokenProvider,
timeout: int = 60,
- work_dir: Union[Path, str] = Path("."),
+ work_dir: Union[Path, str, None] = None,
functions: Sequence[
Union[
FunctionWithRequirements[Any, A],
@@ -101,21 +106,31 @@ $functions"""
if timeout < 1:
raise ValueError("Timeout must be greater than or equal to 1.")
- if isinstance(work_dir, str):
- work_dir = Path(work_dir)
+ self._work_dir: Optional[Path] = None
+ self._temp_dir: Optional[tempfile.TemporaryDirectory[str]] = None
+
+ # If a user specifies a working directory, use that
+ if work_dir is not None:
+ if isinstance(work_dir, str):
+ self._work_dir = Path(work_dir)
+ else:
+ self._work_dir = work_dir
+ # Create the directory if it doesn't exist
+ self._work_dir.mkdir(exist_ok=True, parents=True)
+ # If a user does not specify a working directory, use the default directory (tempfile.TemporaryDirectory)
+ else:
+ self._temp_dir = tempfile.TemporaryDirectory()
+ temp_dir_path = Path(self._temp_dir.name)
+ temp_dir_path.mkdir(exist_ok=True, parents=True)
- if not functions_module.isidentifier():
- raise ValueError("Module name must be a valid Python identifier")
+ self._started = False
+ # Rest of initialization remains the same
self._functions_module = functions_module
-
- work_dir.mkdir(exist_ok=True)
- self._work_dir: Path = work_dir
-
self._timeout = timeout
-
self._functions = functions
- self._func_code: str | None = None
+ self._func_code: Optional[str] = None
+
# Setup could take some time so we intentionally wait for the first code block to do it.
if len(functions) > 0:
self._setup_functions_complete = False
@@ -172,8 +187,21 @@ $functions"""
@property
def work_dir(self) -> Path:
- """(Experimental) The working directory for the code execution."""
- return self._work_dir
+ # If a user specifies a working directory, use that
+ if self._work_dir is not None:
+ # If a user specifies the current directory, warn them that this is deprecated
+ if self._work_dir == Path("."):
+ warnings.warn(
+ "Using the current directory as work_dir is deprecated",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return self._work_dir
+ # If a user does not specify a working directory, use the default directory (tempfile.TemporaryDirectory)
+ elif self._temp_dir is not None:
+ return Path(self._temp_dir.name)
+ else:
+ raise RuntimeError("Working directory not properly initialized")
def _construct_url(self, path: str) -> str:
endpoint = self._pool_management_endpoint
@@ -210,11 +238,18 @@ import pkg_resources\n[d.project_name for d in pkg_resources.working_set]
flattened_packages = [item for sublist in lists_of_packages for item in sublist]
required_packages = set(flattened_packages)
+
+ if self._available_packages is None:
+ await self._populate_available_packages(cancellation_token)
+
if self._available_packages is not None:
missing_pkgs = set(required_packages - self._available_packages)
if len(missing_pkgs) > 0:
raise ValueError(f"Packages unavailable in environment: {missing_pkgs}")
+ func_file = self.work_dir / f"{self._functions_module}.py"
+ func_file.write_text(self._func_code)
+
# Attempt to load the function file to check for syntax errors, imports etc.
exec_result = await self._execute_code_dont_check_setup(
[CodeBlock(code=self._func_code, language="python")], cancellation_token
@@ -278,8 +313,8 @@ import pkg_resources\n[d.project_name for d in pkg_resources.working_set]
timeout = aiohttp.ClientTimeout(total=float(self._timeout))
async with aiohttp.ClientSession(timeout=timeout) as client:
for file in files:
- file_path = os.path.join(self._work_dir, file)
- if not os.path.isfile(file_path):
+ file_path = self.work_dir / file
+ if not file_path.is_file():
# TODO: what to do here?
raise FileNotFoundError(f"{file} does not exist")
@@ -339,8 +374,8 @@ import pkg_resources\n[d.project_name for d in pkg_resources.working_set]
try:
resp = await task
resp.raise_for_status()
- local_path = os.path.join(self._work_dir, file)
- local_paths.append(local_path)
+ local_path = self.work_dir / file
+ local_paths.append(str(local_path))
async with await open_file(local_path, "wb") as f:
await f.write(await resp.read())
except asyncio.TimeoutError as e:
@@ -457,7 +492,11 @@ import pkg_resources\n[d.project_name for d in pkg_resources.working_set]
return CodeResult(exit_code=exitcode, output=logs_all)
async def restart(self) -> None:
- """(Experimental) Restart the code executor."""
+ """(Experimental) Restart the code executor.
+
+ Resets the internal state of the executor by generating a new session ID and resetting the setup variables.
+ This causes the next code execution to reinitialize the environment and re-run any setup code.
+ """
self._session_id = str(uuid4())
self._setup_functions_complete = False
self._access_token = None
@@ -465,11 +504,17 @@ import pkg_resources\n[d.project_name for d in pkg_resources.working_set]
self._setup_cwd_complete = False
async def start(self) -> None:
- """(Experimental) Start the code executor."""
+ """(Experimental) Start the code executor.
+
+ Marks the code executor as started."""
# No setup needed for this executor
- pass
+ self._started = True
async def stop(self) -> None:
- """(Experimental) Stop the code executor."""
- # No cleanup needed for this executor
- pass
+ """(Experimental) Stop the code executor.
+
+ Stops the code executor after cleaning up the temporary working directory (if it was created)."""
+ if self._temp_dir is not None:
+ self._temp_dir.cleanup()
+ self._temp_dir = None
+ self._started = False
diff --git a/python/packages/autogen-ext/src/autogen_ext/code_executors/docker/_docker_code_executor.py b/python/packages/autogen-ext/src/autogen_ext/code_executors/docker/_docker_code_executor.py
index 266effcd6..51ac4f200 100644
--- a/python/packages/autogen-ext/src/autogen_ext/code_executors/docker/_docker_code_executor.py
+++ b/python/packages/autogen-ext/src/autogen_ext/code_executors/docker/_docker_code_executor.py
@@ -7,7 +7,9 @@ import asyncio
import logging
import shlex
import sys
+import tempfile
import uuid
+import warnings
from collections.abc import Sequence
from hashlib import sha256
from pathlib import Path
@@ -68,8 +70,8 @@ class DockerCommandLineCodeExecutorConfig(BaseModel):
image: str = "python:3-slim"
container_name: Optional[str] = None
timeout: int = 60
- work_dir: str = "." # Stored as string, converted to Path
- bind_dir: Optional[str] = None # Stored as string, converted to Path
+ work_dir: Optional[str] = None
+ bind_dir: Optional[str] = None
auto_remove: bool = True
stop_container: bool = True
functions_module: str = "functions"
@@ -95,8 +97,7 @@ class DockerCommandLineCodeExecutor(CodeExecutor, Component[DockerCommandLineCod
The executor executes the code blocks in the order they are received.
Currently, the executor only supports Python and shell scripts.
For Python code, use the language "python" for the code block.
- For shell scripts, use the language "bash", "shell", or "sh" for the code
- block.
+ For shell scripts, use the language "bash", "shell", "sh", "pwsh", "powershell", or "ps1" for the code block.
Args:
image (_type_, optional): Docker image to use for code execution.
@@ -105,7 +106,7 @@ class DockerCommandLineCodeExecutor(CodeExecutor, Component[DockerCommandLineCod
which is created. If None, will autogenerate a name. Defaults to None.
timeout (int, optional): The timeout for code execution. Defaults to 60.
work_dir (Union[Path, str], optional): The working directory for the code
- execution. Defaults to Path(".").
+ execution. Defaults to temporary directory.
bind_dir (Union[Path, str], optional): The directory that will be bound
to the code executor container. Useful for cases where you want to spawn
the container from within a container. Defaults to work_dir.
@@ -123,6 +124,10 @@ class DockerCommandLineCodeExecutor(CodeExecutor, Component[DockerCommandLineCod
Example: extra_hosts = {"kubernetes.docker.internal": "host-gateway"}
init_command (Optional[str], optional): A shell command to run before each shell operation execution. Defaults to None.
Example: init_command="kubectl config use-context docker-hub"
+
+ .. note::
+ Using the current directory (".") as working directory is deprecated. Using it will raise a deprecation warning.
+
"""
component_config_schema = DockerCommandLineCodeExecutorConfig
@@ -152,7 +157,7 @@ $functions"""
container_name: Optional[str] = None,
*,
timeout: int = 60,
- work_dir: Union[Path, str] = Path("."),
+ work_dir: Union[Path, str, None] = None,
bind_dir: Optional[Union[Path, str]] = None,
auto_remove: bool = True,
stop_container: bool = True,
@@ -171,14 +176,22 @@ $functions"""
if timeout < 1:
raise ValueError("Timeout must be greater than or equal to 1.")
- if isinstance(work_dir, str):
- work_dir = Path(work_dir)
- work_dir.mkdir(exist_ok=True)
-
- if bind_dir is None:
- bind_dir = work_dir
- elif isinstance(bind_dir, str):
- bind_dir = Path(bind_dir)
+ # Handle working directory logic
+ if work_dir is None:
+ self._work_dir = None
+ else:
+ if isinstance(work_dir, str):
+ work_dir = Path(work_dir)
+ # Emit a deprecation warning if the user is using the current directory as working directory
+ if work_dir.resolve() == Path.cwd().resolve():
+ warnings.warn(
+ "Using the current directory as work_dir is deprecated.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ self._work_dir = work_dir
+ # Create the working directory if it doesn't exist
+ self._work_dir.mkdir(exist_ok=True, parents=True)
if container_name is None:
self.container_name = f"autogen-code-exec-{uuid.uuid4()}"
@@ -186,8 +199,19 @@ $functions"""
self.container_name = container_name
self._timeout = timeout
- self._work_dir: Path = work_dir
- self._bind_dir: Path = bind_dir
+
+ # Handle bind_dir
+ self._bind_dir: Optional[Path] = None
+ if bind_dir is not None:
+ self._bind_dir = Path(bind_dir) if isinstance(bind_dir, str) else bind_dir
+ else:
+ self._bind_dir = self._work_dir # Default to work_dir if not provided
+
+ # Track temporary directory
+ self._temp_dir: Optional[tempfile.TemporaryDirectory[str]] = None
+ self._temp_dir_path: Optional[Path] = None
+
+ self._started = False
self._auto_remove = auto_remove
self._stop_container = stop_container
@@ -217,19 +241,9 @@ $functions"""
"""(Experimental) The timeout for code execution."""
return self._timeout
- @property
- def work_dir(self) -> Path:
- """(Experimental) The working directory for the code execution."""
- return self._work_dir
-
- @property
- def bind_dir(self) -> Path:
- """(Experimental) The binding directory for the code execution container."""
- return self._bind_dir
-
async def _setup_functions(self, cancellation_token: CancellationToken) -> None:
func_file_content = build_python_functions_file(self._functions)
- func_file = self._work_dir / f"{self._functions_module}.py"
+ func_file = self.work_dir / f"{self._functions_module}.py"
func_file.write_text(func_file_content)
# Collect requirements
@@ -303,7 +317,7 @@ $functions"""
# Check if there is a filename comment
try:
- filename = get_file_name_from_content(code, self._work_dir)
+ filename = get_file_name_from_content(code, self.work_dir)
except ValueError:
outputs.append("Filename is not in the workspace")
last_exit_code = 1
@@ -312,7 +326,7 @@ $functions"""
if not filename:
filename = f"tmp_code_{sha256(code.encode()).hexdigest()}.{lang}"
- code_path = self._work_dir / filename
+ code_path = self.work_dir / filename
with code_path.open("w", encoding="utf-8") as fout:
fout.write(code)
files.append(code_path)
@@ -328,6 +342,33 @@ $functions"""
code_file = str(files[0]) if files else None
return CommandLineCodeResult(exit_code=last_exit_code, output="".join(outputs), code_file=code_file)
+ @property
+ def work_dir(self) -> Path:
+ # If a user specifies a working directory, use that
+ if self._work_dir is not None:
+ # If a user specifies the current directory, warn them that this is deprecated
+ if self._work_dir == Path("."):
+ warnings.warn(
+ "Using the current directory as work_dir is deprecated.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return self._work_dir
+ # If a user does not specify a working directory, use the default directory (tempfile.TemporaryDirectory)
+ elif self._temp_dir is not None:
+ return Path(self._temp_dir.name)
+ else:
+ raise RuntimeError("Working directory not properly initialized")
+
+ @property
+ def bind_dir(self) -> Path:
+ # If the user specified a bind directory, return it
+ if self._bind_dir is not None:
+ return self._bind_dir
+ # Otherwise bind_dir is set to the current work_dir as default
+ else:
+ return self.work_dir
+
async def execute_code_blocks(
self, code_blocks: List[CodeBlock], cancellation_token: CancellationToken
) -> CommandLineCodeResult:
@@ -345,10 +386,10 @@ $functions"""
return await self._execute_code_dont_check_setup(code_blocks, cancellation_token)
async def restart(self) -> None:
+ """(Experimental) Restart the Docker container code executor."""
if self._container is None or not self._running:
raise ValueError("Container is not running. Must first be started with either start or a context manager.")
- """(Experimental) Restart the code executor."""
await asyncio.to_thread(self._container.restart) # type: ignore
if self._container.status != "running":
self._running = False
@@ -356,11 +397,19 @@ $functions"""
raise ValueError(f"Failed to restart container. Logs: {logs_str}")
async def stop(self) -> None:
- """(Experimental) Stop the code executor."""
+ """(Experimental) Stop the code executor.
+ Stops the Docker container and cleans up any temporary files (if they were created), along with the temporary directory.
+ The method first waits for all cancellation tasks to finish before stopping the container. Finally it marks the executor as not running.
+ If the container is not running, the method does nothing.
+ """
if not self._running:
return
+ if self._temp_dir is not None:
+ self._temp_dir.cleanup()
+ self._temp_dir = None
+
client = docker.from_env()
try:
container = await asyncio.to_thread(client.containers.get, self.container_name)
@@ -374,6 +423,17 @@ $functions"""
self._running = False
async def start(self) -> None:
+ """(Experimental) Start the code executor.
+
+ This method sets the working environment variables, connects to Docker and starts the code executor.
+ If no working directory was provided to the code executor, it creates a temporary directory and sets it as the code executor working directory.
+ """
+
+ if self._work_dir is None and self._temp_dir is None:
+ self._temp_dir = tempfile.TemporaryDirectory()
+ self._temp_dir_path = Path(self._temp_dir.name)
+ self._temp_dir_path.mkdir(exist_ok=True)
+
# Start a container from the image, read to exec commands later
try:
client = docker.from_env()
@@ -397,6 +457,13 @@ $functions"""
shell_command = "/bin/sh"
command = ["-c", f"{(self._init_command)};exec {shell_command}"] if self._init_command else None
+ # Check if a container with the same name already exists and remove it
+ try:
+ existing_container = await asyncio.to_thread(client.containers.get, self.container_name)
+ await asyncio.to_thread(existing_container.remove, force=True)
+ except NotFound:
+ pass
+
self._container = await asyncio.to_thread(
client.containers.create,
self._image,
@@ -406,7 +473,7 @@ $functions"""
tty=True,
detach=True,
auto_remove=self._auto_remove,
- volumes={str(self._bind_dir.resolve()): {"bind": "/workspace", "mode": "rw"}, **self._extra_volumes},
+ volumes={str(self.bind_dir.resolve()): {"bind": "/workspace", "mode": "rw"}, **self._extra_volumes},
working_dir="/workspace",
extra_hosts=self._extra_hosts,
)
@@ -437,7 +504,7 @@ $functions"""
image=self._image,
container_name=self.container_name,
timeout=self._timeout,
- work_dir=str(self._work_dir),
+ work_dir=str(self._work_dir) if self._work_dir else None,
bind_dir=str(self._bind_dir) if self._bind_dir else None,
auto_remove=self._auto_remove,
stop_container=self._stop_container,
@@ -450,13 +517,13 @@ $functions"""
@classmethod
def _from_config(cls, config: DockerCommandLineCodeExecutorConfig) -> Self:
"""(Experimental) Create a component from a config object."""
- bind_dir = Path(config.bind_dir) if config.bind_dir else None
+
return cls(
image=config.image,
container_name=config.container_name,
timeout=config.timeout,
- work_dir=Path(config.work_dir),
- bind_dir=bind_dir,
+ work_dir=Path(config.work_dir) if config.work_dir else None,
+ bind_dir=Path(config.bind_dir) if config.bind_dir else None,
auto_remove=config.auto_remove,
stop_container=config.stop_container,
functions=[], # Functions not restored from config
diff --git a/python/packages/autogen-ext/src/autogen_ext/code_executors/jupyter/_jupyter_code_executor.py b/python/packages/autogen-ext/src/autogen_ext/code_executors/jupyter/_jupyter_code_executor.py
index 385c26b6c..2476b5a33 100644
--- a/python/packages/autogen-ext/src/autogen_ext/code_executors/jupyter/_jupyter_code_executor.py
+++ b/python/packages/autogen-ext/src/autogen_ext/code_executors/jupyter/_jupyter_code_executor.py
@@ -3,7 +3,9 @@ import base64
import json
import re
import sys
+import tempfile
import uuid
+import warnings
from dataclasses import dataclass
from pathlib import Path
@@ -15,6 +17,9 @@ if sys.version_info >= (3, 11):
else:
from typing_extensions import Self
+from contextlib import AbstractAsyncContextManager
+from typing import Optional, Union
+
from autogen_core import CancellationToken
from autogen_core.code_executor import CodeBlock, CodeExecutor, CodeResult
from nbclient import NotebookClient
@@ -37,7 +42,7 @@ class JupyterCodeExecutorConfig(BaseModel):
kernel_name: str = "python3"
timeout: int = 60
- output_dir: str = "."
+ output_dir: Optional[str] = None
class JupyterCodeExecutor(CodeExecutor, Component[JupyterCodeExecutorConfig]):
@@ -121,7 +126,11 @@ class JupyterCodeExecutor(CodeExecutor, Component[JupyterCodeExecutorConfig]):
Args:
kernel_name (str): The kernel name to use. By default, "python3".
timeout (int): The timeout for code execution, by default 60.
- output_dir (Path): The directory to save output files, by default ".".
+ output_dir (Path): The directory to save output files, by default a temporary directory.
+
+
+ .. note::
+ Using the current directory (".") as output directory is deprecated. Using it will raise a deprecation warning.
"""
component_config_schema = JupyterCodeExecutorConfig
@@ -131,21 +140,24 @@ class JupyterCodeExecutor(CodeExecutor, Component[JupyterCodeExecutorConfig]):
self,
kernel_name: str = "python3",
timeout: int = 60,
- output_dir: Path = Path("."),
+ output_dir: Optional[Union[Path, str]] = None,
):
if timeout < 1:
raise ValueError("Timeout must be greater than or equal to 1.")
+ self._output_dir: Path = Path(tempfile.mkdtemp()) if output_dir is None else Path(output_dir)
+ self._output_dir.mkdir(exist_ok=True, parents=True)
+
+ self._temp_dir: Optional[tempfile.TemporaryDirectory[str]] = None
+ self._temp_dir_path: Optional[Path] = None
+
+ self._started = False
+
self._kernel_name = kernel_name
self._timeout = timeout
- self._output_dir = output_dir
- # TODO: Forward arguments perhaps?
- self._client = NotebookClient(
- nb=nbformat.new_notebook(), # type: ignore
- kernel_name=self._kernel_name,
- timeout=self._timeout,
- allow_errors=True,
- )
+
+ self._client: Optional[NotebookClient] = None
+ self.kernel_context: Optional[AbstractAsyncContextManager[None]] = None
async def execute_code_blocks(
self, code_blocks: list[CodeBlock], cancellation_token: CancellationToken
@@ -230,6 +242,8 @@ class JupyterCodeExecutor(CodeExecutor, Component[JupyterCodeExecutorConfig]):
async def _execute_cell(self, cell: NotebookNode) -> NotebookNode:
# Temporary push cell to nb as async_execute_cell expects it. But then we want to remove it again as cells can take up significant amount of memory (especially with images)
+ if not self._client:
+ raise RuntimeError("Executor must be started before executing cells")
self._client.nb.cells.append(cell)
output = await self._client.async_execute_cell(
cell,
@@ -257,20 +271,65 @@ class JupyterCodeExecutor(CodeExecutor, Component[JupyterCodeExecutorConfig]):
await self.start()
async def start(self) -> None:
+ """(Experimental) Start the code executor.
+
+ Initializes the Jupyter Notebook execution environment by creating a new notebook and setting it up with the specified Jupyter Kernel.
+ Marks the executor as started, allowing for code execution.
+ This method should be called before executing any code blocks.
+ """
+ if self._started:
+ return
+
+ notebook: NotebookNode = nbformat.new_notebook() # type: ignore
+
+ self._client = NotebookClient(
+ nb=notebook,
+ kernel_name=self._kernel_name,
+ timeout=self._timeout,
+ allow_errors=True,
+ )
+
self.kernel_context = self._client.async_setup_kernel()
await self.kernel_context.__aenter__()
+ self._started = True
+
async def stop(self) -> None:
- """Stop the kernel."""
- await self.kernel_context.__aexit__(None, None, None)
+ """(Experimental) Stop the code executor.
+
+ Terminates the Jupyter Notebook execution by exiting the kernel context and cleaning up the associated resources."""
+ if not self._started:
+ return
+
+ if self.kernel_context is not None:
+ await self.kernel_context.__aexit__(None, None, None)
+ self.kernel_context = None
+
+ self._client = None
+ self._started = False
def _to_config(self) -> JupyterCodeExecutorConfig:
"""Convert current instance to config object"""
return JupyterCodeExecutorConfig(
- kernel_name=self._kernel_name, timeout=self._timeout, output_dir=str(self._output_dir)
+ kernel_name=self._kernel_name, timeout=self._timeout, output_dir=str(self.output_dir)
)
+ @property
+ def output_dir(self) -> Path:
+ # If a user specifies the current directory, warn them that this is deprecated
+ if self._output_dir == Path("."):
+ warnings.warn(
+ "Using the current directory as output_dir is deprecated",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ return self._output_dir
+
@classmethod
def _from_config(cls, config: JupyterCodeExecutorConfig) -> Self:
"""Create instance from config object"""
- return cls(kernel_name=config.kernel_name, timeout=config.timeout, output_dir=Path(config.output_dir))
+ return cls(
+ kernel_name=config.kernel_name,
+ timeout=config.timeout,
+ output_dir=Path(config.output_dir) if config.output_dir else None,
+ )
diff --git a/python/packages/autogen-ext/src/autogen_ext/code_executors/local/__init__.py b/python/packages/autogen-ext/src/autogen_ext/code_executors/local/__init__.py
index 852c4aee2..3b02767cf 100644
--- a/python/packages/autogen-ext/src/autogen_ext/code_executors/local/__init__.py
+++ b/python/packages/autogen-ext/src/autogen_ext/code_executors/local/__init__.py
@@ -5,6 +5,7 @@ import asyncio
import logging
import os
import sys
+import tempfile
import warnings
from hashlib import sha256
from pathlib import Path
@@ -36,7 +37,7 @@ class LocalCommandLineCodeExecutorConfig(BaseModel):
"""Configuration for LocalCommandLineCodeExecutor"""
timeout: int = 60
- work_dir: str = "." # Stored as string, converted to Path in _from_config
+ work_dir: Optional[str] = None
functions_module: str = "functions"
@@ -56,7 +57,7 @@ class LocalCommandLineCodeExecutor(CodeExecutor, Component[LocalCommandLineCodeE
commands from being executed which may potentially affect the users environment.
Currently the only supported languages is Python and shell scripts.
For Python code, use the language "python" for the code block.
- For shell scripts, use the language "bash", "shell", or "sh" for the code
+ For shell scripts, use the language "bash", "shell", "sh", "pwsh", "powershell", or "ps1" for the code
block.
.. note::
@@ -74,12 +75,15 @@ class LocalCommandLineCodeExecutor(CodeExecutor, Component[LocalCommandLineCodeE
Args:
timeout (int): The timeout for the execution of any single code block. Default is 60.
work_dir (str): The working directory for the code execution. If None,
- a default working directory will be used. The default working
- directory is the current directory ".".
+ a default working directory will be used. The default working directory is a temporary directory.
functions (List[Union[FunctionWithRequirements[Any, A], Callable[..., Any]]]): A list of functions that are available to the code executor. Default is an empty list.
functions_module (str, optional): The name of the module that will be created to store the functions. Defaults to "functions".
virtual_env_context (Optional[SimpleNamespace], optional): The virtual environment context. Defaults to None.
+ .. note::
+ Using the current directory (".") as working directory is deprecated. Using it will raise a deprecation warning.
+
+
Example:
How to use `LocalCommandLineCodeExecutor` with a virtual environment different from the one used to run the autogen application:
@@ -141,7 +145,7 @@ $functions"""
def __init__(
self,
timeout: int = 60,
- work_dir: Union[Path, str] = Path("."),
+ work_dir: Optional[Union[Path, str]] = None,
functions: Sequence[
Union[
FunctionWithRequirements[Any, A],
@@ -155,18 +159,27 @@ $functions"""
if timeout < 1:
raise ValueError("Timeout must be greater than or equal to 1.")
- if isinstance(work_dir, str):
- work_dir = Path(work_dir)
+ self._work_dir: Optional[Path] = None
+ if work_dir is not None:
+ # Check if user provided work_dir is the current directory and warn if so.
+ if Path(work_dir).resolve() == Path.cwd().resolve():
+ warnings.warn(
+ "Using the current directory as work_dir is deprecated.",
+ DeprecationWarning,
+ stacklevel=2,
+ )
+ if isinstance(work_dir, str):
+ self._work_dir = Path(work_dir)
+ else:
+ self._work_dir = work_dir
+ self._work_dir.mkdir(exist_ok=True)
if not functions_module.isidentifier():
raise ValueError("Module name must be a valid Python identifier")
self._functions_module = functions_module
- work_dir.mkdir(exist_ok=True)
-
self._timeout = timeout
- self._work_dir: Path = work_dir
self._functions = functions
# Setup could take some time so we intentionally wait for the first code block to do it.
@@ -177,6 +190,9 @@ $functions"""
self._virtual_env_context: Optional[SimpleNamespace] = virtual_env_context
+ self._temp_dir: Optional[tempfile.TemporaryDirectory[str]] = None
+ self._started = False
+
# Check the current event loop policy if on windows.
if sys.platform == "win32":
current_policy = asyncio.get_event_loop_policy()
@@ -229,11 +245,18 @@ $functions"""
@property
def work_dir(self) -> Path:
"""(Experimental) The working directory for the code execution."""
- return self._work_dir
+ if self._work_dir is not None:
+ return self._work_dir
+ else:
+ # Automatically create temp directory if not exists
+ if self._temp_dir is None:
+ self._temp_dir = tempfile.TemporaryDirectory()
+ self._started = True
+ return Path(self._temp_dir.name)
async def _setup_functions(self, cancellation_token: CancellationToken) -> None:
func_file_content = build_python_functions_file(self._functions)
- func_file = self._work_dir / f"{self._functions_module}.py"
+ func_file = self.work_dir / f"{self._functions_module}.py"
func_file.write_text(func_file_content)
# Collect requirements
@@ -255,7 +278,7 @@ $functions"""
asyncio.create_subprocess_exec(
py_executable,
*cmd_args,
- cwd=self._work_dir,
+ cwd=self.work_dir,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
@@ -329,7 +352,7 @@ $functions"""
# Try extracting a filename (if present)
try:
- filename = get_file_name_from_content(code, self._work_dir)
+ filename = get_file_name_from_content(code, self.work_dir)
except ValueError:
return CommandLineCodeResult(
exit_code=1,
@@ -349,7 +372,7 @@ $functions"""
filename = f"tmp_code_{code_hash}.{ext}"
- written_file = (self._work_dir / filename).resolve()
+ written_file = (self.work_dir / filename).resolve()
with written_file.open("w", encoding="utf-8") as f:
f.write(code)
file_names.append(written_file)
@@ -388,7 +411,7 @@ $functions"""
asyncio.create_subprocess_exec(
program,
*extra_args,
- cwd=self._work_dir,
+ cwd=self.work_dir,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
env=env,
@@ -433,13 +456,26 @@ $functions"""
)
async def start(self) -> None:
- """(Experimental) Start the code executor."""
- # No action needed for local command line executor
- pass
+ """(Experimental) Start the code executor.
+
+ Initializes the local code executor and should be called before executing any code blocks.
+ It marks the executor internal state as started.
+ If no working directory is provided, the method creates a temporary directory for the executor to use.
+ """
+ if self._work_dir is None and self._temp_dir is None:
+ self._temp_dir = tempfile.TemporaryDirectory()
+ self._started = True
async def stop(self) -> None:
- """(Experimental) Stop the code executor."""
- # No action needed for local command line executor
+ """(Experimental) Stop the code executor.
+
+ Stops the local code executor and performs the cleanup of the temporary working directory (if it was created).
+ The executor's internal state is markes as no longer started.
+ """
+ if self._temp_dir is not None:
+ self._temp_dir.cleanup()
+ self._temp_dir = None
+ self._started = False
pass
def _to_config(self) -> LocalCommandLineCodeExecutorConfig:
@@ -450,7 +486,7 @@ $functions"""
return LocalCommandLineCodeExecutorConfig(
timeout=self._timeout,
- work_dir=str(self._work_dir),
+ work_dir=str(self.work_dir),
functions_module=self._functions_module,
)
@@ -458,6 +494,6 @@ $functions"""
def _from_config(cls, config: LocalCommandLineCodeExecutorConfig) -> Self:
return cls(
timeout=config.timeout,
- work_dir=Path(config.work_dir),
+ work_dir=Path(config.work_dir) if config.work_dir is not None else None,
functions_module=config.functions_module,
)
diff --git a/python/packages/autogen-ext/tests/code_executors/test_aca_dynamic_sessions.py b/python/packages/autogen-ext/tests/code_executors/test_aca_dynamic_sessions.py
index 51f677f34..8fa8503ca 100644
--- a/python/packages/autogen-ext/tests/code_executors/test_aca_dynamic_sessions.py
+++ b/python/packages/autogen-ext/tests/code_executors/test_aca_dynamic_sessions.py
@@ -33,6 +33,7 @@ async def test_execute_code() -> None:
executor = ACADynamicSessionsCodeExecutor(
pool_management_endpoint=POOL_ENDPOINT, credential=DefaultAzureCredential()
)
+ await executor.start()
# Test single code block.
code_blocks = [CodeBlock(code="import sys; print('hello world!')", language="python")]
@@ -59,6 +60,7 @@ async def test_execute_code() -> None:
code_blocks = [CodeBlock(code="\n".join(file_lines), language="python")]
code_result = await executor.execute_code_blocks(code_blocks, cancellation_token)
assert code_result.exit_code == 0 and "hello world!" in code_result.output and "200" in code_result.output
+ await executor.stop()
@pytest.mark.skipif(
@@ -121,9 +123,11 @@ async def test_azure_container_code_executor_timeout() -> None:
executor = ACADynamicSessionsCodeExecutor(
pool_management_endpoint=POOL_ENDPOINT, credential=DefaultAzureCredential(), timeout=1
)
+ await executor.start()
code_blocks = [CodeBlock(code="import time; time.sleep(10); print('hello world!')", language="python")]
with pytest.raises(asyncio.TimeoutError):
await executor.execute_code_blocks(code_blocks, cancellation_token)
+ await executor.stop()
@pytest.mark.skipif(
@@ -137,6 +141,7 @@ async def test_azure_container_code_executor_cancellation() -> None:
executor = ACADynamicSessionsCodeExecutor(
pool_management_endpoint=POOL_ENDPOINT, credential=DefaultAzureCredential()
)
+ await executor.start()
code_blocks = [CodeBlock(code="import time; time.sleep(10); print('hello world!')", language="python")]
coro = executor.execute_code_blocks(code_blocks, cancellation_token)
@@ -146,6 +151,7 @@ async def test_azure_container_code_executor_cancellation() -> None:
with pytest.raises(asyncio.CancelledError):
await coro
+ await executor.stop()
@pytest.mark.skipif(
@@ -165,6 +171,7 @@ async def test_upload_files() -> None:
executor = ACADynamicSessionsCodeExecutor(
pool_management_endpoint=POOL_ENDPOINT, credential=DefaultAzureCredential(), work_dir=temp_dir
)
+ await executor.start()
async with await open_file(os.path.join(temp_dir, test_file_1), "w") as f:
await f.write(test_file_1_contents)
@@ -193,6 +200,8 @@ with open("{test_file_2}") as f:
assert test_file_1_contents in code_result.output
assert test_file_2_contents in code_result.output
+ await executor.stop()
+
@pytest.mark.skipif(
not POOL_ENDPOINT,
@@ -211,6 +220,7 @@ async def test_download_files() -> None:
executor = ACADynamicSessionsCodeExecutor(
pool_management_endpoint=POOL_ENDPOINT, credential=DefaultAzureCredential(), work_dir=temp_dir
)
+ await executor.start()
code_blocks = [
CodeBlock(
@@ -240,3 +250,5 @@ with open("{test_file_2}", "w") as f:
async with await open_file(os.path.join(temp_dir, test_file_2), "r") as f:
content = await f.read()
assert test_file_2_contents in content
+
+ await executor.stop()
diff --git a/python/packages/autogen-ext/tests/code_executors/test_aca_user_defined_functions.py b/python/packages/autogen-ext/tests/code_executors/test_aca_user_defined_functions.py
index 27adbee72..b0a50837e 100644
--- a/python/packages/autogen-ext/tests/code_executors/test_aca_user_defined_functions.py
+++ b/python/packages/autogen-ext/tests/code_executors/test_aca_user_defined_functions.py
@@ -61,6 +61,7 @@ async def test_azure_can_load_function_with_reqs() -> None:
azure_executor = ACADynamicSessionsCodeExecutor(
pool_management_endpoint=POOL_ENDPOINT, credential=DefaultAzureCredential(), functions=[load_data]
)
+ await azure_executor.start()
# ACADynamicSessionsCodeExecutor doesn't use the functions module import
code = """import polars
@@ -77,6 +78,8 @@ print(data['name'][0])"""
assert azure_result.output == "John\n"
assert azure_result.exit_code == 0
+ await azure_executor.stop()
+
@pytest.mark.skipif(
not POOL_ENDPOINT,
@@ -90,6 +93,8 @@ async def test_azure_can_load_function() -> None:
azure_executor = ACADynamicSessionsCodeExecutor(
pool_management_endpoint=POOL_ENDPOINT, credential=DefaultAzureCredential(), functions=[add_two_numbers]
)
+ await azure_executor.start()
+
# ACADynamicSessionsCodeExecutor doesn't use the functions module import
code = """print(add_two_numbers(1, 2))"""
@@ -102,6 +107,8 @@ async def test_azure_can_load_function() -> None:
assert azure_result.output == "3\n"
assert azure_result.exit_code == 0
+ await azure_executor.stop()
+
@pytest.mark.skipif(
not POOL_ENDPOINT,
@@ -116,6 +123,8 @@ async def test_azure_fails_for_function_incorrect_import() -> None:
credential=DefaultAzureCredential(),
functions=[function_incorrect_import],
)
+ await azure_executor.start()
+
code = """function_incorrect_import()"""
with pytest.raises(ValueError):
@@ -126,6 +135,8 @@ async def test_azure_fails_for_function_incorrect_import() -> None:
cancellation_token=cancellation_token,
)
+ await azure_executor.stop()
+
@pytest.mark.skipif(
not POOL_ENDPOINT,
@@ -138,6 +149,7 @@ async def test_azure_fails_for_function_incorrect_dep() -> None:
azure_executor = ACADynamicSessionsCodeExecutor(
pool_management_endpoint=POOL_ENDPOINT, credential=DefaultAzureCredential(), functions=[function_incorrect_dep]
)
+ await azure_executor.start()
code = """function_incorrect_dep()"""
with pytest.raises(ValueError):
@@ -148,6 +160,8 @@ async def test_azure_fails_for_function_incorrect_dep() -> None:
cancellation_token=cancellation_token,
)
+ await azure_executor.stop()
+
def test_azure_formatted_prompt() -> None:
assert_str = '''def add_two_numbers(a: int, b: int) -> int:
@@ -200,6 +214,8 @@ def add_two_numbers(a: int, b: int) -> int:
azure_executor = ACADynamicSessionsCodeExecutor(
pool_management_endpoint=POOL_ENDPOINT, credential=DefaultAzureCredential(), functions=[func]
)
+ await azure_executor.start()
+
code = """print(add_two_numbers(1, 2))"""
azure_result = await azure_executor.execute_code_blocks(
@@ -211,6 +227,8 @@ def add_two_numbers(a: int, b: int) -> int:
assert azure_result.output == "3\n"
assert azure_result.exit_code == 0
+ await azure_executor.stop()
+
@pytest.mark.skipif(
not POOL_ENDPOINT,
@@ -231,6 +249,8 @@ def add_two_numbers(a: int, b: int) -> int:
azure_executor = ACADynamicSessionsCodeExecutor(
pool_management_endpoint=POOL_ENDPOINT, credential=DefaultAzureCredential(), functions=[func]
)
+ await azure_executor.start()
+
code = """print(add_two_numbers(object(), False))"""
azure_result = await azure_executor.execute_code_blocks(
@@ -242,3 +262,5 @@ def add_two_numbers(a: int, b: int) -> int:
# result.output = result.output.encode().decode('unicode_escape')
assert "TypeError: unsupported operand type(s) for +:" in azure_result.output
assert azure_result.exit_code == 1
+
+ await azure_executor.stop()
diff --git a/python/packages/autogen-ext/tests/code_executors/test_commandline_code_executor.py b/python/packages/autogen-ext/tests/code_executors/test_commandline_code_executor.py
index 2a5cedcb5..a167c37fe 100644
--- a/python/packages/autogen-ext/tests/code_executors/test_commandline_code_executor.py
+++ b/python/packages/autogen-ext/tests/code_executors/test_commandline_code_executor.py
@@ -28,7 +28,9 @@ async def executor_and_temp_dir(
request: pytest.FixtureRequest,
) -> AsyncGenerator[tuple[LocalCommandLineCodeExecutor, str], None]:
with tempfile.TemporaryDirectory() as temp_dir:
- yield LocalCommandLineCodeExecutor(work_dir=temp_dir), temp_dir
+ executor = LocalCommandLineCodeExecutor(work_dir=temp_dir)
+ await executor.start()
+ yield executor, temp_dir
ExecutorFixture: TypeAlias = tuple[LocalCommandLineCodeExecutor, str]
@@ -98,6 +100,7 @@ async def test_commandline_code_executor_cancellation() -> None:
with tempfile.TemporaryDirectory() as temp_dir:
cancellation_token = CancellationToken()
executor = LocalCommandLineCodeExecutor(work_dir=temp_dir)
+ await executor.start()
# Write code that sleep for 10 seconds and then write "hello world!"
# to a file.
code = """import time
@@ -173,6 +176,8 @@ async def test_local_executor_with_custom_venv() -> None:
env_builder_context = env_builder.ensure_directories(temp_dir)
executor = LocalCommandLineCodeExecutor(work_dir=temp_dir, virtual_env_context=env_builder_context)
+ await executor.start()
+
code_blocks = [
# https://stackoverflow.com/questions/1871549/how-to-determine-if-python-is-running-inside-a-virtualenv
CodeBlock(code="import sys; print(sys.prefix != sys.base_prefix)", language="python"),
@@ -197,6 +202,8 @@ async def test_local_executor_with_custom_venv_in_local_relative_path() -> None:
env_builder_context = env_builder.ensure_directories(env_path)
executor = LocalCommandLineCodeExecutor(work_dir=relative_folder_path, virtual_env_context=env_builder_context)
+ await executor.start()
+
code_blocks = [
CodeBlock(code="import sys; print(sys.executable)", language="python"),
]
@@ -213,13 +220,19 @@ async def test_local_executor_with_custom_venv_in_local_relative_path() -> None:
shutil.rmtree(relative_folder_path)
-def test_serialize_deserialize() -> None:
+async def test_serialize_deserialize() -> None:
with tempfile.TemporaryDirectory() as temp_dir:
executor = LocalCommandLineCodeExecutor(work_dir=temp_dir)
+ await executor.start()
executor_config = executor.dump_component()
loaded_executor = LocalCommandLineCodeExecutor.load_component(executor_config)
+ await loaded_executor.start()
assert executor.work_dir == loaded_executor.work_dir
+ await executor.stop()
+ await loaded_executor.stop()
+
@pytest.mark.asyncio
@pytest.mark.windows
diff --git a/python/packages/autogen-ext/tests/code_executors/test_docker_commandline_code_executor.py b/python/packages/autogen-ext/tests/code_executors/test_docker_commandline_code_executor.py
index 24ccdc218..dfaa1b99c 100644
--- a/python/packages/autogen-ext/tests/code_executors/test_docker_commandline_code_executor.py
+++ b/python/packages/autogen-ext/tests/code_executors/test_docker_commandline_code_executor.py
@@ -243,6 +243,75 @@ async def test_docker_commandline_code_executor_extra_args() -> None:
async def test_docker_commandline_code_executor_serialization() -> None:
with tempfile.TemporaryDirectory() as temp_dir:
executor = DockerCommandLineCodeExecutor(work_dir=temp_dir)
- loaded_executor = DockerCommandLineCodeExecutor.load_component(executor.dump_component())
+ await executor.start()
+
+ executor_config = executor.dump_component()
+ loaded_executor = DockerCommandLineCodeExecutor.load_component(executor_config)
+ await loaded_executor.start()
+
assert executor.bind_dir == loaded_executor.bind_dir
assert executor.timeout == loaded_executor.timeout
+
+ await executor.stop()
+ await loaded_executor.stop()
+
+
+def test_invalid_timeout() -> None:
+ with pytest.raises(ValueError, match="Timeout must be greater than or equal to 1."):
+ _ = DockerCommandLineCodeExecutor(timeout=0)
+
+
+async def test_directory_not_initialized() -> None:
+ executor = DockerCommandLineCodeExecutor()
+ with pytest.raises(RuntimeError, match="Working directory not properly initialized"):
+ _ = executor.work_dir
+
+
+async def test_error_wrong_path() -> None:
+ if not docker_tests_enabled():
+ pytest.skip("Docker tests are disabled")
+
+ with tempfile.TemporaryDirectory() as temp_dir:
+ async with DockerCommandLineCodeExecutor(work_dir=temp_dir) as executor:
+ cancellation_token = CancellationToken()
+ code_blocks = [
+ CodeBlock(
+ code="""with open("/nonexistent_dir/test.txt", "w") as f:
+ f.write("hello world!")""",
+ language="python",
+ )
+ ]
+ result = await executor.execute_code_blocks(code_blocks, cancellation_token)
+ assert result.exit_code != 0
+ assert "No such file or directory" in result.output
+
+
+async def test_deprecated_warning() -> None:
+ if not docker_tests_enabled():
+ pytest.skip("Docker tests are disabled")
+
+ with pytest.warns(DeprecationWarning, match="Using the current directory as work_dir is deprecated."):
+ async with DockerCommandLineCodeExecutor(work_dir=".") as executor:
+ await executor.start()
+ cancellation_token = CancellationToken()
+ code_block = CodeBlock(code='echo "hello world!"', language="sh")
+ result = await executor.execute_code_blocks([code_block], cancellation_token)
+ assert result.exit_code == 0
+ assert "hello world!" in result.output
+
+
+async def test_directory_creation_cleanup() -> None:
+ executor = DockerCommandLineCodeExecutor(timeout=60, work_dir=None)
+
+ await executor.start()
+
+ directory = executor.work_dir
+ assert directory.is_dir()
+
+ await executor.stop()
+
+ assert not Path(directory).exists()
diff --git a/python/packages/autogen-ext/tests/code_executors/test_jupyter_code_executor.py b/python/packages/autogen-ext/tests/code_executors/test_jupyter_code_executor.py
index 2ff0f1cb2..b6789d0b5 100644
--- a/python/packages/autogen-ext/tests/code_executors/test_jupyter_code_executor.py
+++ b/python/packages/autogen-ext/tests/code_executors/test_jupyter_code_executor.py
@@ -11,14 +11,17 @@ from autogen_ext.code_executors.jupyter import JupyterCodeExecutor, JupyterCodeR
@pytest.mark.asyncio
async def test_execute_code(tmp_path: Path) -> None:
async with JupyterCodeExecutor(output_dir=tmp_path) as executor:
+ await executor.start()
code_blocks = [CodeBlock(code="import sys; print('hello world!')", language="python")]
code_result = await executor.execute_code_blocks(code_blocks, CancellationToken())
assert code_result == JupyterCodeResult(exit_code=0, output="hello world!\n", output_files=[])
+ await executor.stop()
@pytest.mark.asyncio
async def test_execute_code_error(tmp_path: Path) -> None:
async with JupyterCodeExecutor(output_dir=tmp_path) as executor:
+ await executor.start()
code_blocks = [CodeBlock(code="print(undefined_variable)", language="python")]
code_result = await executor.execute_code_blocks(code_blocks, CancellationToken())
assert code_result == JupyterCodeResult(
@@ -33,22 +36,26 @@ async def test_execute_code_error(tmp_path: Path) -> None:
"""),
output_files=[],
)
+ await executor.stop()
@pytest.mark.asyncio
async def test_execute_multiple_code_blocks(tmp_path: Path) -> None:
async with JupyterCodeExecutor(output_dir=tmp_path) as executor:
+ await executor.start()
code_blocks = [
CodeBlock(code="import sys; print('hello world!')", language="python"),
CodeBlock(code="a = 100 + 100; print(a)", language="python"),
]
code_result = await executor.execute_code_blocks(code_blocks, CancellationToken())
assert code_result == JupyterCodeResult(exit_code=0, output="hello world!\n\n200\n", output_files=[])
+ await executor.stop()
@pytest.mark.asyncio
async def test_depedent_executions(tmp_path: Path) -> None:
async with JupyterCodeExecutor(output_dir=tmp_path) as executor:
+ await executor.start()
code_blocks_1 = [CodeBlock(code="a = 'hello world!'", language="python")]
code_blocks_2 = [
CodeBlock(code="print(a)", language="python"),
@@ -56,11 +63,13 @@ async def test_depedent_executions(tmp_path: Path) -> None:
await executor.execute_code_blocks(code_blocks_1, CancellationToken())
code_result = await executor.execute_code_blocks(code_blocks_2, CancellationToken())
assert code_result == JupyterCodeResult(exit_code=0, output="hello world!\n", output_files=[])
+ await executor.stop()
@pytest.mark.asyncio
async def test_execute_multiple_code_blocks_error(tmp_path: Path) -> None:
async with JupyterCodeExecutor(output_dir=tmp_path) as executor:
+ await executor.start()
code_blocks = [
CodeBlock(code="import sys; print('hello world!')", language="python"),
CodeBlock(code="a = 100 + 100; print(a); print(undefined_variable)", language="python"),
@@ -82,30 +91,37 @@ async def test_execute_multiple_code_blocks_error(tmp_path: Path) -> None:
"""),
output_files=[],
)
+ await executor.stop()
@pytest.mark.asyncio
async def test_execute_code_after_restart(tmp_path: Path) -> None:
async with JupyterCodeExecutor(output_dir=tmp_path) as executor:
+ await executor.start()
await executor.restart()
code_blocks = [CodeBlock(code="import sys; print('hello world!')", language="python")]
code_result = await executor.execute_code_blocks(code_blocks, CancellationToken())
assert code_result == JupyterCodeResult(exit_code=0, output="hello world!\n", output_files=[])
+ await executor.stop()
@pytest.mark.asyncio
async def test_commandline_code_executor_timeout(tmp_path: Path) -> None:
async with JupyterCodeExecutor(output_dir=tmp_path, timeout=2) as executor:
+ await executor.start()
code_blocks = [CodeBlock(code="import time; time.sleep(10); print('hello world!')", language="python")]
with pytest.raises(asyncio.TimeoutError):
await executor.execute_code_blocks(code_blocks, CancellationToken())
+ await executor.stop()
+
@pytest.mark.asyncio
async def test_commandline_code_executor_cancellation(tmp_path: Path) -> None:
async with JupyterCodeExecutor(output_dir=tmp_path) as executor:
+ await executor.start()
code_blocks = [CodeBlock(code="import time; time.sleep(10); print('hello world!')", language="python")]
cancellation_token = CancellationToken()
@@ -117,10 +133,13 @@ async def test_commandline_code_executor_cancellation(tmp_path: Path) -> None:
with pytest.raises(asyncio.CancelledError):
await code_result_coroutine
+ await executor.stop()
+
@pytest.mark.asyncio
async def test_execute_code_with_image_output(tmp_path: Path) -> None:
async with JupyterCodeExecutor(output_dir=tmp_path) as executor:
+ await executor.start()
code_blocks = [
CodeBlock(
code=inspect.cleandoc("""
@@ -144,10 +163,13 @@ async def test_execute_code_with_image_output(tmp_path: Path) -> None:
)
assert code_result.output_files[0].parent == tmp_path
+ await executor.stop()
+
@pytest.mark.asyncio
async def test_execute_code_with_html_output(tmp_path: Path) -> None:
async with JupyterCodeExecutor(output_dir=tmp_path) as executor:
+ await executor.start()
code_blocks = [
CodeBlock(
code=inspect.cleandoc("""
@@ -168,11 +190,38 @@ async def test_execute_code_with_html_output(tmp_path: Path) -> None:
)
assert code_result.output_files[0].parent == tmp_path
+ await executor.stop()
+
@pytest.mark.asyncio
async def test_jupyter_code_executor_serialization(tmp_path: Path) -> None:
executor = JupyterCodeExecutor(output_dir=tmp_path)
+ await executor.start()
serialized = executor.dump_component()
loaded_executor = JupyterCodeExecutor.load_component(serialized)
+ await loaded_executor.start()
assert isinstance(loaded_executor, JupyterCodeExecutor)
+
+ await loaded_executor.stop()
+ await executor.stop()
+
+
+def test_invalid_timeout() -> None:
+ with pytest.raises(ValueError, match="Timeout must be greater than or equal to 1."):
+ _ = JupyterCodeExecutor(timeout=0)
+
+
+async def test_deprecation_output_dir() -> None:
+ with pytest.warns(DeprecationWarning, match="Using the current directory as output_dir is deprecated"):
+ async with JupyterCodeExecutor(output_dir=".") as executor:
+ _ = executor.output_dir
+
+
+async def test_runtime_error_not_started() -> None:
+ executor = JupyterCodeExecutor()
+ code_blocks = [CodeBlock(code="print('hello world!')", language="python")]
+ with pytest.raises(RuntimeError, match="Executor must be started before executing cells"):
+ await executor.execute_code_blocks(code_blocks, CancellationToken())
diff --git a/python/packages/autogen-ext/tests/code_executors/test_user_defined_functions.py b/python/packages/autogen-ext/tests/code_executors/test_user_defined_functions.py
index c8dd6eb5f..ebfdf5328 100644
--- a/python/packages/autogen-ext/tests/code_executors/test_user_defined_functions.py
+++ b/python/packages/autogen-ext/tests/code_executors/test_user_defined_functions.py
@@ -3,6 +3,7 @@
import os
import tempfile
+from pathlib import Path
import polars
import pytest
@@ -59,6 +60,7 @@ async def test_can_load_function_with_reqs() -> None:
with tempfile.TemporaryDirectory() as temp_dir:
cancellation_token = CancellationToken()
executor = LocalCommandLineCodeExecutor(work_dir=temp_dir, functions=[load_data])
+ await executor.start()
code = f"""from {executor.functions_module} import load_data
import polars
@@ -75,19 +77,24 @@ print(data['name'][0])"""
assert result.output == f"John{os.linesep}"
assert result.exit_code == 0
+ await executor.stop()
-def test_local_formatted_prompt() -> None:
+
+async def test_local_formatted_prompt() -> None:
assert_str = '''def add_two_numbers(a: int, b: int) -> int:
"""Add two numbers together."""
'''
with tempfile.TemporaryDirectory() as temp_dir:
executor = LocalCommandLineCodeExecutor(work_dir=temp_dir, functions=[add_two_numbers])
+ await executor.start()
result = executor.format_functions_for_prompt()
assert assert_str in result
+ await executor.stop()
+
-def test_local_formatted_prompt_str_func() -> None:
+async def test_local_formatted_prompt_str_func() -> None:
func = FunctionWithRequirements.from_str(
'''
def add_two_numbers(a: int, b: int) -> int:
@@ -102,16 +109,20 @@ def add_two_numbers(a: int, b: int) -> int:
with tempfile.TemporaryDirectory() as temp_dir:
executor = LocalCommandLineCodeExecutor(work_dir=temp_dir, functions=[func])
+ await executor.start()
result = executor.format_functions_for_prompt()
assert assert_str in result
+ await executor.stop()
+
@pytest.mark.asyncio
async def test_can_load_function() -> None:
with tempfile.TemporaryDirectory() as temp_dir:
cancellation_token = CancellationToken()
executor = LocalCommandLineCodeExecutor(work_dir=temp_dir, functions=[add_two_numbers])
+ await executor.start()
code = f"""from {executor.functions_module} import add_two_numbers
print(add_two_numbers(1, 2))"""
@@ -124,12 +135,17 @@ print(add_two_numbers(1, 2))"""
assert result.output == f"3{os.linesep}"
assert result.exit_code == 0
+ await executor.stop()
+
@pytest.mark.asyncio
async def test_fails_for_function_incorrect_import() -> None:
with tempfile.TemporaryDirectory() as temp_dir:
cancellation_token = CancellationToken()
executor = LocalCommandLineCodeExecutor(work_dir=temp_dir, functions=[function_incorrect_import])
+
+ await executor.start()
+
code = f"""from {executor.functions_module} import function_incorrect_import
function_incorrect_import()"""
@@ -141,12 +157,17 @@ function_incorrect_import()"""
cancellation_token=cancellation_token,
)
+ await executor.stop()
+
@pytest.mark.asyncio
async def test_fails_for_function_incorrect_dep() -> None:
with tempfile.TemporaryDirectory() as temp_dir:
cancellation_token = CancellationToken()
executor = LocalCommandLineCodeExecutor(work_dir=temp_dir, functions=[function_incorrect_dep])
+
+ await executor.start()
+
code = f"""from {executor.functions_module} import function_incorrect_dep
function_incorrect_dep()"""
@@ -158,6 +179,8 @@ function_incorrect_dep()"""
cancellation_token=cancellation_token,
)
+ await executor.stop()
+
@pytest.mark.asyncio
async def test_can_load_str_function_with_reqs() -> None:
@@ -172,6 +195,8 @@ def add_two_numbers(a: int, b: int) -> int:
cancellation_token = CancellationToken()
executor = LocalCommandLineCodeExecutor(work_dir=temp_dir, functions=[func])
+ await executor.start()
+
code = f"""from {executor.functions_module} import add_two_numbers
print(add_two_numbers(1, 2))"""
@@ -184,6 +209,8 @@ print(add_two_numbers(1, 2))"""
assert result.output == f"3{os.linesep}"
assert result.exit_code == 0
+ await executor.stop()
+
def test_cant_load_broken_str_function_with_reqs() -> None:
with pytest.raises(ValueError):
@@ -209,6 +236,8 @@ def add_two_numbers(a: int, b: int) -> int:
cancellation_token = CancellationToken()
executor = LocalCommandLineCodeExecutor(work_dir=temp_dir, functions=[func])
+ await executor.start()
+
code = f"""from {executor.functions_module} import add_two_numbers
print(add_two_numbers(object(), False))"""
@@ -220,3 +249,71 @@ print(add_two_numbers(object(), False))"""
)
assert "TypeError: unsupported operand type(s) for +:" in result.output
assert result.exit_code == 1
+
+ await executor.stop()
+
+
+async def test_error_wrong_path() -> None:
+ with tempfile.TemporaryDirectory() as temp_dir:
+ executor = LocalCommandLineCodeExecutor(work_dir=temp_dir, functions=[])
+ await executor.start()
+
+ code_blocks = [
+ CodeBlock(
+ code="""with open("/nonexistent_dir/test.txt", "w") as f:
+ f.write("hello word")""",
+ language="python",
+ )
+ ]
+
+ result = await executor.execute_code_blocks(code_blocks, CancellationToken())
+ assert result.exit_code != 0
+ assert "No such file or directory" in result.output
+
+ await executor.stop()
+
+
+async def test_deprecated_warning() -> None:
+ with pytest.warns(DeprecationWarning, match="Using the current directory as work_dir is deprecated."):
+ executor = LocalCommandLineCodeExecutor(work_dir=".", functions=[])
+ await executor.start()
+
+ code_block = CodeBlock(code='echo "hello word"', language="sh")
+ result = await executor.execute_code_blocks([code_block], CancellationToken())
+
+ assert result.exit_code == 0
+ assert "hello word" in result.output
+
+ await executor.stop()
+
+
+async def test_default_work_dir_is_temp() -> None:
+ executor = LocalCommandLineCodeExecutor(functions=[])
+ await executor.start()
+
+ assert executor.work_dir != Path(".")
+
+ system_temp = tempfile.gettempdir()
+ assert system_temp in str(executor.work_dir)
+
+ await executor.stop()
+
+
+def test_invalid_timeout() -> None:
+ with pytest.raises(ValueError, match="Timeout must be greater than or equal to 1."):
+ _ = LocalCommandLineCodeExecutor(timeout=0)
+
+
+def test_python_identifier() -> None:
+ with pytest.raises(ValueError, match="Module name must be a valid Python identifier"):
+ # Using a name with an hyphen is an example of an invalid Python identifier
+ _ = LocalCommandLineCodeExecutor(functions_module="invalid-identifier")
+
+
+async def test_create_temp_dir() -> None:
+ executor = LocalCommandLineCodeExecutor()
+ assert executor.work_dir.is_dir()