-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
Copy pathagent_group_chat.py
135 lines (104 loc) · 4.84 KB
/
agent_group_chat.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# Copyright (c) Microsoft. All rights reserved.
import logging
from collections.abc import AsyncIterable
from typing import Any
from pydantic import Field
from semantic_kernel.agents import Agent, AgentChat
from semantic_kernel.agents.strategies import (
DefaultTerminationStrategy,
SequentialSelectionStrategy,
)
from semantic_kernel.agents.strategies.selection.selection_strategy import SelectionStrategy
from semantic_kernel.agents.strategies.termination.termination_strategy import TerminationStrategy
from semantic_kernel.contents.chat_message_content import ChatMessageContent
from semantic_kernel.contents.utils.author_role import AuthorRole
from semantic_kernel.exceptions.agent_exceptions import AgentChatException
logger: logging.Logger = logging.getLogger(__name__)
class AgentGroupChat(AgentChat):
"""An agent chat that supports multi-turn interactions."""
agent_ids: set[str]
agents: list[Agent] = Field(default_factory=list)
is_complete: bool = False
termination_strategy: TerminationStrategy = Field(default_factory=DefaultTerminationStrategy)
selection_strategy: SelectionStrategy = Field(default_factory=SequentialSelectionStrategy)
def __init__(
self,
agents: list[Agent] | None = None,
termination_strategy: TerminationStrategy | None = None,
selection_strategy: SelectionStrategy | None = None,
) -> None:
"""Initialize a new instance of AgentGroupChat.
Args:
agents: The agents to add to the group chat.
termination_strategy: The termination strategy to use.
selection_strategy: The selection strategy
"""
agent_ids = {agent.id for agent in agents} if agents else set()
if agents is None:
agents = []
args: dict[str, Any] = {
"agents": agents,
"agent_ids": agent_ids,
}
if termination_strategy is not None:
args["termination_strategy"] = termination_strategy
if selection_strategy is not None:
args["selection_strategy"] = selection_strategy
super().__init__(**args)
def add_agent(self, agent: Agent) -> None:
"""Add an agent to the group chat.
Args:
agent: The agent to add.
"""
if agent.id not in self.agent_ids:
self.agent_ids.add(agent.id)
self.agents.append(agent)
async def invoke_single_turn(self, agent: Agent) -> AsyncIterable[ChatMessageContent]:
"""Invoke the agent chat for a single turn.
Args:
agent: The agent to invoke.
Yields:
The chat message.
"""
async for message in self.invoke(agent, is_joining=True):
if message.role == AuthorRole.ASSISTANT:
task = self.termination_strategy.should_terminate(agent, self.history.messages)
self.is_complete = await task
yield message
async def invoke(self, agent: Agent | None = None, is_joining: bool = True) -> AsyncIterable[ChatMessageContent]:
"""Invoke the agent chat asynchronously.
Handles both group interactions and single agent interactions based on the provided arguments.
Args:
agent: The agent to invoke. If not provided, the method processes all agents in the chat.
is_joining: Controls whether the agent joins the chat. Defaults to True.
Yields:
The chat message.
"""
if agent is not None:
if is_joining:
self.add_agent(agent)
async for message in super().invoke_agent(agent):
if message.role == AuthorRole.ASSISTANT:
task = self.termination_strategy.should_terminate(agent, self.history.messages)
self.is_complete = await task
yield message
return
if self.agents is None:
raise AgentChatException("No agents are available")
if self.is_complete:
if not self.termination_strategy.automatic_reset:
raise AgentChatException("Chat is already complete")
self.is_complete = False
for _ in range(self.termination_strategy.maximum_iterations):
try:
selected_agent = await self.selection_strategy.next(self.agents, self.history.messages)
except Exception as ex:
logger.error(f"Failed to select agent: {ex}")
raise AgentChatException("Failed to select agent") from ex
async for message in super().invoke_agent(selected_agent):
if message.role == AuthorRole.ASSISTANT:
task = self.termination_strategy.should_terminate(selected_agent, self.history.messages)
self.is_complete = await task
yield message
if self.is_complete:
break