Skip to main content

agentchat.groupchat

GroupChat

@dataclass
class GroupChat()

(In preview) A group chat class that contains the following data fields:

  • agents: a list of participating agents.
  • messages: a list of messages in the group chat.
  • max_round: the maximum number of rounds.
  • admin_name: the name of the admin agent if there is one. Default is "Admin". KeyBoardInterrupt will make the admin agent take over.
  • func_call_filter: whether to enforce function call filter. Default is True. When set to True and when a message is a function call suggestion, the next speaker will be chosen from an agent which contains the corresponding function name in its function_map.
  • select_speaker_message_template: customize the select speaker message (used in "auto" speaker selection), which appears first in the message context and generally includes the agent descriptions and list of agents. If the string contains "{roles}" it will replaced with the agent's and their role descriptions. If the string contains "{agentlist}" it will be replaced with a comma-separated list of agent names in square brackets. The default value is: "You are in a role play game. The following roles are available: {roles}. Read the following conversation. Then select the next role from {agentlist} to play. Only return the role."
  • select_speaker_prompt_template: customize the select speaker prompt (used in "auto" speaker selection), which appears last in the message context and generally includes the list of agents and guidance for the LLM to select the next agent. If the string contains "{agentlist}" it will be replaced with a comma-separated list of agent names in square brackets. The default value is: "Read the above conversation. Then select the next role from {agentlist} to play. Only return the role." To ignore this prompt being used, set this to None. If set to None, ensure your instructions for selecting a speaker are in the select_speaker_message_template string.
  • select_speaker_auto_multiple_template: customize the follow-up prompt used when selecting a speaker fails with a response that contains multiple agent names. This prompt guides the LLM to return just one agent name. Applies only to "auto" speaker selection method. If the string contains "{agentlist}" it will be replaced with a comma-separated list of agent names in square brackets. The default value is: "You provided more than one name in your text, please return just the name of the next speaker. To determine the speaker use these prioritised rules:
  1. If the context refers to themselves as a speaker e.g. "As the..." , choose that speaker's name
  2. If it refers to the "next" speaker name, choose that name
  3. Otherwise, choose the first provided speaker's name in the context The names are case-sensitive and should not be abbreviated or changed. Respond with ONLY the name of the speaker and DO NOT provide a reason."
  • select_speaker_auto_none_template: customize the follow-up prompt used when selecting a speaker fails with a response that contains no agent names. This prompt guides the LLM to return an agent name and provides a list of agent names. Applies only to "auto" speaker selection method. If the string contains "{agentlist}" it will be replaced with a comma-separated list of agent names in square brackets. The default value is: "You didn't choose a speaker. As a reminder, to determine the speaker use these prioritised rules:
  1. If the context refers to themselves as a speaker e.g. "As the..." , choose that speaker's name
  2. If it refers to the "next" speaker name, choose that name
  3. Otherwise, choose the first provided speaker's name in the context The names are case-sensitive and should not be abbreviated or changed. The only names that are accepted are {agentlist}. Respond with ONLY the name of the speaker and DO NOT provide a reason."
  • speaker_selection_method: the method for selecting the next speaker. Default is "auto". Could be any of the following (case insensitive), will raise ValueError if not recognized:
  • "auto": the next speaker is selected automatically by LLM.
  • "manual": the next speaker is selected manually by user input.
  • "random": the next speaker is selected randomly.
  • "round_robin": the next speaker is selected in a round robin fashion, i.e., iterating in the same order as provided in agents.
  • a customized speaker selection function (Callable): the function will be called to select the next speaker. The function should take the last speaker and the group chat as input and return one of the following:
  1. an Agent class, it must be one of the agents in the group chat.
  2. a string from ['auto', 'manual', 'random', 'round_robin'] to select a default method to use.
  3. None, which would terminate the conversation gracefully.
  • max_retries_for_selecting_speaker: the maximum number of times the speaker selection requery process will run. If, during speaker selection, multiple agent names or no agent names are returned by the LLM as the next agent, it will be queried again up to the maximum number of times until a single agent is returned or it exhausts the maximum attempts. Applies only to "auto" speaker selection method. Default is 2.
  • select_speaker_transform_messages: (optional) the message transformations to apply to the nested select speaker agent-to-agent chat messages. Takes a TransformMessages object, defaults to None and is only utilised when the speaker selection method is "auto".
  • select_speaker_auto_verbose: whether to output the select speaker responses and selections If set to True, the outputs from the two agents in the nested select speaker chat will be output, along with whether the responses were successful, or not, in selecting an agent Applies only to "auto" speaker selection method.
  • allow_repeat_speaker: whether to allow the same speaker to speak consecutively. Default is True, in which case all speakers are allowed to speak consecutively. If allow_repeat_speaker is a list of Agents, then only those listed agents are allowed to repeat. If set to False, then no speakers are allowed to repeat. allow_repeat_speaker and allowed_or_disallowed_speaker_transitions are mutually exclusive.
  • allowed_or_disallowed_speaker_transitions: dict. The keys are source agents, and the values are agents that the key agent can/can't transit to, depending on speaker_transitions_type. Default is None, which means all agents can transit to all other agents. allow_repeat_speaker and allowed_or_disallowed_speaker_transitions are mutually exclusive.
  • speaker_transitions_type: whether the speaker_transitions_type is a dictionary containing lists of allowed agents or disallowed agents. "allowed" means the allowed_or_disallowed_speaker_transitions is a dictionary containing lists of allowed agents. If set to "disallowed", then the allowed_or_disallowed_speaker_transitions is a dictionary containing lists of disallowed agents. Must be supplied if allowed_or_disallowed_speaker_transitions is not None.
  • enable_clear_history: enable possibility to clear history of messages for agents manually by providing "clear history" phrase in user prompt. This is experimental feature. See description of GroupChatManager.clear_agents_history function for more info.
  • send_introductions: send a round of introductions at the start of the group chat, so agents know who they can speak to (default: False)
  • select_speaker_auto_model_client_cls: Custom model client class for the internal speaker select agent used during 'auto' speaker selection (optional)
  • select_speaker_auto_llm_config: LLM config for the internal speaker select agent used during 'auto' speaker selection (optional)
  • role_for_select_speaker_messages: sets the role name for speaker selection when in 'auto' mode, typically 'user' or 'system'. (default: 'system') python def custom_speaker_selection_func( last_speaker: Agent, groupchat: GroupChat ) -> Union[Agent, str, None]:

agent_names

@property
def agent_names() -> List[str]

Return the names of the agents in the group chat.

reset

def reset()

Reset the group chat.

append

def append(message: Dict, speaker: Agent)

Append a message to the group chat. We cast the content to str here so that it can be managed by text-based model.

agent_by_name

def agent_by_name(name: str,
recursive: bool = False,
raise_on_name_conflict: bool = False) -> Optional[Agent]

Returns the agent with a given name. If recursive is True, it will search in nested teams.

nested_agents

def nested_agents() -> List[Agent]

Returns all agents in the group chat manager.

next_agent

def next_agent(agent: Agent, agents: Optional[List[Agent]] = None) -> Agent

Return the next agent in the list.

select_speaker_msg

def select_speaker_msg(agents: Optional[List[Agent]] = None) -> str

Return the system message for selecting the next speaker. This is always the first message in the context.

select_speaker_prompt

def select_speaker_prompt(agents: Optional[List[Agent]] = None) -> str

Return the floating system prompt selecting the next speaker. This is always the last message in the context. Will return None if the select_speaker_prompt_template is None.

introductions_msg

def introductions_msg(agents: Optional[List[Agent]] = None) -> str

Return the system message for selecting the next speaker. This is always the first message in the context.

manual_select_speaker

def manual_select_speaker(
agents: Optional[List[Agent]] = None) -> Union[Agent, None]

Manually select the next speaker.

random_select_speaker

def random_select_speaker(
agents: Optional[List[Agent]] = None) -> Union[Agent, None]

Randomly select the next speaker.

select_speaker

def select_speaker(last_speaker: Agent, selector: ConversableAgent) -> Agent

Select the next speaker (with requery).

a_select_speaker

async def a_select_speaker(last_speaker: Agent,
selector: ConversableAgent) -> Agent

Select the next speaker (with requery), asynchronously.

a_auto_select_speaker

async def a_auto_select_speaker(last_speaker: Agent,
selector: ConversableAgent,
messages: Optional[List[Dict]],
agents: Optional[List[Agent]]) -> Agent

(Asynchronous) Selects next speaker for the "auto" speaker selection method. Utilises its own two-agent chat to determine the next speaker and supports requerying.

Speaker selection for "auto" speaker selection method:

  1. Create a two-agent chat with a speaker selector agent and a speaker validator agent, like a nested chat
  2. Inject the group messages into the new chat
  3. Run the two-agent chat, evaluating the result of response from the speaker selector agent:
  • If a single agent is provided then we return it and finish. If not, we add an additional message to this nested chat in an attempt to guide the LLM to a single agent response
  1. Chat continues until a single agent is nominated or there are no more attempts left
  2. If we run out of turns and no single agent can be determined, the next speaker in the list of agents is returned

Arguments:

last_speaker Agent: The previous speaker in the group chat selector ConversableAgent: messages Optional[List[Dict]]: Current chat messages agents Optional[List[Agent]]: Valid list of agents for speaker selection

Returns:

  • Dict - a counter for mentioned agents.

GroupChatManager

class GroupChatManager(ConversableAgent)

(In preview) A chat manager agent that can manage a group chat of multiple agents.

groupchat

@property
def groupchat() -> GroupChat

Returns the group chat managed by the group chat manager.

chat_messages_for_summary

def chat_messages_for_summary(agent: Agent) -> List[Dict]

The list of messages in the group chat as a conversation to summarize. The agent is ignored.

last_speaker

@property
def last_speaker() -> Agent

Return the agent who sent the last message to group chat manager.

In a group chat, an agent will always send a message to the group chat manager, and the group chat manager will send the message to all other agents in the group chat. So, when an agent receives a message, it will always be from the group chat manager. With this property, the agent receiving the message can know who actually sent the message.

Example:

from autogen import ConversableAgent
from autogen import GroupChat, GroupChatManager


def print_messages(recipient, messages, sender, config):
# Print the message immediately
print(
f"Sender: {sender.name} | Recipient: {recipient.name} | Message: {messages[-1].get('content')}"
)
print(f"Real Sender: {sender.last_speaker.name}")
assert sender.last_speaker.name in messages[-1].get("content")
return False, None # Required to ensure the agent communication flow continues


agent_a = ConversableAgent("agent A", default_auto_reply="I'm agent A.")
agent_b = ConversableAgent("agent B", default_auto_reply="I'm agent B.")
agent_c = ConversableAgent("agent C", default_auto_reply="I'm agent C.")
for agent in [agent_a, agent_b, agent_c]:
agent.register_reply(
[ConversableAgent, None], reply_func=print_messages, config=None
)
group_chat = GroupChat(
[agent_a, agent_b, agent_c],
messages=[],
max_round=6,
speaker_selection_method="random",
allow_repeat_speaker=True,
)
chat_manager = GroupChatManager(group_chat)
groupchat_result = agent_a.initiate_chat(
chat_manager, message="Hi, there, I'm agent A."
)

run_chat

def run_chat(messages: Optional[List[Dict]] = None,
sender: Optional[Agent] = None,
config: Optional[GroupChat] = None) -> Tuple[bool, Optional[str]]

Run a group chat.

a_run_chat

async def a_run_chat(messages: Optional[List[Dict]] = None,
sender: Optional[Agent] = None,
config: Optional[GroupChat] = None)

Run a group chat asynchronously.

resume

def resume(messages: Union[List[Dict], str],
remove_termination_string: Union[str, Callable[[str], str]] = None,
silent: Optional[bool] = False) -> Tuple[ConversableAgent, Dict]

Resumes a group chat using the previous messages as a starting point. Requires the agents, group chat, and group chat manager to be established as per the original group chat.

Arguments:

  • messages Union[List[Dict], str]: The content of the previous chat's messages, either as a Json string or a list of message dictionaries.
  • remove_termination_string (str or function): Remove the termination string from the last message to prevent immediate termination If a string is provided, this string will be removed from last message. If a function is provided, the last message will be passed to this function.
  • silent (bool or None): (Experimental) whether to print the messages for this conversation. Default is False.

Returns:

  • Tuple[ConversableAgent, Dict]: A tuple containing the last agent who spoke and their message

a_resume

async def a_resume(
messages: Union[List[Dict], str],
remove_termination_string: Union[str, Callable[[str], str]] = None,
silent: Optional[bool] = False) -> Tuple[ConversableAgent, Dict]

Resumes a group chat using the previous messages as a starting point, asynchronously. Requires the agents, group chat, and group chat manager to be established as per the original group chat.

Arguments:

  • messages Union[List[Dict], str]: The content of the previous chat's messages, either as a Json string or a list of message dictionaries.
  • remove_termination_string (str or function): Remove the termination string from the last message to prevent immediate termination If a string is provided, this string will be removed from last message. If a function is provided, the last message will be passed to this function, and the function returns the string after processing.
  • silent (bool or None): (Experimental) whether to print the messages for this conversation. Default is False.

Returns:

  • Tuple[ConversableAgent, Dict]: A tuple containing the last agent who spoke and their message

messages_from_string

def messages_from_string(message_string: str) -> List[Dict]

Reads the saved state of messages in Json format for resume and returns as a messages list

args:

  • message_string: Json string, the saved state

returns:

  • List[Dict]: List of messages

messages_to_string

def messages_to_string(messages: List[Dict]) -> str

Converts the provided messages into a Json string that can be used for resuming the chat. The state is made up of a list of messages

args:

  • messages (List[Dict]): set of messages to convert to a string

returns:

  • str: Json representation of the messages which can be persisted for resuming later

clear_agents_history

def clear_agents_history(reply: dict, groupchat: GroupChat) -> str

Clears history of messages for all agents or selected one. Can preserve selected number of last messages. That function is called when user manually provide "clear history" phrase in his reply. When "clear history" is provided, the history of messages for all agents is cleared. When "clear history <agent_name>" is provided, the history of messages for selected agent is cleared. When "clear history <nr_of_messages_to_preserve>" is provided, the history of messages for all agents is cleared except last <nr_of_messages_to_preserve> messages. When "clear history <agent_name> <nr_of_messages_to_preserve>" is provided, the history of messages for selected agent is cleared except last <nr_of_messages_to_preserve> messages. Phrase "clear history" and optional arguments are cut out from the reply before it passed to the chat.

Arguments:

  • reply dict - reply message dict to analyze.
  • groupchat GroupChat - GroupChat object.