Skip to content

A programming framework for agentic AI

Change team one confirmation to be on executor (#595)

Jack Gerrits741ccd77ccb1
diff --git a/python/packages/team-one/examples/example.py b/python/packages/team-one/examples/example.py
index 836ae6a84..f02089b4c 100644
--- a/python/packages/team-one/examples/example.py
+++ b/python/packages/team-one/examples/example.py
@@ -6,13 +6,11 @@ The code snippets are executed inside a docker container."""
import asyncio
import logging
-from typing import Any
from autogen_core.application import SingleThreadedAgentRuntime
from autogen_core.application.logging import EVENT_LOGGER_NAME
from autogen_core.base import AgentId, AgentProxy
-from autogen_core.base.intervention import DefaultInterventionHandler, DropMessage
-from autogen_core.components.code_executor import DockerCommandLineCodeExecutor
+from autogen_core.components.code_executor import CodeBlock, DockerCommandLineCodeExecutor
from team_one.agents.coder import Coder, Executor
from team_one.agents.orchestrator import LedgerOrchestrator
from team_one.agents.user_proxy import UserProxy
@@ -20,20 +18,17 @@ from team_one.messages import RequestReplyMessage
from team_one.utils import LogHandler, create_completion_client_from_env
-class ConfirmCode(DefaultInterventionHandler):
- async def on_publish(self, message: Any, *, sender: AgentId | None) -> Any | type[DropMessage]:
- if sender is not None and sender.type == "Coder":
- print("Coder has generated the following code:")
- print(message)
- response = await asyncio.to_thread(input, "Do you want to proceed? (yes/no): ")
- if response.lower() != "yes":
- raise ValueError("User has rejected the message.")
- return message
+async def confirm_code(code: CodeBlock) -> bool:
+ response = await asyncio.to_thread(
+ input,
+ f"Executor is about to execute code (lang: {code.language}):\n{code.code}\n\nDo you want to proceed? (yes/no): ",
+ )
+ return response.lower() == "yes"
async def main() -> None:
# Create the runtime.
- runtime = SingleThreadedAgentRuntime(intervention_handlers=[ConfirmCode()])
+ runtime = SingleThreadedAgentRuntime()
async with DockerCommandLineCodeExecutor() as code_executor:
# Register agents.
@@ -43,7 +38,7 @@ async def main() -> None:
await Executor.register(
runtime,
"Executor",
- lambda: Executor("A agent for executing code", executor=code_executor),
+ lambda: Executor("A agent for executing code", executor=code_executor, confirm_execution=confirm_code),
)
executor = AgentProxy(AgentId("Executor", "default"), runtime)
diff --git a/python/packages/team-one/examples/example_coder.py b/python/packages/team-one/examples/example_coder.py
index 91c9ead2e..8ecb13014 100644
--- a/python/packages/team-one/examples/example_coder.py
+++ b/python/packages/team-one/examples/example_coder.py
@@ -6,13 +6,11 @@ round-robin orchestrator agent. The code snippets are executed inside a docker c
import asyncio
import logging
-from typing import Any
from autogen_core.application import SingleThreadedAgentRuntime
from autogen_core.application.logging import EVENT_LOGGER_NAME
from autogen_core.base import AgentId, AgentProxy
-from autogen_core.base.intervention import DefaultInterventionHandler, DropMessage
-from autogen_core.components.code_executor import DockerCommandLineCodeExecutor
+from autogen_core.components.code_executor import CodeBlock, DockerCommandLineCodeExecutor
from team_one.agents.coder import Coder, Executor
from team_one.agents.orchestrator import RoundRobinOrchestrator
from team_one.agents.user_proxy import UserProxy
@@ -20,20 +18,17 @@ from team_one.messages import RequestReplyMessage
from team_one.utils import LogHandler, create_completion_client_from_env
-class ConfirmCode(DefaultInterventionHandler):
- async def on_publish(self, message: Any, *, sender: AgentId | None) -> Any | type[DropMessage]:
- if sender is not None and sender.type == "Coder":
- print("Coder has generated the following code:")
- print(message)
- response = await asyncio.to_thread(input, "Do you want to proceed? (yes/no): ")
- if response.lower() != "yes":
- raise ValueError("User has rejected the message.")
- return message
+async def confirm_code(code: CodeBlock) -> bool:
+ response = await asyncio.to_thread(
+ input,
+ f"Executor is about to execute code (lang: {code.language}):\n{code.code}\n\nDo you want to proceed? (yes/no): ",
+ )
+ return response.lower() == "yes"
async def main() -> None:
# Create the runtime.
- runtime = SingleThreadedAgentRuntime(intervention_handlers=[ConfirmCode()])
+ runtime = SingleThreadedAgentRuntime()
async with DockerCommandLineCodeExecutor() as code_executor:
# Register agents.
@@ -43,7 +38,7 @@ async def main() -> None:
await Executor.register(
runtime,
"Executor",
- lambda: Executor("A agent for executing code", executor=code_executor),
+ lambda: Executor("A agent for executing code", executor=code_executor, confirm_execution=confirm_code),
)
executor = AgentProxy(AgentId("Executor", "default"), runtime)
diff --git a/python/packages/team-one/src/team_one/agents/coder.py b/python/packages/team-one/src/team_one/agents/coder.py
index 43b23f269..d5badcae4 100644
--- a/python/packages/team-one/src/team_one/agents/coder.py
+++ b/python/packages/team-one/src/team_one/agents/coder.py
@@ -1,5 +1,5 @@
import re
-from typing import List, Tuple, Union
+from typing import Awaitable, Callable, List, Literal, Tuple, Union
from autogen_core.base import CancellationToken
from autogen_core.components import default_subscription
@@ -54,6 +54,10 @@ Reply "TERMINATE" in the end when everything is done.""")
return "TERMINATE" in response.content, response.content
+# True if the user confirms the code, False otherwise
+ConfirmCode = Callable[[CodeBlock], Awaitable[bool]]
+
+
@default_subscription
class Executor(BaseWorker):
DEFAULT_DESCRIPTION = "A computer terminal that performs no other action than running Python scripts (provided to it quoted in ```python code blocks), or sh shell scripts (provided to it quoted in ```sh code blocks)"
@@ -64,10 +68,12 @@ class Executor(BaseWorker):
check_last_n_message: int = 5,
*,
executor: CodeExecutor,
+ confirm_execution: ConfirmCode | Literal["ACCEPT_ALL"],
) -> None:
super().__init__(description)
self._executor = executor
self._check_last_n_message = check_last_n_message
+ self._confirm_execution = confirm_execution
async def _generate_reply(self, cancellation_token: CancellationToken) -> Tuple[bool, UserContent]:
"""Respond to a reply request."""
@@ -88,18 +94,24 @@ class Executor(BaseWorker):
if code_lang == "py":
code_lang = "python"
execution_requests = [CodeBlock(code=code_block, language=code_lang)]
- result = await self._executor.execute_code_blocks(execution_requests, cancellation_token)
-
- if result.output.strip() == "":
- # Sometimes agents forget to print(). Remind the to print something
- return (
- False,
- f"The script ran but produced no output to console. The Unix exit code was: {result.exit_code}. If you were expecting output, consider revising the script to ensure content is printed to stdout.",
- )
+ if self._confirm_execution == "ACCEPT_ALL" or await self._confirm_execution(execution_requests[0]): # type: ignore
+ result = await self._executor.execute_code_blocks(execution_requests, cancellation_token)
+
+ if result.output.strip() == "":
+ # Sometimes agents forget to print(). Remind the to print something
+ return (
+ False,
+ f"The script ran but produced no output to console. The Unix exit code was: {result.exit_code}. If you were expecting output, consider revising the script to ensure content is printed to stdout.",
+ )
+ else:
+ return (
+ False,
+ f"The script ran, then exited with Unix exit code: {result.exit_code}\nIts output was:\n{result.output}",
+ )
else:
return (
False,
- f"The script ran, then exited with Unix exit code: {result.exit_code}\nIts output was:\n{result.output}",
+ "The code block was not confirmed by the user and so was not run.",
)
else:
n_messages_checked += 1