Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,18 @@ def __init__(
self._approval_func = approval_func
self._approval_func_is_async = approval_func is not None and iscoroutinefunction(approval_func)

# Issue warning if no approval function is set
if approval_func is None:
import warnings

warnings.warn(
"No approval function set for CodeExecutorAgent. This means code will be executed automatically without human oversight. "
"For security, consider setting an approval_func to review and approve code before execution. "
"See the CodeExecutorAgent documentation for examples of approval functions.",
UserWarning,
stacklevel=2,
)

if supported_languages is not None:
self._supported_languages = supported_languages
else:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
"""Code executor utilities for AutoGen-Ext."""

import warnings
from typing import Optional

from autogen_core.code_executor import CodeExecutor

# Docker imports for default code executor
try:
import docker as docker_client
from docker.errors import DockerException

from .docker import DockerCommandLineCodeExecutor

_docker_available = True
except ImportError:
docker_client = None # type: ignore
DockerException = Exception # type: ignore
DockerCommandLineCodeExecutor = None # type: ignore
_docker_available = False

from .local import LocalCommandLineCodeExecutor


def _is_docker_available() -> bool:
"""Check if Docker is available and running."""
if not _docker_available:
return False

try:
if docker_client is not None:
client = docker_client.from_env()
client.ping() # type: ignore
return True
except DockerException:
return False

return False


def create_default_code_executor(work_dir: Optional[str] = None) -> CodeExecutor:
"""Create a default code executor, preferring Docker if available.

This function creates a code executor using the following priority:
1. DockerCommandLineCodeExecutor if Docker is available
2. LocalCommandLineCodeExecutor with a warning if Docker is not available

Args:
work_dir: Optional working directory for the code executor

Returns:
CodeExecutor: A code executor instance

.. warning::
For security, it is recommended to use DockerCommandLineCodeExecutor
when available to isolate code execution.
"""
if _is_docker_available() and DockerCommandLineCodeExecutor is not None:
try:
if work_dir:
return DockerCommandLineCodeExecutor(work_dir=work_dir)
else:
return DockerCommandLineCodeExecutor()
except Exception:
# Fallback to local if Docker fails to initialize
pass

# Issue warning and use local executor if Docker is not available
warnings.warn(
"Docker is not available or not running. Using LocalCommandLineCodeExecutor instead of the recommended DockerCommandLineCodeExecutor. "
"For security, it is recommended to install Docker and ensure it's running before using code executors. "
"To install Docker, visit: https://docs.docker.com/get-docker/",
UserWarning,
stacklevel=2,
)

if work_dir:
return LocalCommandLineCodeExecutor(work_dir=work_dir)
else:
return LocalCommandLineCodeExecutor()


__all__ = ["create_default_code_executor"]
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,10 @@
FunctionWithRequirements,
FunctionWithRequirementsStr,
)
from docker.types import DeviceRequest
from pydantic import BaseModel
from typing_extensions import Self

from docker.types import DeviceRequest

from .._common import (
CommandLineCodeResult,
build_python_functions_file,
Expand All @@ -43,7 +42,6 @@

try:
import asyncio_atexit

import docker
from docker.errors import DockerException, ImageNotFound, NotFound
from docker.models.containers import Container
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@

from autogen_core import CancellationToken, Component
from autogen_core.code_executor import CodeBlock, CodeExecutor, CodeResult
from autogen_ext.code_executors._common import silence_pip
from pydantic import BaseModel
from typing_extensions import Self

from autogen_ext.code_executors._common import silence_pip

from ._jupyter_server import JupyterClient, JupyterConnectable, JupyterConnectionInfo, JupyterKernelClient


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,15 @@ def __init__(
cleanup_temp_files: bool = True,
virtual_env_context: Optional[SimpleNamespace] = None,
):
# Issue warning about using LocalCommandLineCodeExecutor
warnings.warn(
"Using LocalCommandLineCodeExecutor may execute code on the local machine which can be unsafe. "
"For security, it is recommended to use DockerCommandLineCodeExecutor instead. "
"To install Docker, visit: https://docs.docker.com/get-docker/",
UserWarning,
stacklevel=2,
)

if timeout < 1:
raise ValueError("Timeout must be greater than or equal to 1.")
self._timeout = timeout
Expand Down
54 changes: 2 additions & 52 deletions python/packages/autogen-ext/src/autogen_ext/teams/magentic_one.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,64 +11,14 @@
from autogen_ext.agents.file_surfer import FileSurfer
from autogen_ext.agents.magentic_one import MagenticOneCoderAgent
from autogen_ext.agents.web_surfer import MultimodalWebSurfer
from autogen_ext.code_executors.local import LocalCommandLineCodeExecutor
from autogen_ext.code_executors import create_default_code_executor
from autogen_ext.models.openai._openai_client import BaseOpenAIChatCompletionClient

# Docker imports for default code executor
try:
import docker
from docker.errors import DockerException

from autogen_ext.code_executors.docker import DockerCommandLineCodeExecutor

_docker_available = True
except ImportError:
docker = None # type: ignore
DockerException = Exception # type: ignore
DockerCommandLineCodeExecutor = None # type: ignore
_docker_available = False

SyncInputFunc = Callable[[str], str]
AsyncInputFunc = Callable[[str, Optional[CancellationToken]], Awaitable[str]]
InputFuncType = Union[SyncInputFunc, AsyncInputFunc]


def _is_docker_available() -> bool:
"""Check if Docker is available and running."""
if not _docker_available:
return False

try:
if docker is not None:
client = docker.from_env()
client.ping() # type: ignore
return True
except DockerException:
return False

return False


def _create_default_code_executor() -> CodeExecutor:
"""Create the default code executor, preferring Docker if available."""
if _is_docker_available() and DockerCommandLineCodeExecutor is not None:
try:
return DockerCommandLineCodeExecutor()
except Exception:
# Fallback to local if Docker fails to initialize
pass

# Issue warning and use local executor if Docker is not available
warnings.warn(
"Docker is not available or not running. Using LocalCommandLineCodeExecutor instead of the recommended DockerCommandLineCodeExecutor. "
"For security, it is recommended to install Docker and ensure it's running before using MagenticOne. "
"To install Docker, visit: https://docs.docker.com/get-docker/",
UserWarning,
stacklevel=3,
)
return LocalCommandLineCodeExecutor()


class MagenticOne(MagenticOneGroupChat):
"""
MagenticOne is a specialized group chat class that integrates various agents
Expand Down Expand Up @@ -256,7 +206,7 @@ def __init__(
DeprecationWarning,
stacklevel=2,
)
code_executor = _create_default_code_executor()
code_executor = create_default_code_executor()

fs = FileSurfer("FileSurfer", model_client=client)
ws = MultimodalWebSurfer("WebSurfer", model_client=client)
Expand Down
4 changes: 2 additions & 2 deletions python/packages/autogen-ext/tests/teams/test_magentic_one.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def test_docker_availability_check() -> None:
assert isinstance(result, bool)


@patch("autogen_ext.teams.magentic_one._is_docker_available")
@patch("autogen_ext.code_executors._is_docker_available")
def test_magentic_one_falls_back_to_local_when_docker_unavailable(
mock_docker_check: Mock, mock_chat_client: Mock
) -> None:
Expand Down Expand Up @@ -154,7 +154,7 @@ def test_magentic_one_falls_back_to_local_when_docker_unavailable(
assert deprecated_warning_found, f"Deprecation warning not found in: {warning_messages}"


@patch("autogen_ext.teams.magentic_one._is_docker_available")
@patch("autogen_ext.code_executors._is_docker_available")
def test_magentic_one_falls_back_to_local_with_approval_function(
mock_docker_check: Mock, mock_chat_client: Mock
) -> None:
Expand Down
Loading