A programming framework for agentic AI
Move start() and stop() as interface methods for CodeExecutor (#6040)
Eric Zhu46add11ec730
diff --git a/python/packages/autogen-core/src/autogen_core/code_executor/_base.py b/python/packages/autogen-core/src/autogen_core/code_executor/_base.pyindex 661751908..727a1eb52 100644--- a/python/packages/autogen-core/src/autogen_core/code_executor/_base.py+++ b/python/packages/autogen-core/src/autogen_core/code_executor/_base.py@@ -5,9 +5,11 @@ from __future__ import annotationsfrom abc import ABC, abstractmethodfrom dataclasses import dataclass-from typing import List+from types import TracebackType+from typing import List, Optional, Typefrom pydantic import BaseModel+from typing_extensions import Selffrom .._cancellation_token import CancellationTokenfrom .._component_config import ComponentBase@@ -30,7 +32,21 @@ class CodeResult:class CodeExecutor(ABC, ComponentBase[BaseModel]):- """Executes code blocks and returns the result."""+ """Executes code blocks and returns the result.++ This is an abstract base class for code executors. It defines the interface+ for executing code blocks and returning the result. A concrete implementation+ of this class should be provided to execute code blocks in a specific+ environment. For example, :class:`~autogen_ext.code_executors.docker.DockerCommandLineCodeExecutor` executes+ code blocks in a command line environment in a Docker container.++ It is recommended for subclass to be used as a context manager to ensure+ that resources are cleaned up properly. To do this, implement the+ :meth:`~autogen_core.code_executor.CodeExecutor.start` and+ :meth:`~autogen_core.code_executor.CodeExecutor.stop` methods+ that will be called when entering and exiting the context manager.++ """component_type = "code_executor"@@ -55,6 +71,16 @@ class CodeExecutor(ABC, ComponentBase[BaseModel]):"""...+ @abstractmethod+ async def start(self) -> None:+ """Start the code executor."""+ ...++ @abstractmethod+ async def stop(self) -> None:+ """Stop the code executor and release any resources."""+ ...+@abstractmethodasync def restart(self) -> None:"""Restart the code executor.@@ -64,3 +90,13 @@ class CodeExecutor(ABC, ComponentBase[BaseModel]):This method is called when the agent is reset."""...++ async def __aenter__(self) -> Self:+ await self.start()+ return self++ async def __aexit__(+ self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]+ ) -> Optional[bool]:+ await self.stop()+ return Nonediff --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.pyindex 3192abfb8..2a6f6c8ee 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@@ -458,3 +458,13 @@ import pkg_resources\n[d.project_name for d in pkg_resources.working_set]self._access_token = Noneself._available_packages = Noneself._setup_cwd_complete = False++ async def start(self) -> None:+ """(Experimental) Start the code executor."""+ # No setup needed for this executor+ pass++ async def stop(self) -> None:+ """(Experimental) Stop the code executor."""+ # No cleanup needed for this executor+ passdiff --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.pyindex 829ad770f..266effcd6 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@@ -11,8 +11,7 @@ import uuidfrom collections.abc import Sequencefrom hashlib import sha256from pathlib import Path-from types import TracebackType-from typing import Any, Callable, ClassVar, Dict, List, Optional, ParamSpec, Tuple, Type, Union+from typing import Any, Callable, ClassVar, Dict, List, Optional, ParamSpec, Tuple, Unionfrom autogen_core import CancellationToken, Componentfrom autogen_core.code_executor import (@@ -429,16 +428,6 @@ $functions"""self._running = True- async def __aenter__(self) -> Self:- await self.start()- return self-- async def __aexit__(- self, exc_type: Optional[Type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]- ) -> Optional[bool]:- await self.stop()- return None-def _to_config(self) -> DockerCommandLineCodeExecutorConfig:"""(Experimental) Convert the component to a config object."""if self._functions: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.pyindex 6da6b18ff..385c26b6c 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@@ -6,7 +6,6 @@ import sysimport uuidfrom dataclasses import dataclassfrom pathlib import Path-from types import TracebackTypefrom autogen_core import Componentfrom pydantic import BaseModel@@ -265,18 +264,6 @@ class JupyterCodeExecutor(CodeExecutor, Component[JupyterCodeExecutorConfig]):"""Stop the kernel."""await self.kernel_context.__aexit__(None, None, None)- async def __aenter__(self) -> Self:- await self.start()- return self-- async def __aexit__(- self,- exc_type: type[BaseException] | None,- exc_val: BaseException | None,- exc_tb: TracebackType | None,- ) -> None:- await self.stop()-def _to_config(self) -> JupyterCodeExecutorConfig:"""Convert current instance to config object"""return JupyterCodeExecutorConfig(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__.pyindex 654c9eab8..852c4aee2 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@@ -432,6 +432,16 @@ $functions"""stacklevel=2,)+ async def start(self) -> None:+ """(Experimental) Start the code executor."""+ # No action needed for local command line executor+ pass++ async def stop(self) -> None:+ """(Experimental) Stop the code executor."""+ # No action needed for local command line executor+ pass+def _to_config(self) -> LocalCommandLineCodeExecutorConfig:if self._functions:logging.info("Functions will not be included in serialized configuration")