A programming framework for agentic AI
add illustrator-critics demo; handle multi-modal messages in agents; refactored examples to use Textual app; equality comparison for AgentId (#87)
Eric Zhu641d83fd10b3
diff --git a/examples/chat_room.py b/examples/chat_room.pyindex 06ac4f0ad..06eea51e3 100644--- a/examples/chat_room.py+++ b/examples/chat_room.py@@ -1,11 +1,11 @@-"""This is an example of a chat room with AI agents. It demonstrates how to use the-`TypeRoutedAgent` class to create custom agents that can use custom message types,-and interact with other using event-based messaging without an orchestrator."""-import argparseimport asyncioimport json-from dataclasses import dataclass+import logging+import os+import sys++sys.path.append(os.path.abspath(os.path.dirname(__file__)))from agnext.application import SingleThreadedAgentRuntimefrom agnext.chat.memory import BufferedChatMemory, ChatMemory@@ -14,18 +14,7 @@ from agnext.chat.utils import convert_messages_to_llm_messagesfrom agnext.components import TypeRoutedAgent, message_handlerfrom agnext.components.models import ChatCompletionClient, OpenAI, SystemMessagefrom agnext.core import AgentRuntime, CancellationToken-from colorama import Fore, Style, init---# Define a custom message type for chat room messages.-@dataclass-class ChatRoomMessage(TextMessage): # type: ignore- pass---sep = "-" * 50--init(autoreset=True)+from utils import TextualChatApp, TextualUserAgent, start_runtime# Define a custom agent that can handle chat room messages.@@ -38,7 +27,6 @@ class ChatRoomAgent(TypeRoutedAgent): # type: ignorebackground_story: str,memory: ChatMemory, # type: ignoremodel_client: ChatCompletionClient, # type: ignore- color: str = Style.RESET_ALL,) -> None: # type: ignoresuper().__init__(name, description, runtime)system_prompt = f"""Your name is {name}.@@ -58,10 +46,9 @@ Use the following JSON format to provide your thought on the latest message andself._system_messages = [SystemMessage(system_prompt)]self._memory = memoryself._client = model_client- self._color = color@message_handler() # type: ignore- async def on_chat_room_message(self, message: ChatRoomMessage, cancellation_token: CancellationToken) -> None: # type: ignore+ async def on_chat_room_message(self, message: TextMessage, cancellation_token: CancellationToken) -> None: # type: ignore# Save the message to memory as structured JSON.from_message = TextMessage(content=json.dumps({"sender": message.source, "content": message.content}), source=message.source@@ -77,7 +64,7 @@ Use the following JSON format to provide your thought on the latest message andassert isinstance(raw_response.content, str)# Save the response to memory.- await self._memory.add_message(ChatRoomMessage(source=self.metadata["name"], content=raw_response.content))+ await self._memory.add_message(TextMessage(source=self.metadata["name"], content=raw_response.content))# Parse the response.data = json.loads(raw_response.content)@@ -86,76 +73,75 @@ Use the following JSON format to provide your thought on the latest message and# Publish the response if needed.if respond is True or str(respond).lower().strip() == "true":- await self._publish_message(ChatRoomMessage(source=self.metadata["name"], content=str(response)))- print(f"{sep}\n{self._color}{self.metadata['name']}:{Style.RESET_ALL}\n{response}")+ await self._publish_message(TextMessage(source=self.metadata["name"], content=str(response)))+++class ChatRoomUserAgent(TextualUserAgent): # type: ignore+ """An agent that is used to receive messages from the runtime."""++ @message_handler # type: ignore+ async def on_chat_room_message(self, message: TextMessage, cancellation_token: CancellationToken) -> None: # type: ignore+ await self._app.post_runtime_message(message)# Define a chat room with participants -- the runtime is the chat room.-def chat_room(runtime: AgentRuntime) -> None: # type: ignore- _ = ChatRoomAgent(+def chat_room(runtime: AgentRuntime, app: TextualChatApp) -> None: # type: ignore+ _ = ChatRoomUserAgent(+ name="User",+ description="The user in the chat room.",+ runtime=runtime,+ app=app,+ )+ alice = ChatRoomAgent(name="Alice",description="Alice in the chat room.",runtime=runtime,background_story="Alice is a software engineer who loves to code.",memory=BufferedChatMemory(buffer_size=10),model_client=OpenAI(model="gpt-4-turbo"), # type: ignore- color=Fore.CYAN,)- _ = ChatRoomAgent(+ bob = ChatRoomAgent(name="Bob",description="Bob in the chat room.",runtime=runtime,background_story="Bob is a data scientist who loves to analyze data.",memory=BufferedChatMemory(buffer_size=10),model_client=OpenAI(model="gpt-4-turbo"), # type: ignore- color=Fore.GREEN,)- _ = ChatRoomAgent(+ charlie = ChatRoomAgent(name="Charlie",description="Charlie in the chat room.",runtime=runtime,background_story="Charlie is a designer who loves to create art.",memory=BufferedChatMemory(buffer_size=10),model_client=OpenAI(model="gpt-4-turbo"), # type: ignore- color=Fore.MAGENTA,)+ app.welcoming_notice = f"""Welcome to the chat room demo with the following participants:+1. π§ {alice.metadata['name']}: {alice.metadata['description']}+2. π±πΌββοΈ {bob.metadata['name']}: {bob.metadata['description']}+3. π¨πΎβ𦳠{charlie.metadata['name']}: {charlie.metadata['description']}+Each participant decides on its own whether to respond to the latest message.-async def get_user_input(prompt: str) -> str:- loop = asyncio.get_event_loop()- return await loop.run_in_executor(None, input, prompt)+You can greet the chat room by typing your first message below.+"""-async def main(user_name: str, wait_seconds: int) -> None:+async def main() -> None:runtime = SingleThreadedAgentRuntime()- chat_room(runtime)- while True:- # TODO: allow user to input at any time while runtime is running.- # Get user input and send messages to the chat room.- # TODO: use Textual to build the UI.- user_input = await get_user_input(f"{sep}\nYou:\n")- if user_input.strip():- # Publish user message if it is not empty.- await runtime.publish_message(ChatRoomMessage(source=user_name, content=user_input))- # Wait for agents to respond.- while runtime.unprocessed_messages:- await runtime.process_next()- await asyncio.sleep(wait_seconds)+ app = TextualChatApp(runtime, user_name="You")+ chat_room(runtime, app)+ asyncio.create_task(start_runtime(runtime))+ await app.run_async()if __name__ == "__main__":- parser = argparse.ArgumentParser(description="Run a chat room simulation.")- parser.add_argument(- "--user-name",- type=str,- default="Host",- help="The name of the user who is participating in the chat room.",- )- parser.add_argument(- "--wait-seconds",- type=int,- default=5,- help="The number of seconds to wait between processing messages.",- )+ parser = argparse.ArgumentParser(description="Chat room demo with self-driving AI agents.")+ parser.add_argument("--verbose", action="store_true", help="Enable verbose logging.")args = parser.parse_args()- asyncio.run(main(args.user_name, args.wait_seconds))+ if args.verbose:+ logging.basicConfig(level=logging.WARNING)+ logging.getLogger("agnext").setLevel(logging.DEBUG)+ handler = logging.FileHandler("chat_room.log")+ logging.getLogger("agnext").addHandler(handler)+ asyncio.run(main())diff --git a/examples/coder_reviewer.py b/examples/coder_reviewer.pyindex 92e9c53e3..89e407111 100644--- a/examples/coder_reviewer.py+++ b/examples/coder_reviewer.py@@ -1,15 +1,28 @@+import argparseimport asyncio+import logging+import logging.handlers+import os+import sys++sys.path.append(os.path.abspath(os.path.dirname(__file__)))from agnext.application import SingleThreadedAgentRuntimefrom agnext.chat.agents import ChatCompletionAgentfrom agnext.chat.memory import BufferedChatMemoryfrom agnext.chat.patterns import GroupChatManager-from agnext.chat.types import TextMessagefrom agnext.components.models import OpenAI, SystemMessagefrom agnext.core import AgentRuntime+from utils import TextualChatApp, TextualUserAgent, start_runtime-def coder_reviewer(runtime: AgentRuntime) -> None:+def coder_reviewer(runtime: AgentRuntime, app: TextualChatApp) -> None:+ _ = TextualUserAgent(+ name="Human",+ description="A human user that provides a problem statement.",+ runtime=runtime,+ app=app,+ )coder = ChatCompletionAgent(name="Coder",description="An agent that writes code",@@ -30,8 +43,13 @@ def coder_reviewer(runtime: AgentRuntime) -> None:system_messages=[SystemMessage("You are a code reviewer. You focus on correctness, efficiency and safety of the code.\n"- "Provide reviews only.\n"- "Output only 'APPROVE' to approve the code and end the conversation."+ "Respond using the following format:\n"+ "Code Review:\n"+ "Correctness: <Your comments>\n"+ "Efficiency: <Your comments>\n"+ "Safety: <Your comments>\n"+ "Approval: <APPROVE or REVISE>\n"+ "Suggested Changes: <Your comments>")],model_client=OpenAI(model="gpt-4-turbo"),@@ -44,24 +62,31 @@ def coder_reviewer(runtime: AgentRuntime) -> None:participants=[coder.id, reviewer.id], # The order of the participants indicates the order of speaking.memory=BufferedChatMemory(buffer_size=10),termination_word="APPROVE",- on_message_received=lambda message: print(f"{'-'*80}\n{message.source}: {message.content}"),)+ app.welcoming_notice = f"""Welcome to the coder-reviewer demo with the following roles:+1. π€ {coder.metadata['name']}: {coder.metadata['description']}+2. π§ {reviewer.metadata['name']}: {reviewer.metadata['description']}+The coder will write code to solve a problem, and the reviewer will review the code.+The conversation will end when the reviewer approves the code.+Let's get started by providing a problem statement.+"""async def main() -> None:runtime = SingleThreadedAgentRuntime()- coder_reviewer(runtime)- runtime.publish_message(- TextMessage(- content="Write a Python script that find near-duplicate paragraphs in a directory of many text files. "- "Output the file names, line numbers and the similarity score of the near-duplicate paragraphs. ",- source="Human",- )- )- # Start the runtime.- while True:- await runtime.process_next()- await asyncio.sleep(1)+ app = TextualChatApp(runtime, user_name="You")+ coder_reviewer(runtime, app)+ asyncio.create_task(start_runtime(runtime))+ await app.run_async()-asyncio.run(main())+if __name__ == "__main__":+ parser = argparse.ArgumentParser(description="Coder-reviewer pattern for code writing and review.")+ parser.add_argument("--verbose", action="store_true", help="Enable verbose logging.")+ args = parser.parse_args()+ if args.verbose:+ logging.basicConfig(level=logging.WARNING)+ logging.getLogger("agnext").setLevel(logging.DEBUG)+ handler = logging.FileHandler("coder_reviewer.log")+ logging.getLogger("agnext").addHandler(handler)+ asyncio.run(main())diff --git a/examples/illustrator_critics.py b/examples/illustrator_critics.pynew file mode 100644index 000000000..0de48efe4--- /dev/null+++ b/examples/illustrator_critics.py@@ -0,0 +1,106 @@+import argparse+import asyncio+import logging+import os+import sys++sys.path.append(os.path.abspath(os.path.dirname(__file__)))++import openai+from agnext.application import SingleThreadedAgentRuntime+from agnext.chat.agents import ChatCompletionAgent, ImageGenerationAgent+from agnext.chat.memory import BufferedChatMemory+from agnext.chat.patterns.group_chat_manager import GroupChatManager+from agnext.components.models import OpenAI, SystemMessage+from agnext.core import AgentRuntime+from utils import TextualChatApp, TextualUserAgent, start_runtime+++def illustrator_critics(runtime: AgentRuntime, app: TextualChatApp) -> str: # type: ignore+ _ = TextualUserAgent(+ name="User",+ description="A user looking for illustration.",+ runtime=runtime,+ app=app,+ )+ descriptor = ChatCompletionAgent(+ name="Descriptor",+ description="An AI agent that provides a description of the image.",+ runtime=runtime,+ system_messages=[+ SystemMessage(+ "You create short description for image. \n"+ "In this conversation, you will be given either: \n"+ "1. Request for new image. \n"+ "2. Feedback on some image created. \n"+ "In both cases, you will provide a description of a new image to be created. \n"+ "Only provide the description of the new image and nothing else. \n"+ "Be succinct and precise."+ ),+ ],+ memory=BufferedChatMemory(buffer_size=10),+ model_client=OpenAI(model="gpt-4-turbo", max_tokens=500),+ )+ illustrator = ImageGenerationAgent(+ name="Illustrator",+ description="An AI agent that generates images.",+ runtime=runtime,+ client=openai.AsyncOpenAI(),+ model="dall-e-3",+ memory=BufferedChatMemory(buffer_size=1),+ )+ critic = ChatCompletionAgent(+ name="Critic",+ description="An AI agent that provides feedback on images given user's requirements.",+ runtime=runtime,+ system_messages=[+ SystemMessage(+ "You are an expert in image understanding. \n"+ "In this conversation, you will judge an image given the description and provide feedback. \n"+ "Pay attention to the details like the spelling of words and number of objects. \n"+ "Use the following format in your response: \n"+ "Number of each object type in the image: <Type 1 (e.g., Husky Dog)>: 1, <Type 2>: 2, ...\n"+ "Feedback: <Your feedback here> \n"+ "Approval: <APPROVE or REVISE> \n"+ ),+ ],+ memory=BufferedChatMemory(buffer_size=2),+ model_client=OpenAI(model="gpt-4-turbo"),+ )+ _ = GroupChatManager(+ name="GroupChatManager",+ description="A chat manager that handles group chat.",+ runtime=runtime,+ memory=BufferedChatMemory(buffer_size=5),+ participants=[illustrator.id, critic.id, descriptor.id],+ termination_word="APPROVE",+ )++ app.welcoming_notice = f"""You are now in a group chat with the following agents:++1. π€ {descriptor.metadata['name']}: {descriptor.metadata.get('description')}+2. π€ {illustrator.metadata['name']}: {illustrator.metadata.get('description')}+3. π€ {critic.metadata['name']}: {critic.metadata.get('description')}++Provide a prompt for the illustrator to generate an image.+"""+++async def main() -> None:+ runtime = SingleThreadedAgentRuntime()+ app = TextualChatApp(runtime, user_name="You")+ illustrator_critics(runtime, app)+ asyncio.create_task(start_runtime(runtime))+ await app.run_async()+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description="Illustrator-critics pattern for image generation demo.")+ parser.add_argument("--verbose", action="store_true", help="Enable verbose logging.")+ args = parser.parse_args()+ if args.verbose:+ logging.basicConfig(level=logging.WARNING)+ logging.getLogger("agnext").setLevel(logging.DEBUG)+ handler = logging.FileHandler("illustrator_critics.log")+ logging.getLogger("agnext").addHandler(handler)+ asyncio.run(main())diff --git a/examples/software_consultancy.py b/examples/software_consultancy.pyindex 2044f743a..396d33a8e 100644--- a/examples/software_consultancy.py+++ b/examples/software_consultancy.py@@ -24,7 +24,7 @@ from agnext.chat.memory import HeadAndTailChatMemoryfrom agnext.chat.patterns.group_chat_manager import GroupChatManagerfrom agnext.components.models import OpenAI, SystemMessagefrom agnext.components.tools import FunctionTool-from agnext.core import Agent, AgentRuntime+from agnext.core import AgentRuntimefrom markdownify import markdownify # type: ignorefrom tqdm import tqdmfrom typing_extensions import Annotated@@ -102,7 +102,13 @@ async def create_image(return f"Image created and saved to {filename}."-def software_consultancy(runtime: AgentRuntime, user_agent: Agent) -> None: # type: ignore+def software_consultancy(runtime: AgentRuntime, app: TextualChatApp) -> None: # type: ignore+ user_agent = TextualUserAgent(+ name="Customer",+ description="A customer looking for help.",+ runtime=runtime,+ app=app,+ )developer = ChatCompletionAgent(name="Developer",description="A Python software developer.",@@ -229,12 +235,9 @@ def software_consultancy(runtime: AgentRuntime, user_agent: Agent) -> None: # tdescription="A group chat manager.",runtime=runtime,memory=HeadAndTailChatMemory(head_size=1, tail_size=10),- # model_client=OpenAI(model="gpt-4-turbo"),+ model_client=OpenAI(model="gpt-4-turbo"),participants=[developer.id, product_manager.id, ux_designer.id, illustrator.id, user_agent.id],)---async def main() -> None:art = r"""+----------------------------------------------------------+| ____ __ _ |@@ -250,21 +253,22 @@ async def main() -> None:| \____\___/|_| |_|___/\__,_|_|\__\__,_|_| |_|\___|\__, | || |___/ || |-+----------------------------------------------------------+| Work with a software development consultancy to create |-| your own Python application. You can start by greeting |-| the team! |+| your own Python application. You are working with a team |+| of the following agents: |+| 1. π€ Developer: A Python software developer. |+| 2. π€ ProductManager: A product manager. |+| 3. π€ UserExperienceDesigner: A user experience designer. |+| 4. π€ Illustrator: An illustrator. |+----------------------------------------------------------+"""+ app.welcoming_notice = art+++async def main() -> None:runtime = SingleThreadedAgentRuntime()- app = TextualChatApp(runtime, welcoming_notice=art, user_name="You")- user_agent = TextualUserAgent(- name="Customer",- description="A customer looking for help.",- runtime=runtime,- app=app,- )- software_consultancy(runtime, user_agent)+ app = TextualChatApp(runtime, user_name="You")+ software_consultancy(runtime, app)# Start the runtime.asyncio.create_task(start_runtime(runtime))# Start the app.@@ -272,11 +276,12 @@ async def main() -> None:if __name__ == "__main__":- description = "Work with a software development consultancy to create your own Python application."parser = argparse.ArgumentParser(description="Software consultancy demo.")parser.add_argument("--verbose", action="store_true", help="Enable verbose logging.")args = parser.parse_args()if args.verbose:logging.basicConfig(level=logging.WARNING)logging.getLogger("agnext").setLevel(logging.DEBUG)+ handler = logging.FileHandler("software_consultancy.log")+ logging.getLogger("agnext").addHandler(handler)asyncio.run(main())diff --git a/examples/utils.py b/examples/utils.pyindex ffb017485..ba463a61e 100644--- a/examples/utils.py+++ b/examples/utils.py@@ -1,28 +1,49 @@import asyncio+import randomfrom asyncio import Futurefrom agnext.application import SingleThreadedAgentRuntime-from agnext.chat.types import PublishNow, RespondNow, TextMessage, ToolApprovalRequest, ToolApprovalResponse-from agnext.components import TypeRoutedAgent, message_handler+from agnext.chat.types import (+ MultiModalMessage,+ PublishNow,+ RespondNow,+ TextMessage,+ ToolApprovalRequest,+ ToolApprovalResponse,+)+from agnext.components import Image, TypeRoutedAgent, message_handlerfrom agnext.core import AgentRuntime, CancellationTokenfrom textual.app import App, ComposeResultfrom textual.containers import ScrollableContainerfrom textual.widgets import Button, Footer, Header, Input, Markdown, Static+from textual_imageview.viewer import ImageViewer-class UserMessage(Markdown):- def on_mount(self) -> None:- self.styles.margin = 1- self.styles.padding = 1- self.styles.border = ("solid", "green")-+class ChatAppMessage(Static):+ def __init__(self, message: TextMessage | MultiModalMessage) -> None: # type: ignore+ self._message = message+ super().__init__()-class AssistantMessage(Markdown):def on_mount(self) -> None:self.styles.margin = 1self.styles.padding = 1self.styles.border = ("solid", "blue")+ def compose(self) -> ComposeResult:+ if isinstance(self._message, TextMessage):+ yield Markdown(f"{self._message.source}:")+ yield Markdown(self._message.content)+ else:+ yield Markdown(f"{self._message.source}:")+ for content in self._message.content:+ if isinstance(content, str):+ yield Markdown(content)+ elif isinstance(content, Image):+ viewer = ImageViewer(content.image)+ viewer.styles.min_width = 50+ viewer.styles.min_height = 50+ yield viewer+class WelcomeMessage(Static):def on_mount(self) -> None:@@ -68,7 +89,7 @@ class ToolApprovalRequestNotice(Static):class TextualChatApp(App): # type: ignore"""A Textual app for a chat interface."""- def __init__(self, runtime: AgentRuntime, welcoming_notice: str, user_name: str) -> None: # type: ignore+ def __init__(self, runtime: AgentRuntime, welcoming_notice: str | None = None, user_name: str = "User") -> None: # type: ignoreself._runtime = runtimeself._welcoming_notice = welcoming_noticeself._user_name = user_name@@ -81,9 +102,18 @@ class TextualChatApp(App): # type: ignoreyield ChatInput()def on_mount(self) -> None:- chat_messages = self.query_one("#chat-messages")- notice = WelcomeMessage(self._welcoming_notice, id="welcome")- chat_messages.mount(notice)+ if self._welcoming_notice is not None:+ chat_messages = self.query_one("#chat-messages")+ notice = WelcomeMessage(self._welcoming_notice, id="welcome")+ chat_messages.mount(notice)++ @property+ def welcoming_notice(self) -> str | None:+ return self._welcoming_notice++ @welcoming_notice.setter+ def welcoming_notice(self, value: str) -> None:+ self._welcoming_notice = valueasync def on_input_submitted(self, event: Input.Submitted) -> None:user_input = event.value@@ -102,16 +132,16 @@ class TextualChatApp(App): # type: ignore# Publish the user message to the runtime.await self._runtime.publish_message(TextMessage(source=self._user_name, content=user_input))- async def post_runtime_message(self, message: TextMessage) -> None: # type: ignore+ async def post_runtime_message(self, message: TextMessage | MultiModalMessage) -> None: # type: ignore"""Post a message from the agent runtime to the message list."""chat_messages = self.query_one("#chat-messages")- msg = AssistantMessage(f"{message.source}: {message.content}")+ msg = ChatAppMessage(message)chat_messages.mount(msg)msg.scroll_visible()async def handle_tool_approval_request(self, message: ToolApprovalRequest) -> ToolApprovalResponse: # type: ignorechat_messages = self.query_one("#chat-messages")- future: Future[ToolApprovalResponse] = asyncio.get_event_loop().create_future()+ future: Future[ToolApprovalResponse] = asyncio.get_event_loop().create_future() # type: ignoretool_call_approval_notice = ToolApprovalRequestNotice(message, future)chat_messages.mount(tool_call_approval_notice)tool_call_approval_notice.scroll_visible()@@ -129,6 +159,16 @@ class TextualUserAgent(TypeRoutedAgent): # type: ignoreasync def on_text_message(self, message: TextMessage, cancellation_token: CancellationToken) -> None: # type: ignoreawait self._app.post_runtime_message(message)+ @message_handler # type: ignore+ async def on_multi_modal_message(self, message: MultiModalMessage, cancellation_token: CancellationToken) -> None: # type: ignore+ # Save the message to file.+ # Generate a ramdom file name.+ for content in message.content:+ if isinstance(content, Image):+ filename = f"{self.metadata['name']}_{message.source}_{random.randbytes(16).hex()}.png"+ content.image.save(filename)+ await self._app.post_runtime_message(message)+@message_handler # type: ignoreasync def on_respond_now(self, message: RespondNow, cancellation_token: CancellationToken) -> None: # type: ignoreawait self._app.post_request_user_input_notice()diff --git a/pyproject.toml b/pyproject.tomlindex 45d117f2e..0e93dee87 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -38,6 +38,7 @@ dev = ["types-aiofiles","colorama","textual",+ "textual-imageview",]docs = ["sphinx", "furo", "sphinxcontrib-apidoc", "myst-parser"]diff --git a/src/agnext/chat/agents/__init__.py b/src/agnext/chat/agents/__init__.pyindex d7a880ce8..be8abe3af 100644--- a/src/agnext/chat/agents/__init__.py+++ b/src/agnext/chat/agents/__init__.py@@ -1,5 +1,6 @@from .chat_completion_agent import ChatCompletionAgent+from .image_generation_agent import ImageGenerationAgentfrom .oai_assistant import OpenAIAssistantAgentfrom .user_proxy import UserProxyAgent-__all__ = ["ChatCompletionAgent", "OpenAIAssistantAgent", "UserProxyAgent"]+__all__ = ["ChatCompletionAgent", "OpenAIAssistantAgent", "UserProxyAgent", "ImageGenerationAgent"]diff --git a/src/agnext/chat/agents/chat_completion_agent.py b/src/agnext/chat/agents/chat_completion_agent.pyindex d602990ec..f522a804b 100644--- a/src/agnext/chat/agents/chat_completion_agent.py+++ b/src/agnext/chat/agents/chat_completion_agent.py@@ -19,6 +19,7 @@ from ..memory import ChatMemoryfrom ..types import (FunctionCallMessage,Message,+ MultiModalMessage,PublishNow,Reset,RespondNow,@@ -82,6 +83,13 @@ class ChatCompletionAgent(TypeRoutedAgent):# Add a user message.await self._memory.add_message(message)+ @message_handler()+ async def on_multi_modal_message(self, message: MultiModalMessage, cancellation_token: CancellationToken) -> None:+ """Handle a multimodal message. This method adds the message to the memory+ and does not generate any message."""+ # Add a user message.+ await self._memory.add_message(message)+@message_handler()async def on_reset(self, message: Reset, cancellation_token: CancellationToken) -> None:"""Handle a reset message. This method clears the memory."""diff --git a/src/agnext/chat/agents/image_generation_agent.py b/src/agnext/chat/agents/image_generation_agent.pynew file mode 100644index 000000000..193f6ef6b--- /dev/null+++ b/src/agnext/chat/agents/image_generation_agent.py@@ -0,0 +1,64 @@+from typing import Literal++import openai++from ...components import (+ Image,+ TypeRoutedAgent,+ message_handler,+)+from ...core import AgentRuntime, CancellationToken+from ..memory import ChatMemory+from ..types import (+ MultiModalMessage,+ PublishNow,+ Reset,+ TextMessage,+)+++class ImageGenerationAgent(TypeRoutedAgent):+ def __init__(+ self,+ name: str,+ description: str,+ runtime: AgentRuntime,+ memory: ChatMemory,+ client: openai.AsyncClient,+ model: Literal["dall-e-2", "dall-e-3"] = "dall-e-2",+ ):+ super().__init__(name, description, runtime)+ self._client = client+ self._model = model+ self._memory = memory++ @message_handler+ async def on_text_message(self, message: TextMessage, cancellation_token: CancellationToken) -> None:+ await self._memory.add_message(message)++ @message_handler+ async def on_reset(self, message: Reset, cancellation_token: CancellationToken) -> None:+ await self._memory.clear()++ @message_handler+ async def on_publish_now(self, message: PublishNow, cancellation_token: CancellationToken) -> None:+ response = await self._generate_response(cancellation_token)+ self._publish_message(response)++ async def _generate_response(self, cancellation_token: CancellationToken) -> MultiModalMessage:+ messages = await self._memory.get_messages()+ if len(messages) == 0:+ return MultiModalMessage(+ content=["I need more information to generate an image."], source=self.metadata["name"]+ )+ prompt = ""+ for m in messages:+ assert isinstance(m, TextMessage)+ prompt += m.content + "\n"+ prompt.strip()+ response = await self._client.images.generate(model=self._model, prompt=prompt, response_format="b64_json")+ assert len(response.data) > 0 and response.data[0].b64_json is not None+ # Create a MultiModalMessage with the image.+ image = Image.from_base64(response.data[0].b64_json)+ multi_modal_message = MultiModalMessage(content=[image], source=self.metadata["name"])+ return multi_modal_messagediff --git a/src/agnext/chat/patterns/group_chat.py b/src/agnext/chat/patterns/group_chat.pydeleted file mode 100644index db8703192..000000000--- a/src/agnext/chat/patterns/group_chat.py+++ /dev/null@@ -1,84 +0,0 @@-from typing import Any, List, Protocol, Sequence--from ...components import TypeRoutedAgent, message_handler-from ...core import AgentId, AgentRuntime, CancellationToken-from ..types import Reset, RespondNow, TextMessage---class GroupChatOutput(Protocol):- def on_message_received(self, message: Any) -> None: ...-- def get_output(self) -> Any: ...-- def reset(self) -> None: ...---class GroupChat(TypeRoutedAgent):- def __init__(- self,- name: str,- description: str,- runtime: AgentRuntime,- participants: Sequence[AgentId],- num_rounds: int,- output: GroupChatOutput,- ) -> None:- self._description = description- self._participants = participants- self._num_rounds = num_rounds- self._history: List[Any] = []- self._output = output- super().__init__(name, description, runtime)-- @message_handler()- async def on_reset(self, message: Reset, cancellation_token: CancellationToken) -> None:- self._history.clear()-- @message_handler()- async def on_respond_now(self, message: RespondNow, cancellation_token: CancellationToken) -> Any:- return self._output.get_output()-- @message_handler()- async def on_text_message(self, message: TextMessage, cancellation_token: CancellationToken) -> Any:- # TODO: how should we handle the group chat receiving a message while in the middle of a conversation?- # Should this class disallow it?-- self._history.append(message)- round = 0- prev_speaker = None-- while round < self._num_rounds:- # TODO: add support for advanced speaker selection.- # Select speaker (round-robin for now).- speaker = self._participants[round % len(self._participants)]-- # Send the last message to all agents except the previous speaker.- for agent in [agent for agent in self._participants if agent is not prev_speaker]:- # TODO gather and await- _ = await self._send_message(- self._history[-1],- agent,- cancellation_token=cancellation_token,- )- # TODO handle if response is not None-- # Request the speaker to speak.- response = await self._send_message(- RespondNow(),- speaker,- cancellation_token=cancellation_token,- )-- if response is not None:- # Append the response to the history.- self._history.append(response)- self._output.on_message_received(response)-- # Increment the round.- round += 1- prev_speaker = speaker-- output = self._output.get_output()- self._output.reset()- self._history.clear()- return outputdiff --git a/src/agnext/chat/patterns/group_chat_manager.py b/src/agnext/chat/patterns/group_chat_manager.pyindex 3302ceec7..80cae0685 100644--- a/src/agnext/chat/patterns/group_chat_manager.py+++ b/src/agnext/chat/patterns/group_chat_manager.py@@ -1,3 +1,4 @@+import loggingfrom typing import Any, Callable, List, Mappingfrom ...components import TypeRoutedAgent, message_handler@@ -5,12 +6,15 @@ from ...components.models import ChatCompletionClientfrom ...core import AgentId, AgentProxy, AgentRuntime, CancellationTokenfrom ..memory import ChatMemoryfrom ..types import (+ MultiModalMessage,PublishNow,Reset,TextMessage,)from .group_chat_utils import select_speaker+logger = logging.getLogger("agnext.events")+class GroupChatManager(TypeRoutedAgent):"""An agent that manages a group chat through event-driven orchestration.@@ -19,18 +23,18 @@ class GroupChatManager(TypeRoutedAgent):name (str): The name of the agent.description (str): The description of the agent.runtime (AgentRuntime): The runtime to register the agent.- participants (List[Agent]): The list of participants in the group chat.+ participants (List[AgentId]): The list of participants in the group chat.memory (ChatMemory): The memory to store and retrieve messages.model_client (ChatCompletionClient, optional): The client to use for the model.If provided, the agent will use the model to select the next speaker.If not provided, the agent will select the next speaker from the list of participantsaccording to the order given.termination_word (str, optional): The word that terminates the group chat. Defaults to "TERMINATE".- transitions (Mapping[Agent, List[Agent]], optional): The transitions between agents.- Keys are the agents, and values are the list of agents that can follow the key agent. Defaults to {}.A+ transitions (Mapping[AgentId, List[AgentId]], optional): The transitions between agents.+ Keys are the agents, and values are the list of agents that can follow the key agent. Defaults to {}.If provided, the group chat manager will use the transitions to select the next speaker.If a transition is not provided for an agent, the choices fallback to all participants.- This setting is only used when a model client is provided.+ If no model client is provided, a transition must have a single value.on_message_received (Callable[[TextMessage], None], optional): A custom handler to call when a message is received.Defaults to None."""@@ -45,27 +49,30 @@ class GroupChatManager(TypeRoutedAgent):model_client: ChatCompletionClient | None = None,termination_word: str = "TERMINATE",transitions: Mapping[AgentId, List[AgentId]] = {},- on_message_received: Callable[[TextMessage], None] | None = None,+ on_message_received: Callable[[TextMessage | MultiModalMessage], None] | None = None,):super().__init__(name, description, runtime)self._memory = memoryself._client = model_client- self._participants = [AgentProxy(x, runtime) for x in participants]+ self._participants = participants+ self._participant_proxies = dict((p, AgentProxy(p, runtime)) for p in participants)self._termination_word = termination_wordfor key, value in transitions.items():- proxy = AgentProxy(key, runtime)if not value:# Make sure no empty transitions are provided.- raise ValueError(f"Empty transition list provided for {proxy.metadata['name']}.")- if proxy.id not in participants:+ raise ValueError(f"Empty transition list provided for {key.name}.")+ if key not in participants:# Make sure all keys are in the list of participants.- raise ValueError(f"Transition key {proxy.metadata['name']} not found in participants.")+ raise ValueError(f"Transition key {key.name} not found in participants.")for v in value:- proxy = AgentProxy(v, runtime)- if proxy.id not in participants:+ if v not in participants:# Make sure all values are in the list of participants.- raise ValueError(f"Transition value {proxy.metadata['name']} not found in participants.")- self._tranistiions = transitions+ raise ValueError(f"Transition value {v.name} not found in participants.")+ if self._client is None:+ # Make sure there is only one transition for each key if no model client is provided.+ if len(value) > 1:+ raise ValueError(f"Multiple transitions provided for {key.name} but no model client is provided.")+ self._tranistions = transitionsself._on_message_received = on_message_received@message_handler()@@ -74,15 +81,17 @@ class GroupChatManager(TypeRoutedAgent):await self._memory.clear()@message_handler()- async def on_text_message(self, message: TextMessage, cancellation_token: CancellationToken) -> None:- """Handle a text message. This method adds the message to the memory, selects the next speaker,+ async def on_new_message(+ self, message: TextMessage | MultiModalMessage, cancellation_token: CancellationToken+ ) -> None:+ """Handle a message. This method adds the message to the memory, selects the next speaker,and sends a message to the selected speaker to publish a response."""# Call the custom on_message_received handler if provided.if self._on_message_received is not None:self._on_message_received(message)- # Check if the message is the termination word.- if message.content.strip() == self._termination_word:+ # Check if the message contains the termination word.+ if isinstance(message, TextMessage) and self._termination_word in message.content:# Terminate the group chat by not selecting the next speaker.return@@ -91,33 +100,49 @@ class GroupChatManager(TypeRoutedAgent):# Get the last speaker.last_speaker_name = message.source- last_speaker_index = next(- (i for i, p in enumerate(self._participants) if p.metadata["name"] == last_speaker_name), None- )+ last_speaker_index = next((i for i, p in enumerate(self._participants) if p.name == last_speaker_name), None)- # Select speaker.- if self._client is None:- # If no model client is provided, select the next speaker from the list of participants.- if last_speaker_index is None:- # If the last speaker is not found, select the first speaker in the list.- next_speaker_index = 0+ # Get the candidates for the next speaker.+ if last_speaker_index is not None:+ logger.debug(f"Last speaker: {last_speaker_name}")+ last_speaker = self._participants[last_speaker_index]+ if self._tranistions.get(last_speaker) is not None:+ candidates = [c for c in self._participants if c in self._tranistions[last_speaker]]else:- next_speaker_index = (last_speaker_index + 1) % len(self._participants)- speaker = self._participants[next_speaker_index]+ candidates = self._participantselse:- # If a model client is provided, select the speaker based on the transitions and the model.candidates = self._participants- if last_speaker_index is not None:- last_speaker = self._participants[last_speaker_index]- if self._tranistiions.get(last_speaker.id) is not None:- candidates = [AgentProxy(x, self._runtime) for x in self._tranistiions[last_speaker.id]]- if len(candidates) == 1:- speaker = candidates[0]+ logger.debug(f"Group chat manager next speaker candidates: {[c.name for c in candidates]}")++ # Select speaker.+ if len(candidates) == 0:+ speaker = None+ elif len(candidates) == 1:+ speaker = candidates[0]+ else:+ # More than one candidate, select the next speaker.+ if self._client is None:+ # If no model client is provided, candidates must be the list of participants.+ assert candidates == self._participants+ # If no model client is provided, select the next speaker from the list of participants.+ if last_speaker_index is not None:+ next_speaker_index = (last_speaker_index + 1) % len(self._participants)+ speaker = self._participants[next_speaker_index]+ else:+ # If no last speaker, select the first speaker.+ speaker = candidates[0]else:- speaker = await select_speaker(self._memory, self._client, candidates)+ # If a model client is provided, select the speaker based on the transitions and the model.+ speaker_index = await select_speaker(+ self._memory, self._client, [self._participant_proxies[c] for c in candidates]+ )+ speaker = candidates[speaker_index]++ logger.debug(f"Group chat manager selected speaker: {speaker.name if speaker is not None else None}")- # Send the message to the selected speaker to ask it to publish a response.- await self._send_message(PublishNow(), speaker.id)+ if speaker is not None:+ # Send the message to the selected speaker to ask it to publish a response.+ await self._send_message(PublishNow(), speaker)def save_state(self) -> Mapping[str, Any]:return {diff --git a/src/agnext/chat/patterns/group_chat_utils.py b/src/agnext/chat/patterns/group_chat_utils.pyindex d480a2a89..1a3804ef2 100644--- a/src/agnext/chat/patterns/group_chat_utils.py+++ b/src/agnext/chat/patterns/group_chat_utils.py@@ -9,7 +9,7 @@ from ..memory import ChatMemoryfrom ..types import TextMessage-async def select_speaker(memory: ChatMemory, client: ChatCompletionClient, agents: List[AgentProxy]) -> AgentProxy:+async def select_speaker(memory: ChatMemory, client: ChatCompletionClient, agents: List[AgentProxy]) -> int:"""Selects the next speaker in a group chat using a ChatCompletion client."""# TODO: Handle multi-modal messages.@@ -42,9 +42,9 @@ Read the above conversation. Then select the next role from {participants} to plif len(mentions) != 1:raise ValueError(f"Expected exactly one agent to be mentioned, but got {mentions}")agent_name = list(mentions.keys())[0]- agent = next((agent for agent in agents if agent.metadata["name"] == agent_name), None)- assert agent is not None- return agent+ agent_index = next((i for i, agent in enumerate(agents) if agent.metadata["name"] == agent_name), None)+ assert agent_index is not None+ return agent_indexdef mentioned_agents(message_content: str, agents: List[AgentProxy]) -> Dict[str, int]:diff --git a/src/agnext/chat/patterns/two_agent_chat.py b/src/agnext/chat/patterns/two_agent_chat.pydeleted file mode 100644index 20aa6eaaa..000000000--- a/src/agnext/chat/patterns/two_agent_chat.py+++ /dev/null@@ -1,25 +0,0 @@-from ...core import AgentId, AgentRuntime-from .group_chat import GroupChat, GroupChatOutput---# TODO: rewrite this with a new message type calling for add to message-# history.-class TwoAgentChat(GroupChat):- def __init__(- self,- name: str,- description: str,- runtime: AgentRuntime,- first_speaker: AgentId,- second_speaker: AgentId,- num_rounds: int,- output: GroupChatOutput,- ) -> None:- super().__init__(- name,- description,- runtime,- [first_speaker, second_speaker],- num_rounds,- output,- )diff --git a/src/agnext/core/_agent_id.py b/src/agnext/core/_agent_id.pyindex a329bbcce..222bae2e4 100644--- a/src/agnext/core/_agent_id.py+++ b/src/agnext/core/_agent_id.py@@ -12,6 +12,11 @@ class AgentId:def __hash__(self) -> int:return hash((self._namespace, self._name))+ def __eq__(self, value: object) -> bool:+ if not isinstance(value, AgentId):+ return False+ return self._name == value.name and self._namespace == value.namespace+@classmethoddef from_str(cls, agent_id: str) -> Self:namespace, name = agent_id.split("/")