|
| 1 | +import asyncio |
| 2 | +from dataclasses import dataclass |
| 3 | +from typing import Any, List |
| 4 | + |
| 5 | +from agnext.application import SingleThreadedAgentRuntime |
| 6 | +from agnext.components import TypeRoutedAgent, message_handler |
| 7 | +from agnext.components.models import ( |
| 8 | + AssistantMessage, |
| 9 | + ChatCompletionClient, |
| 10 | + LLMMessage, |
| 11 | + OpenAI, |
| 12 | + SystemMessage, |
| 13 | + UserMessage, |
| 14 | +) |
| 15 | +from agnext.core import AgentId, CancellationToken |
| 16 | +from agnext.core.intervention import DefaultInterventionHandler |
| 17 | + |
| 18 | + |
| 19 | +@dataclass |
| 20 | +class Message: |
| 21 | + source: str |
| 22 | + content: str |
| 23 | + |
| 24 | + |
| 25 | +@dataclass |
| 26 | +class RequestToSpeak: |
| 27 | + pass |
| 28 | + |
| 29 | + |
| 30 | +@dataclass |
| 31 | +class Termination: |
| 32 | + pass |
| 33 | + |
| 34 | + |
| 35 | +class RoundRobinGroupChatManager(TypeRoutedAgent): |
| 36 | + def __init__( |
| 37 | + self, |
| 38 | + description: str, |
| 39 | + participants: List[AgentId], |
| 40 | + num_rounds: int, |
| 41 | + ) -> None: |
| 42 | + super().__init__(description) |
| 43 | + self._participants = participants |
| 44 | + self._num_rounds = num_rounds |
| 45 | + self._round_count = 0 |
| 46 | + |
| 47 | + @message_handler |
| 48 | + async def handle_message(self, message: Message, cancellation_token: CancellationToken) -> None: |
| 49 | + # Select the next speaker in a round-robin fashion |
| 50 | + speaker = self._participants[self._round_count % len(self._participants)] |
| 51 | + self._round_count += 1 |
| 52 | + if self._round_count == self._num_rounds * len(self._participants): |
| 53 | + # End the conversation after the specified number of rounds. |
| 54 | + self.publish_message(Termination()) |
| 55 | + return |
| 56 | + # Send a request to speak message to the selected speaker. |
| 57 | + self.send_message(RequestToSpeak(), speaker) |
| 58 | + |
| 59 | + |
| 60 | +class GroupChatParticipant(TypeRoutedAgent): |
| 61 | + def __init__( |
| 62 | + self, |
| 63 | + description: str, |
| 64 | + system_messages: List[SystemMessage], |
| 65 | + model_client: ChatCompletionClient, |
| 66 | + ) -> None: |
| 67 | + super().__init__(description) |
| 68 | + self._system_messages = system_messages |
| 69 | + self._model_client = model_client |
| 70 | + self._memory: List[Message] = [] |
| 71 | + |
| 72 | + @message_handler |
| 73 | + async def handle_message(self, message: Message, cancellation_token: CancellationToken) -> None: |
| 74 | + self._memory.append(message) |
| 75 | + |
| 76 | + @message_handler |
| 77 | + async def handle_request_to_speak(self, message: RequestToSpeak, cancellation_token: CancellationToken) -> None: |
| 78 | + # Generate a response to the last message in the memory |
| 79 | + if not self._memory: |
| 80 | + return |
| 81 | + llm_messages: List[LLMMessage] = [] |
| 82 | + for m in self._memory[-10:]: |
| 83 | + if m.source == self.metadata["name"]: |
| 84 | + llm_messages.append(AssistantMessage(content=m.content, source=self.metadata["name"])) |
| 85 | + else: |
| 86 | + llm_messages.append(UserMessage(content=m.content, source=m.source)) |
| 87 | + response = await self._model_client.create(self._system_messages + llm_messages) |
| 88 | + assert isinstance(response.content, str) |
| 89 | + speach = Message(content=response.content, source=self.metadata["name"]) |
| 90 | + self._memory.append(speach) |
| 91 | + self.publish_message(speach) |
| 92 | + |
| 93 | + |
| 94 | +class TerminationHandler(DefaultInterventionHandler): |
| 95 | + """A handler that listens for termination messages.""" |
| 96 | + |
| 97 | + def __init__(self) -> None: |
| 98 | + self._terminated = False |
| 99 | + |
| 100 | + async def on_publish(self, message: Any, *, sender: AgentId | None) -> Any: |
| 101 | + if isinstance(message, Termination): |
| 102 | + self._terminated = True |
| 103 | + return message |
| 104 | + |
| 105 | + @property |
| 106 | + def terminated(self) -> bool: |
| 107 | + return self._terminated |
| 108 | + |
| 109 | + |
| 110 | +async def main() -> None: |
| 111 | + # Create the termination handler. |
| 112 | + termination_handler = TerminationHandler() |
| 113 | + |
| 114 | + # Create the runtime. |
| 115 | + runtime = SingleThreadedAgentRuntime(intervention_handler=termination_handler) |
| 116 | + |
| 117 | + # Register the participants. |
| 118 | + agent1 = runtime.register_and_get( |
| 119 | + "DataScientist", |
| 120 | + lambda: GroupChatParticipant( |
| 121 | + description="A data scientist", |
| 122 | + system_messages=[SystemMessage("You are a data scientist.")], |
| 123 | + model_client=OpenAI(model="gpt-3.5-turbo"), |
| 124 | + ), |
| 125 | + ) |
| 126 | + agent2 = runtime.register_and_get( |
| 127 | + "Engineer", |
| 128 | + lambda: GroupChatParticipant( |
| 129 | + description="An engineer", |
| 130 | + system_messages=[SystemMessage("You are an engineer.")], |
| 131 | + model_client=OpenAI(model="gpt-3.5-turbo"), |
| 132 | + ), |
| 133 | + ) |
| 134 | + agent3 = runtime.register_and_get( |
| 135 | + "Artist", |
| 136 | + lambda: GroupChatParticipant( |
| 137 | + description="An artist", |
| 138 | + system_messages=[SystemMessage("You are an artist.")], |
| 139 | + model_client=OpenAI(model="gpt-3.5-turbo"), |
| 140 | + ), |
| 141 | + ) |
| 142 | + |
| 143 | + # Register the group chat manager. |
| 144 | + runtime.register( |
| 145 | + "GroupChatManager", |
| 146 | + lambda: RoundRobinGroupChatManager( |
| 147 | + description="A group chat manager", |
| 148 | + participants=[agent1, agent2, agent3], |
| 149 | + num_rounds=3, |
| 150 | + ), |
| 151 | + ) |
| 152 | + |
| 153 | + # Start the conversation. |
| 154 | + runtime.publish_message(Message(content="Hello, everyone!", source="Moderator"), namespace="default") |
| 155 | + |
| 156 | + # Run the runtime until termination. |
| 157 | + while not termination_handler.terminated: |
| 158 | + await runtime.process_next() |
| 159 | + |
| 160 | + |
| 161 | +if __name__ == "__main__": |
| 162 | + import logging |
| 163 | + |
| 164 | + logging.basicConfig(level=logging.WARNING) |
| 165 | + logging.getLogger("agnext").setLevel(logging.DEBUG) |
| 166 | + asyncio.run(main()) |
0 commit comments