A programming framework for agentic AI
Make FileSurfer and CodeExecAgent Declarative (#5765)
Victor Dibiab8b13935c944
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 a192025c5..162217d35 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,15 +1,26 @@import refrom typing import List, Sequence-from autogen_core import CancellationToken+from autogen_core import CancellationToken, Component, ComponentModelfrom autogen_core.code_executor import CodeBlock, CodeExecutor+from pydantic import BaseModel+from typing_extensions import Selffrom ..base import Responsefrom ..messages import ChatMessage, TextMessagefrom ._base_chat_agent import BaseChatAgent-class CodeExecutorAgent(BaseChatAgent):+class CodeExecutorAgentConfig(BaseModel):+ """Configuration for CodeExecutorAgent"""++ name: str+ code_executor: ComponentModel+ description: str = "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)."+ sources: List[str] | None = None+++class CodeExecutorAgent(BaseChatAgent, Component[CodeExecutorAgentConfig]):"""An agent that extracts and executes code snippets found in received messages and returns the output.It is typically used within a team with another agent that generates code snippets to be executed.@@ -65,6 +76,9 @@ class CodeExecutorAgent(BaseChatAgent):"""+ component_config_schema = CodeExecutorAgentConfig+ component_provider_override = "autogen_agentchat.agents.CodeExecutorAgent"+def __init__(self,name: str,@@ -123,3 +137,20 @@ class CodeExecutorAgent(BaseChatAgent):code_content = match[1]code_blocks.append(CodeBlock(code=code_content, language=language))return code_blocks++ def _to_config(self) -> CodeExecutorAgentConfig:+ return CodeExecutorAgentConfig(+ name=self.name,+ code_executor=self._code_executor.dump_component(),+ description=self.description,+ sources=list(self._sources) if self._sources is not None else None,+ )++ @classmethod+ def _from_config(cls, config: CodeExecutorAgentConfig) -> Self:+ return cls(+ name=config.name,+ code_executor=CodeExecutor.load_component(config.code_executor),+ description=config.description,+ sources=config.sources,+ )diff --git a/python/packages/autogen-agentchat/tests/test_code_executor_agent.py b/python/packages/autogen-agentchat/tests/test_code_executor_agent.pyindex 89476586a..2ebf79feb 100644--- a/python/packages/autogen-agentchat/tests/test_code_executor_agent.py+++ b/python/packages/autogen-agentchat/tests/test_code_executor_agent.py@@ -164,3 +164,17 @@ print("%0.3f" % (square_root,))assert "The current time is:" in response.chat_message.contentassert "The script ran, then exited with an error (POSIX exit code: 1)" in response.chat_message.contentassert "ValueError: math domain error" in response.chat_message.content+++async def test_code_execution_agent_serialization() -> None:+ """Test agent config serialization"""++ agent = CodeExecutorAgent(name="code_executor", code_executor=LocalCommandLineCodeExecutor())++ # Serialize and deserialize the agent+ serialized_agent = agent.dump_component()+ deserialized_agent = CodeExecutorAgent.load_component(serialized_agent)++ assert isinstance(deserialized_agent, CodeExecutorAgent)+ assert deserialized_agent.name == "code_executor"diff --git a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/magentic-one.md b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/magentic-one.mdindex 194edee38..fad93f9e6 100644--- a/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/magentic-one.md+++ b/python/packages/autogen-core/docs/src/user-guide/agentchat-user-guide/magentic-one.md@@ -86,7 +86,10 @@ from autogen_ext.models.openai import OpenAIChatCompletionClientfrom autogen_agentchat.teams import MagenticOneGroupChatfrom autogen_agentchat.ui import Consolefrom autogen_ext.agents.web_surfer import MultimodalWebSurfer-+# from autogen_ext.agents.file_surfer import FileSurfer+# from autogen_ext.agents.magentic_one import MagenticOneCoderAgent+# from autogen_agentchat.agents import CodeExecutorAgent+# from autogen_ext.code_executors.local import LocalCommandLineCodeExecutorasync def main() -> None:model_client = OpenAIChatCompletionClient(model="gpt-4o")@@ -95,9 +98,16 @@ async def main() -> None:"WebSurfer",model_client=model_client,)+team = MagenticOneGroupChat([surfer], model_client=model_client)await Console(team.run_stream(task="What is the UV index in Melbourne today?"))+ # # Note: you can also use other agents in the team+ # team = MagenticOneGroupChat([surfer, file_surfer, coder, terminal], model_client=model_client)+ # file_surfer = FileSurfer( "FileSurfer",model_client=model_client)+ # coder = MagenticOneCoderAgent("Coder",model_client=model_client)+ # terminal = CodeExecutorAgent("ComputerTerminal",code_executor=LocalCommandLineCodeExecutor())+asyncio.run(main())```@@ -133,7 +143,7 @@ Magentic-One work is based on a multi-agent architecture where a lead OrchestratOverall, Magentic-One consists of the following agents:- Orchestrator: the lead agent responsible for task decomposition and planning, directing other agents in executing subtasks, tracking overall progress, and taking corrective actions as needed-- WebSurfer: This is an LLM-based agent that is proficient in commanding and managing the state of a Chromium-based web browser. With each incoming request, the WebSurfer performs an action on the browser then reports on the new state of the web page The action space of the WebSurfer includes navigation (e.g. visiting a URL, performing a web search); web page actions (e.g., clicking and typing); and reading actions (e.g., summarizing or answering questions). The WebSurfer relies on the accessibility tree of the browser and on set-of-marks prompting to perform its actions.+- WebSurfer: This is an LLM-based agent that is proficient in commanding and managing the state of a Chromium-based web browser. With each incoming request, the WebSurfer performs an action on the browser then reports on the new state of the web page The action space of the WebSurfer includes navigation (e.g. visiting a URL, performing a web search); web page actions (e.g., clicking and typing); and reading actions (e.g., summarizing or answering questions). The WebSurfer relies on the accessibility tree of the browser and on set-of-marks prompting to perform its actions.- FileSurfer: This is an LLM-based agent that commands a markdown-based file preview application to read local files of most types. The FileSurfer can also perform common navigation tasks such as listing the contents of directories and navigating a folder structure.- Coder: This is an LLM-based agent specialized through its system prompt for writing code, analyzing information collected from the other agents, or creating new artifacts.- ComputerTerminal: Finally, ComputerTerminal provides the team with access to a console shell where the Coder’s programs can be executed, and where new programming libraries can be installed.diff --git a/python/packages/autogen-ext/src/autogen_ext/agents/file_surfer/_file_surfer.py b/python/packages/autogen-ext/src/autogen_ext/agents/file_surfer/_file_surfer.pyindex 742bddc65..8ab6ff9c6 100644--- a/python/packages/autogen-ext/src/autogen_ext/agents/file_surfer/_file_surfer.py+++ b/python/packages/autogen-ext/src/autogen_ext/agents/file_surfer/_file_surfer.py@@ -10,7 +10,7 @@ from autogen_agentchat.messages import (TextMessage,)from autogen_agentchat.utils import remove_images-from autogen_core import CancellationToken, FunctionCall+from autogen_core import CancellationToken, Component, ComponentModel, FunctionCallfrom autogen_core.models import (AssistantMessage,ChatCompletionClient,@@ -18,6 +18,8 @@ from autogen_core.models import (SystemMessage,UserMessage,)+from pydantic import BaseModel+from typing_extensions import Selffrom ._markdown_file_browser import MarkdownFileBrowser@@ -31,7 +33,15 @@ from ._tool_definitions import ()-class FileSurfer(BaseChatAgent):+class FileSurferConfig(BaseModel):+ """Configuration for FileSurfer agent"""++ name: str+ model_client: ComponentModel+ description: str | None = None+++class FileSurfer(BaseChatAgent, Component[FileSurferConfig]):"""An agent, used by MagenticOne, that acts as a local file previewer. FileSurfer can open and read a variety of common file types, and can navigate the local file hierarchy.Installation:@@ -47,6 +57,9 @@ class FileSurfer(BaseChatAgent):"""+ component_config_schema = FileSurferConfig+ component_provider_override = "autogen_ext.agents.file_surfer.FileSurfer"+DEFAULT_DESCRIPTION = "An agent that can handle local files."DEFAULT_SYSTEM_MESSAGES = [@@ -180,3 +193,18 @@ class FileSurfer(BaseChatAgent):return messageselse:return remove_images(messages)++ def _to_config(self) -> FileSurferConfig:+ return FileSurferConfig(+ name=self.name,+ model_client=self._model_client.dump_component(),+ description=self.description,+ )++ @classmethod+ def _from_config(cls, config: FileSurferConfig) -> Self:+ return cls(+ name=config.name,+ model_client=ChatCompletionClient.load_component(config.model_client),+ description=config.description or cls.DEFAULT_DESCRIPTION,+ )diff --git a/python/packages/autogen-ext/src/autogen_ext/agents/magentic_one/_magentic_one_coder_agent.py b/python/packages/autogen-ext/src/autogen_ext/agents/magentic_one/_magentic_one_coder_agent.pyindex c5321c46b..60df8c5d1 100644--- a/python/packages/autogen-ext/src/autogen_ext/agents/magentic_one/_magentic_one_coder_agent.py+++ b/python/packages/autogen-ext/src/autogen_ext/agents/magentic_one/_magentic_one_coder_agent.py@@ -1,3 +1,5 @@+from typing import Any+from autogen_agentchat.agents import AssistantAgentfrom autogen_core.models import (ChatCompletionClient,@@ -23,10 +25,13 @@ class MagenticOneCoderAgent(AssistantAgent):The prompts and description are sealed, to replicate the original MagenticOne configuration. See AssistantAgent if you wish to modify these values."""+ component_provider_override = "autogen_ext.agents.magentic_one.MagenticOneCoderAgent"+def __init__(self,name: str,model_client: ChatCompletionClient,+ **kwargs: Any,):super().__init__(name,diff --git a/python/packages/autogen-ext/tests/test_filesurfer_agent.py b/python/packages/autogen-ext/tests/test_filesurfer_agent.pyindex 513a1fe84..470bb270a 100644--- a/python/packages/autogen-ext/tests/test_filesurfer_agent.py+++ b/python/packages/autogen-ext/tests/test_filesurfer_agent.py@@ -145,3 +145,22 @@ async def test_run_filesurfer(monkeypatch: pytest.MonkeyPatch) -> None:result = await agent.run(task="Please read the test directory")assert "# Index of " in result.messages[1].contentassert "test_filesurfer_agent.html" in result.messages[1].content+++async def test_file_surfer_serialization() -> None:+ """Test that FileSurfer can be serialized and deserialized properly."""+ model = "gpt-4o-2024-05-13"+ agent = FileSurfer(+ "FileSurfer",+ model_client=OpenAIChatCompletionClient(model=model, api_key=""),+ )++ # Serialize the agent+ serialized_agent = agent.dump_component()++ # Deserialize the agent+ deserialized_agent = FileSurfer.load_component(serialized_agent)++ # Check that the deserialized agent has the same attributes as the original agent+ assert isinstance(deserialized_agent, FileSurfer)