A programming framework for agentic AI
Add approval_func option to CodeExecutorAgent (#6886)
Eric Zhuc1e4ae681982
diff --git a/python/docs/src/user-guide/agentchat-user-guide/magentic-one.md b/python/docs/src/user-guide/agentchat-user-guide/magentic-one.mdindex 46b90ad45..6de052d1a 100644--- a/python/docs/src/user-guide/agentchat-user-guide/magentic-one.md+++ b/python/docs/src/user-guide/agentchat-user-guide/magentic-one.md@@ -121,11 +121,23 @@ import asynciofrom autogen_ext.models.openai import OpenAIChatCompletionClientfrom autogen_ext.teams.magentic_one import MagenticOnefrom autogen_agentchat.ui import Console+from autogen_agentchat.agents import ApprovalRequest, ApprovalResponse+++def approval_func(request: ApprovalRequest) -> ApprovalResponse:+ """Simple approval function that requests user input before code execution."""+ print(f"Code to execute:\n{request.code}")+ user_input = input("Do you approve this code execution? (y/n): ").strip().lower()+ if user_input == 'y':+ return ApprovalResponse(approved=True, reason="User approved the code execution")+ else:+ return ApprovalResponse(approved=False, reason="User denied the code execution")async def example_usage():client = OpenAIChatCompletionClient(model="gpt-4o")- m1 = MagenticOne(client=client)+ # Enable code execution approval for security+ m1 = MagenticOne(client=client, approval_func=approval_func)task = "Write a Python script to fetch data from an API."result = await Console(m1.run_stream(task=task))print(result)diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/__init__.py b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/__init__.pyindex 90faeaac4..ebce7b8e3 100644--- a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/__init__.py+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/__init__.py@@ -5,7 +5,7 @@ BaseChatAgent is the base class for all agents in AgentChat.from ._assistant_agent import AssistantAgentfrom ._base_chat_agent import BaseChatAgent-from ._code_executor_agent import CodeExecutorAgent+from ._code_executor_agent import ApprovalFuncType, ApprovalRequest, ApprovalResponse, CodeExecutorAgentfrom ._message_filter_agent import MessageFilterAgent, MessageFilterConfig, PerSourceFilterfrom ._society_of_mind_agent import SocietyOfMindAgentfrom ._user_proxy_agent import UserProxyAgent@@ -19,4 +19,7 @@ __all__ = ["MessageFilterAgent","MessageFilterConfig","PerSourceFilter",+ "ApprovalRequest",+ "ApprovalResponse",+ "ApprovalFuncType",]diff --git a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_code_executor_agent.py b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_code_executor_agent.pyindex e5a2a4544..4e3fcf0e9 100644--- a/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_code_executor_agent.py+++ b/python/packages/autogen-agentchat/src/autogen_agentchat/agents/_code_executor_agent.py@@ -1,11 +1,15 @@import loggingimport re+from inspect import iscoroutinefunctionfrom typing import (AsyncGenerator,+ Awaitable,+ Callable,List,Optional,Sequence,Union,+ cast,)from autogen_core import CancellationToken, Component, ComponentModel@@ -62,6 +66,26 @@ class RetryDecision(BaseModel):retry: bool+class ApprovalRequest(BaseModel):+ """Request for approval of code execution."""++ code: str+ context: List[LLMMessage]+++class ApprovalResponse(BaseModel):+ """Response to approval request."""++ approved: bool+ reason: str+++# Type aliases for approval functions+SyncApprovalFunc = Callable[[ApprovalRequest], ApprovalResponse]+AsyncApprovalFunc = Callable[[ApprovalRequest], Awaitable[ApprovalResponse]]+ApprovalFuncType = Union[SyncApprovalFunc, AsyncApprovalFunc]++class CodeExecutorAgent(BaseChatAgent, Component[CodeExecutorAgentConfig]):"""(Experimental) An agent that generates and executes code snippets based on user instructions.@@ -113,6 +137,10 @@ class CodeExecutorAgent(BaseChatAgent, Component[CodeExecutorAgentConfig]):If the code execution fails after this number of retries, the agent will yield a reflection result.supported_languages (List[str], optional): List of programming languages that will be parsed and executed from agent response;others will be ignored. Defaults to DEFAULT_SUPPORTED_LANGUAGES.+ approval_func (Optional[Union[Callable[[ApprovalRequest], ApprovalResponse], Callable[[ApprovalRequest], Awaitable[ApprovalResponse]]]], optional): A function that is called before each code execution to get approval.+ The function takes an ApprovalRequest containing the code to be executed and the current context, and returns an ApprovalResponse.+ The function can be either synchronous or asynchronous. If None (default), all code executions are automatically approved.+ If set, the agent cannot be serialized using :meth:`~autogen_agentchat.agents.CodeExecutorAgent.dump_component`... note::@@ -139,22 +167,44 @@ class CodeExecutorAgent(BaseChatAgent, Component[CodeExecutorAgentConfig]):In this example, we show how to set up a `CodeExecutorAgent` agent that uses the:py:class:`~autogen_ext.code_executors.docker.DockerCommandLineCodeExecutor`- to execute code snippets in a Docker container. The `work_dir` parameter indicates where all executed files are first saved locally before being executed in the Docker container.+ to execute code snippets in a Docker container. The `work_dir` parameter indicates+ where all executed files are first saved locally before being executed in the Docker container... code-block:: pythonimport asyncio- from autogen_agentchat.agents import CodeExecutorAgent+ from autogen_agentchat.agents import CodeExecutorAgent, ApprovalRequest, ApprovalResponsefrom autogen_agentchat.messages import TextMessagefrom autogen_ext.code_executors.docker import DockerCommandLineCodeExecutorfrom autogen_core import CancellationToken+ def simple_approval_func(request: ApprovalRequest) -> ApprovalResponse:+ \"\"\"Simple approval function that requests user input for code execution approval.\"\"\"+ print("Code execution approval requested:")+ print("=" * 50)+ print(request.code)+ print("=" * 50)++ while True:+ user_input = input("Do you want to execute this code? (y/n): ").strip().lower()+ if user_input in ['y', 'yes']:+ return ApprovalResponse(approved=True, reason='Approved by user')+ elif user_input in ['n', 'no']:+ return ApprovalResponse(approved=False, reason='Denied by user')+ else:+ print("Please enter 'y' for yes or 'n' for no.")++async def run_code_executor_agent() -> None:# Create a code executor agent that uses a Docker container to execute code.code_executor = DockerCommandLineCodeExecutor(work_dir="coding")await code_executor.start()- code_executor_agent = CodeExecutorAgent("code_executor", code_executor=code_executor)+ code_executor_agent = CodeExecutorAgent(+ "code_executor",+ code_executor=code_executor,+ approval_func=simple_approval_func+ )# Run the agent with a given code snippet.task = TextMessage(@@ -222,7 +272,7 @@ class CodeExecutorAgent(BaseChatAgent, Component[CodeExecutorAgentConfig]):from autogen_ext.code_executors.docker import DockerCommandLineCodeExecutorfrom autogen_ext.models.openai import OpenAIChatCompletionClient- from autogen_agentchat.agents import AssistantAgent, CodeExecutorAgent+ from autogen_agentchat.agents import AssistantAgent, CodeExecutorAgent, ApprovalRequest, ApprovalResponsefrom autogen_agentchat.conditions import MaxMessageTerminationfrom autogen_agentchat.teams import RoundRobinGroupChatfrom autogen_agentchat.ui import Console@@ -230,6 +280,21 @@ class CodeExecutorAgent(BaseChatAgent, Component[CodeExecutorAgentConfig]):termination_condition = MaxMessageTermination(3)+ def group_chat_approval_func(request: ApprovalRequest) -> ApprovalResponse:+ \"\"\"Approval function for group chat that allows basic Python operations.\"\"\"+ # Allow common safe operations+ safe_operations = ["print(", "import ", "def ", "class ", "if ", "for ", "while "]+ if any(op in request.code for op in safe_operations):+ return ApprovalResponse(approved=True, reason='Safe Python operation')++ # Deny file system operations in group chat+ dangerous_operations = ["open(", "file(", "os.", "subprocess", "eval(", "exec("]+ if any(op in request.code for op in dangerous_operations):+ return ApprovalResponse(approved=False, reason='File system or dangerous operation not allowed')++ return ApprovalResponse(approved=True, reason='Operation approved')++async def main() -> None:model_client = OpenAIChatCompletionClient(model="gpt-4o")@@ -239,7 +304,11 @@ class CodeExecutorAgent(BaseChatAgent, Component[CodeExecutorAgentConfig]):# start the execution containerawait code_executor.start()- code_executor_agent = CodeExecutorAgent("code_executor_agent", code_executor=code_executor)+ code_executor_agent = CodeExecutorAgent(+ "code_executor_agent",+ code_executor=code_executor,+ approval_func=group_chat_approval_func+ )coder_agent = AssistantAgent("coder_agent", model_client=model_client)groupchat = RoundRobinGroupChat(@@ -270,7 +339,10 @@ class CodeExecutorAgent(BaseChatAgent, Component[CodeExecutorAgentConfig]):---------- code_executor_agent ----------Hello World!- In the following example, we show how to setup `CodeExecutorAgent` with `model_client` that can generate its own code without the help of any other agent and executing it in :py:class:`~autogen_ext.code_executors.docker.DockerCommandLineCodeExecutor`+ In the following example, we show how to setup `CodeExecutorAgent` with `model_client`+ that can generate its own code without the help of any other agent and executing it in+ :py:class:`~autogen_ext.code_executors.docker.DockerCommandLineCodeExecutor`.+ It also demonstrates using a model-based approval function that reviews the code for safety before execution... code-block:: python@@ -278,8 +350,9 @@ class CodeExecutorAgent(BaseChatAgent, Component[CodeExecutorAgentConfig]):from autogen_ext.code_executors.docker import DockerCommandLineCodeExecutorfrom autogen_ext.models.openai import OpenAIChatCompletionClient+ from autogen_core.models import SystemMessage, UserMessage- from autogen_agentchat.agents import CodeExecutorAgent+ from autogen_agentchat.agents import CodeExecutorAgent, ApprovalRequest, ApprovalResponsefrom autogen_agentchat.conditions import TextMessageTerminationfrom autogen_agentchat.ui import Console@@ -289,6 +362,17 @@ class CodeExecutorAgent(BaseChatAgent, Component[CodeExecutorAgentConfig]):async def main() -> None:model_client = OpenAIChatCompletionClient(model="gpt-4o")+ async def model_client_approval_func(request: ApprovalRequest) -> ApprovalResponse:+ instruction = "Approve or reject the code in the last message based on whether it is dangerous or not. Use the following JSON format for your response: {approved: true/false, reason: 'your reason here'}"+ response = await model_client.create(+ messages=[SystemMessage(content=instruction)]+ + request.context+ + [UserMessage(content=request.code, source="user")],+ json_output=ApprovalResponse,+ )+ assert isinstance(response.content, str)+ return ApprovalResponse.model_validate_json(response.content)+# define the Docker CLI Code Executorcode_executor = DockerCommandLineCodeExecutor(work_dir="coding")@@ -296,7 +380,10 @@ class CodeExecutorAgent(BaseChatAgent, Component[CodeExecutorAgentConfig]):await code_executor.start()code_executor_agent = CodeExecutorAgent(- "code_executor_agent", code_executor=code_executor, model_client=model_client+ "code_executor_agent",+ code_executor=code_executor,+ model_client=model_client,+ approval_func=model_client_approval_func,)task = "Write python code to print Hello World!"@@ -308,6 +395,7 @@ class CodeExecutorAgent(BaseChatAgent, Component[CodeExecutorAgentConfig]):asyncio.run(main())+.. code-block:: text---------- user ----------@@ -350,6 +438,7 @@ class CodeExecutorAgent(BaseChatAgent, Component[CodeExecutorAgentConfig]):system_message: str | None = DEFAULT_SYSTEM_MESSAGE,sources: Sequence[str] | None = None,supported_languages: List[str] | None = None,+ approval_func: Optional[ApprovalFuncType] = None,) -> None:if description is None:if model_client is None:@@ -362,6 +451,8 @@ class CodeExecutorAgent(BaseChatAgent, Component[CodeExecutorAgentConfig]):self._sources = sourcesself._model_client_stream = model_client_streamself._max_retries_on_error = max_retries_on_error+ self._approval_func = approval_func+ self._approval_func_is_async = approval_func is not None and iscoroutinefunction(approval_func)if supported_languages is not None:self._supported_languages = supported_languages@@ -584,6 +675,33 @@ class CodeExecutorAgent(BaseChatAgent, Component[CodeExecutorAgentConfig]):async def execute_code_block(self, code_blocks: List[CodeBlock], cancellation_token: CancellationToken) -> CodeResult:+ # Check for approval before executing code blocks+ if self._approval_func is not None:+ # Combine all code blocks into a single string for approval+ combined_code = "\n\n".join([f"```{block.language}\n{block.code}\n```" for block in code_blocks])++ # Get the current context from model_context+ context_messages = await self._model_context.get_messages()++ # Create approval request+ approval_request = ApprovalRequest(code=combined_code, context=context_messages)++ # Get approval (handle both sync and async functions)+ if self._approval_func_is_async:+ # Cast to AsyncApprovalFunc for proper typing+ async_func = cast(AsyncApprovalFunc, self._approval_func)+ approval_response = await async_func(approval_request)+ else:+ # Cast to SyncApprovalFunc for proper typing+ sync_func = cast(SyncApprovalFunc, self._approval_func)+ approval_response = sync_func(approval_request)++ # If not approved, return error result+ if not approval_response.approved:+ return CodeResult(+ exit_code=1, output=f"Code execution was not approved. Reason: {approval_response.reason}"+ )+# Execute the code blocks.result = await self._code_executor.execute_code_blocks(code_blocks, cancellation_token=cancellation_token)@@ -611,6 +729,11 @@ class CodeExecutorAgent(BaseChatAgent, Component[CodeExecutorAgentConfig]):return code_blocksdef _to_config(self) -> CodeExecutorAgentConfig:+ if self._approval_func is not None:+ raise ValueError(+ "Cannot serialize CodeExecutorAgent with approval_func set. The approval function is not serializable."+ )+return CodeExecutorAgentConfig(name=self.name,model_client=(self._model_client.dump_component() if self._model_client is not None else None),@@ -641,6 +764,7 @@ class CodeExecutorAgent(BaseChatAgent, Component[CodeExecutorAgentConfig]):model_client_stream=config.model_client_stream,model_context=ChatCompletionContext.load_component(config.model_context) if config.model_context else None,supported_languages=config.supported_languages,+ approval_func=None, # approval_func cannot be serialized, so it's always None when loading from config)@staticmethoddiff --git a/python/packages/autogen-agentchat/tests/test_code_executor_agent.py b/python/packages/autogen-agentchat/tests/test_code_executor_agent.pyindex ddfc5d45c..1ed98c89e 100644--- a/python/packages/autogen-agentchat/tests/test_code_executor_agent.py+++ b/python/packages/autogen-agentchat/tests/test_code_executor_agent.py@@ -1,5 +1,9 @@+import asyncio+from typing import List+import pytestfrom autogen_agentchat.agents import CodeExecutorAgent+from autogen_agentchat.agents._code_executor_agent import ApprovalFuncType, ApprovalRequest, ApprovalResponsefrom autogen_agentchat.base import Responsefrom autogen_agentchat.messages import (CodeExecutionEvent,@@ -7,6 +11,7 @@ from autogen_agentchat.messages import (TextMessage,)from autogen_core import CancellationToken+from autogen_core.code_executor import CodeBlockfrom autogen_core.models import ModelFamily, ModelInfofrom autogen_ext.code_executors.local import LocalCommandLineCodeExecutorfrom autogen_ext.models.replay import ReplayChatCompletionClient@@ -430,3 +435,200 @@ async def test_code_execution_agent_serialization_with_model_client() -> None:assert isinstance(deserialized_agent, CodeExecutorAgent)assert deserialized_agent.name == "code_executor_agent"assert deserialized_agent._model_client is not None # type: ignore+++# Approval function test helpers+def approval_function_allow_all(request: ApprovalRequest) -> ApprovalResponse:+ """Approval function that allows all code execution."""+ return ApprovalResponse(approved=True, reason="All code is approved")+++def approval_function_deny_dangerous(request: ApprovalRequest) -> ApprovalResponse:+ """Approval function that denies potentially dangerous code."""+ dangerous_keywords = ["rm ", "del ", "format", "delete", "DROP TABLE"]++ for keyword in dangerous_keywords:+ if keyword in request.code:+ return ApprovalResponse(approved=False, reason=f"Code contains potentially dangerous keyword: {keyword}")++ return ApprovalResponse(approved=True, reason="Code appears safe")+++def approval_function_deny_all(request: ApprovalRequest) -> ApprovalResponse:+ """Approval function that denies all code execution."""+ return ApprovalResponse(approved=False, reason="All code execution is denied")+++# Async approval function test helpers+async def async_approval_function_allow_all(request: ApprovalRequest) -> ApprovalResponse:+ """Async approval function that allows all code execution."""+ await asyncio.sleep(0.01) # Simulate async operation+ return ApprovalResponse(approved=True, reason="All code is approved (async)")+++async def async_approval_function_deny_dangerous(request: ApprovalRequest) -> ApprovalResponse:+ """Async approval function that denies potentially dangerous code."""+ await asyncio.sleep(0.01) # Simulate async operation+ dangerous_keywords = ["rm ", "del ", "format", "delete", "DROP TABLE"]++ for keyword in dangerous_keywords:+ if keyword in request.code:+ return ApprovalResponse(+ approved=False, reason=f"Code contains potentially dangerous keyword: {keyword} (async)"+ )++ return ApprovalResponse(approved=True, reason="Code appears safe (async)")+++async def async_approval_function_deny_all(request: ApprovalRequest) -> ApprovalResponse:+ """Async approval function that denies all code execution."""+ await asyncio.sleep(0.01) # Simulate async operation+ return ApprovalResponse(approved=False, reason="All code execution is denied (async)")+++async def test_approval_functionality_no_approval() -> None:+ """Test that CodeExecutorAgent works without approval function (default behavior)."""+ agent = CodeExecutorAgent("test_agent", LocalCommandLineCodeExecutor())++ code_blocks = [CodeBlock(code="print('Hello World!')", language="python")]+ result = await agent.execute_code_block(code_blocks, CancellationToken())++ # Should execute successfully+ assert result.exit_code == 0+ assert "Hello World!" in result.output+++ "approval_func,code,language,expected_exit_code,expected_in_output",+ [+ (approval_function_allow_all, "print('Approved code')", "python", 0, "Approved code"),+ (approval_function_deny_dangerous, "print('Safe code')", "python", 0, "Safe code"),+ (approval_function_deny_dangerous, "rm somefile.txt", "sh", 1, "dangerous keyword"),+ (approval_function_deny_all, "print('This should be denied')", "python", 1, "All code execution is denied"),+ ],+)+async def test_approval_functionality_sync(+ approval_func: ApprovalFuncType, code: str, language: str, expected_exit_code: int, expected_in_output: str+) -> None:+ """Test sync approval functionality with various approval functions and code samples."""+ agent = CodeExecutorAgent("test_agent", LocalCommandLineCodeExecutor(), approval_func=approval_func)++ code_blocks = [CodeBlock(code=code, language=language)]+ result = await agent.execute_code_block(code_blocks, CancellationToken())++ assert result.exit_code == expected_exit_code+ assert expected_in_output in result.output++[email protected]("is_async", [False, True])+async def test_approval_functionality_context_passed(is_async: bool) -> None:+ """Test that approval functions receive the correct context."""+ received_requests: List[ApprovalRequest] = []++ if is_async:++ async def capture_context_async(request: ApprovalRequest) -> ApprovalResponse:+ await asyncio.sleep(0.01)+ received_requests.append(request)+ return ApprovalResponse(approved=True, reason="Captured for testing (async)")++ agent = CodeExecutorAgent("test_agent", LocalCommandLineCodeExecutor(), approval_func=capture_context_async)+ else:++ def capture_context_sync(request: ApprovalRequest) -> ApprovalResponse:+ received_requests.append(request)+ return ApprovalResponse(approved=True, reason="Captured for testing")++ agent = CodeExecutorAgent("test_agent", LocalCommandLineCodeExecutor(), approval_func=capture_context_sync)++ code_blocks = [CodeBlock(code="print('Test context')", language="python")]+ await agent.execute_code_block(code_blocks, CancellationToken())++ # Verify the approval function was called and received the correct data+ assert len(received_requests) == 1+ request = received_requests[0]+ assert isinstance(request, ApprovalRequest)+ assert "print('Test context')" in request.code+ assert "```python" in request.code+ assert isinstance(request.context, list)+++ "approval_func",+ [approval_function_allow_all, async_approval_function_allow_all],+)+def test_approval_functionality_serialization_fails(approval_func: ApprovalFuncType) -> None:+ """Test that serialization fails when approval function is set."""+ agent = CodeExecutorAgent("test_agent", LocalCommandLineCodeExecutor(), approval_func=approval_func)++ # Should raise ValueError when trying to serialize+ with pytest.raises(ValueError, match="Cannot serialize CodeExecutorAgent with approval_func set"):+ agent.dump_component()+++def test_approval_functionality_serialization_succeeds() -> None:+ """Test that serialization succeeds when no approval function is set."""+ agent = CodeExecutorAgent("test_agent", LocalCommandLineCodeExecutor())++ # Should serialize successfully+ config = agent.dump_component()+ assert config.config["name"] == "test_agent"+++ "approval_func,async_marker",+ [+ (approval_function_deny_dangerous, ""),+ (async_approval_function_deny_dangerous, "(async)"),+ ],+)+async def test_approval_functionality_with_on_messages(approval_func: ApprovalFuncType, async_marker: str) -> None:+ """Test approval functionality works with the on_messages interface."""+ agent = CodeExecutorAgent("test_agent", LocalCommandLineCodeExecutor(), approval_func=approval_func)++ # Test with safe code+ safe_message = TextMessage(content="```python\nprint('Safe message')\n```", source="user")+ response = await agent.on_messages([safe_message], CancellationToken())+ assert isinstance(response.chat_message, TextMessage)+ assert "Safe message" in response.chat_message.content++ # Test with dangerous code+ dangerous_message = TextMessage(content="```sh\nrm -rf /\n```", source="user")+ response = await agent.on_messages([dangerous_message], CancellationToken())+ assert isinstance(response.chat_message, TextMessage)+ assert "Code execution was not approved" in response.chat_message.content+ if async_marker:+ assert async_marker in response.chat_message.content+++ "approval_func,code,language,expected_exit_code,expected_in_output",+ [+ (async_approval_function_allow_all, "print('Approved async code')", "python", 0, "Approved async code"),+ (async_approval_function_deny_dangerous, "print('Safe async code')", "python", 0, "Safe async code"),+ (async_approval_function_deny_dangerous, "rm somefile.txt", "sh", 1, "dangerous keyword"),+ (+ async_approval_function_deny_all,+ "print('This should be denied async')",+ "python",+ 1,+ "All code execution is denied (async)",+ ),+ ],+)+async def test_approval_functionality_async(+ approval_func: ApprovalFuncType, code: str, language: str, expected_exit_code: int, expected_in_output: str+) -> None:+ """Test async approval functionality with various approval functions and code samples."""+ agent = CodeExecutorAgent("test_agent", LocalCommandLineCodeExecutor(), approval_func=approval_func)++ code_blocks = [CodeBlock(code=code, language=language)]+ result = await agent.execute_code_block(code_blocks, CancellationToken())++ assert result.exit_code == expected_exit_code+ assert expected_in_output in result.outputdiff --git a/python/packages/autogen-ext/src/autogen_ext/teams/magentic_one.py b/python/packages/autogen-ext/src/autogen_ext/teams/magentic_one.pyindex 12de81328..5acc70955 100644--- a/python/packages/autogen-ext/src/autogen_ext/teams/magentic_one.py+++ b/python/packages/autogen-ext/src/autogen_ext/teams/magentic_one.py@@ -1,7 +1,7 @@import warningsfrom typing import Awaitable, Callable, List, Optional, Union-from autogen_agentchat.agents import CodeExecutorAgent, UserProxyAgent+from autogen_agentchat.agents import ApprovalFuncType, CodeExecutorAgent, UserProxyAgentfrom autogen_agentchat.base import ChatAgentfrom autogen_agentchat.teams import MagenticOneGroupChatfrom autogen_core import CancellationToken@@ -85,6 +85,9 @@ class MagenticOne(MagenticOneGroupChat):Args:client (ChatCompletionClient): The client used for model interactions.hil_mode (bool): Optional; If set to True, adds the UserProxyAgent to the list of agents.+ input_func (InputFuncType | None): Optional; Function to use for user input in human-in-the-loop mode.+ code_executor (CodeExecutor | None): Optional; Code executor to use. If None, will use Docker if available, otherwise local executor.+ approval_func (ApprovalFuncType | None): Optional; Function to approve code execution before running. If None, code will execute without approval... warning::Using Magentic-One involves interacting with a digital world designed for humans, which carries inherent risks. To minimize these risks, consider the following precautions:@@ -139,19 +142,41 @@ class MagenticOne(MagenticOneGroupChat):.. code-block:: python- # Enable human-in-the-loop mode with explicit Docker executor+ # Enable human-in-the-loop mode with explicit Docker executor and code approvalimport asynciofrom autogen_ext.models.openai import OpenAIChatCompletionClientfrom autogen_ext.teams.magentic_one import MagenticOnefrom autogen_ext.code_executors.docker import DockerCommandLineCodeExecutorfrom autogen_agentchat.ui import Console+ from autogen_agentchat.agents import ApprovalRequest, ApprovalResponse+++ def user_input_func(prompt: str) -> str:+ \"\"\"Custom input function for user interaction.\"\"\"+ return input(prompt)+++ def approval_func(request: ApprovalRequest) -> ApprovalResponse:+ \"\"\"Simple approval function that requests user input.\"\"\"+ print(f\"Code to execute:\\n{request.code}\")+ user_input = input("Do you approve this code execution? (y/n): ").strip().lower()+ if user_input == 'y':+ return ApprovalResponse(approved=True, reason=\"User approved the code execution\")+ else:+ return ApprovalResponse(approved=False, reason=\"User denied the code execution\")async def example_usage_hil():client = OpenAIChatCompletionClient(model="gpt-4o")# Explicitly specify Docker code executor for better securityasync with DockerCommandLineCodeExecutor() as code_executor:- m1 = MagenticOne(client=client, hil_mode=True, code_executor=code_executor)+ m1 = MagenticOne(+ client=client,+ hil_mode=True,+ input_func=user_input_func,+ code_executor=code_executor,+ approval_func=approval_func+ )task = "Write a Python script to fetch data from an API."result = await Console(m1.run_stream(task=task))print(result)@@ -160,6 +185,46 @@ class MagenticOne(MagenticOneGroupChat):if __name__ == "__main__":asyncio.run(example_usage_hil())++ .. code-block:: python++ # Enable code execution approval without human-in-the-loop mode+ import asyncio+ from autogen_ext.models.openai import OpenAIChatCompletionClient+ from autogen_ext.teams.magentic_one import MagenticOne+ from autogen_ext.code_executors.docker import DockerCommandLineCodeExecutor+ from autogen_agentchat.ui import Console+ from autogen_agentchat.agents import ApprovalRequest, ApprovalResponse+++ def approval_func(request: ApprovalRequest) -> ApprovalResponse:+ \"\"\"Simple approval function that requests user input.\"\"\"+ print(f\"Code to execute:\\n{request.code}\")+ user_input = input("Do you approve this code execution? (y/n): ").strip().lower()+ if user_input == 'y':+ return ApprovalResponse(approved=True, reason=\"User approved the code execution\")+ else:+ return ApprovalResponse(approved=False, reason=\"User denied the code execution\")+++ async def example_usage_with_approval():+ client = OpenAIChatCompletionClient(model="gpt-4o")+ # Use approval_func for code approval only (hil_mode=False)+ async with DockerCommandLineCodeExecutor() as code_executor:+ m1 = MagenticOne(+ client=client,+ hil_mode=False, # No human-in-the-loop for general conversation+ code_executor=code_executor,+ approval_func=approval_func # But still ask for code execution approval+ )+ task = "Write a Python script to fetch data from an API."+ result = await Console(m1.run_stream(task=task))+ print(result)+++ if __name__ == "__main__":+ asyncio.run(example_usage_with_approval())+References:.. code-block:: bibtex@@ -180,6 +245,7 @@ class MagenticOne(MagenticOneGroupChat):hil_mode: bool = False,input_func: InputFuncType | None = None,code_executor: CodeExecutor | None = None,+ approval_func: ApprovalFuncType | None = None,):self.client = clientself._validate_client_capabilities(client)@@ -195,7 +261,8 @@ class MagenticOne(MagenticOneGroupChat):fs = FileSurfer("FileSurfer", model_client=client)ws = MultimodalWebSurfer("WebSurfer", model_client=client)coder = MagenticOneCoderAgent("Coder", model_client=client)- executor = CodeExecutorAgent("ComputerTerminal", code_executor=code_executor)++ executor = CodeExecutorAgent("ComputerTerminal", code_executor=code_executor, approval_func=approval_func)agents: List[ChatAgent] = [fs, ws, coder, executor]if hil_mode:diff --git a/python/packages/autogen-ext/tests/teams/test_magentic_one.py b/python/packages/autogen-ext/tests/teams/test_magentic_one.pyindex d0c443d52..4050f5fe4 100644--- a/python/packages/autogen-ext/tests/teams/test_magentic_one.py+++ b/python/packages/autogen-ext/tests/teams/test_magentic_one.py@@ -6,6 +6,7 @@ from unittest.mock import Mock, patchimport pytestfrom autogen_agentchat.agents import CodeExecutorAgent+from autogen_agentchat.agents._code_executor_agent import ApprovalRequest, ApprovalResponsefrom autogen_core.models import ChatCompletionClientfrom autogen_ext.code_executors.local import LocalCommandLineCodeExecutorfrom autogen_ext.teams.magentic_one import MagenticOne@@ -43,6 +44,16 @@ def mock_chat_client() -> Mock:return mock_client+def approval_function_allow_all(request: ApprovalRequest) -> ApprovalResponse:+ """Test approval function that allows all code execution."""+ return ApprovalResponse(approved=True, reason="Test approval - all code allowed")+++def approval_function_deny_all(request: ApprovalRequest) -> ApprovalResponse:+ """Test approval function that denies all code execution."""+ return ApprovalResponse(approved=False, reason="Test approval - all code denied")++@pytest.mark.skipif(not docker_tests_enabled(), reason="Docker is not available")def test_magentic_one_uses_docker_by_default(mock_chat_client: Mock) -> None:"""Test that MagenticOne uses Docker code executor by default when Docker is available."""@@ -66,6 +77,36 @@ def test_magentic_one_uses_docker_by_default(mock_chat_client: Mock) -> None:DockerCommandLineCodeExecutor, # type: ignore[reportPrivateUsage]), f"Expected DockerCommandLineCodeExecutor, got {type(code_executor_agent._code_executor)}" # type: ignore[reportPrivateUsage]+ # Test that no approval function is set by default+ assert code_executor_agent._approval_func is None, "Expected no approval function by default" # type: ignore[reportPrivateUsage]++[email protected](not docker_tests_enabled(), reason="Docker is not available")+def test_magentic_one_uses_docker_with_approval_function(mock_chat_client: Mock) -> None:+ """Test that MagenticOne uses Docker code executor with approval function when provided."""+ from autogen_ext.code_executors.docker import DockerCommandLineCodeExecutor++ with warnings.catch_warnings():+ warnings.simplefilter("ignore", DeprecationWarning)++ m1 = MagenticOne(client=mock_chat_client, approval_func=approval_function_allow_all)++ # Find the CodeExecutorAgent in the participants list+ code_executor_agent = None+ for agent in m1._participants: # type: ignore[reportPrivateUsage]+ if isinstance(agent, CodeExecutorAgent):+ code_executor_agent = agent+ break++ assert code_executor_agent is not None, "CodeExecutorAgent not found"+ assert isinstance(+ code_executor_agent._code_executor, # type: ignore[reportPrivateUsage]+ DockerCommandLineCodeExecutor, # type: ignore[reportPrivateUsage]+ ), f"Expected DockerCommandLineCodeExecutor, got {type(code_executor_agent._code_executor)}" # type: ignore[reportPrivateUsage]++ # Test that approval function is set correctly+ assert code_executor_agent._approval_func is approval_function_allow_all, "Expected approval function to be set" # type: ignore[reportPrivateUsage]+def test_docker_availability_check() -> None:"""Test the Docker availability check function."""@@ -99,6 +140,48 @@ def test_magentic_one_falls_back_to_local_when_docker_unavailable(LocalCommandLineCodeExecutor, # type: ignore[reportPrivateUsage]), f"Expected LocalCommandLineCodeExecutor, got {type(code_executor_agent._code_executor)}" # type: ignore[reportPrivateUsage]+ # Test that no approval function is set by default+ assert code_executor_agent._approval_func is None, "Expected no approval function by default" # type: ignore[reportPrivateUsage]++ # Check that appropriate warnings were issued+ warning_messages = [str(warning.message) for warning in w]+ docker_warning_found = any("Docker is not available" in msg for msg in warning_messages)+ deprecated_warning_found = any(+ "Instantiating MagenticOne without a code_executor is deprecated" in msg for msg in warning_messages+ )++ assert docker_warning_found, f"Docker unavailable warning not found in: {warning_messages}"+ assert deprecated_warning_found, f"Deprecation warning not found in: {warning_messages}"+++@patch("autogen_ext.teams.magentic_one._is_docker_available")+def test_magentic_one_falls_back_to_local_with_approval_function(+ mock_docker_check: Mock, mock_chat_client: Mock+) -> None:+ """Test that MagenticOne falls back to local executor with approval function when Docker is not available."""+ mock_docker_check.return_value = False++ with warnings.catch_warnings(record=True) as w:+ warnings.simplefilter("always")++ m1 = MagenticOne(client=mock_chat_client, approval_func=approval_function_deny_all)++ # Find the CodeExecutorAgent in the participants list+ code_executor_agent = None+ for agent in m1._participants: # type: ignore[reportPrivateUsage]+ if isinstance(agent, CodeExecutorAgent):+ code_executor_agent = agent+ break++ assert code_executor_agent is not None, "CodeExecutorAgent not found"+ assert isinstance(+ code_executor_agent._code_executor, # type: ignore[reportPrivateUsage]+ LocalCommandLineCodeExecutor, # type: ignore[reportPrivateUsage]+ ), f"Expected LocalCommandLineCodeExecutor, got {type(code_executor_agent._code_executor)}" # type: ignore[reportPrivateUsage]++ # Test that approval function is set correctly+ assert code_executor_agent._approval_func is approval_function_deny_all, "Expected approval function to be set" # type: ignore[reportPrivateUsage]+# Check that appropriate warnings were issuedwarning_messages = [str(warning.message) for warning in w]docker_warning_found = any("Docker is not available" in msg for msg in warning_messages)@@ -129,6 +212,42 @@ def test_magentic_one_with_explicit_code_executor(mock_chat_client: Mock) -> Nonassert code_executor_agent is not None, "CodeExecutorAgent not found"assert code_executor_agent._code_executor is explicit_executor, "Expected the explicitly provided code executor" # type: ignore[reportPrivateUsage]+ # Test that no approval function is set by default+ assert code_executor_agent._approval_func is None, "Expected no approval function by default" # type: ignore[reportPrivateUsage]++ # No deprecation warning should be issued when explicitly providing a code executor+ warning_messages = [str(warning.message) for warning in w]+ deprecated_warning_found = any(+ "Instantiating MagenticOne without a code_executor is deprecated" in msg for msg in warning_messages+ )++ assert not deprecated_warning_found, f"Unexpected deprecation warning found: {warning_messages}"+++def test_magentic_one_with_explicit_code_executor_and_approval_function(mock_chat_client: Mock) -> None:+ """Test that MagenticOne uses the provided code executor and approval function when explicitly given."""+ explicit_executor = LocalCommandLineCodeExecutor()++ with warnings.catch_warnings(record=True) as w:+ warnings.simplefilter("always")++ m1 = MagenticOne(+ client=mock_chat_client, code_executor=explicit_executor, approval_func=approval_function_allow_all+ )++ # Find the CodeExecutorAgent in the participants list+ code_executor_agent = None+ for agent in m1._participants: # type: ignore[reportPrivateUsage]+ if isinstance(agent, CodeExecutorAgent):+ code_executor_agent = agent+ break++ assert code_executor_agent is not None, "CodeExecutorAgent not found"+ assert code_executor_agent._code_executor is explicit_executor, "Expected the explicitly provided code executor" # type: ignore[reportPrivateUsage]++ # Test that approval function is set correctly+ assert code_executor_agent._approval_func is approval_function_allow_all, "Expected approval function to be set" # type: ignore[reportPrivateUsage]+# No deprecation warning should be issued when explicitly providing a code executorwarning_messages = [str(warning.message) for warning in w]deprecated_warning_found = any(