Ending a chat
There are a number of ways a chat can end:
- The maximum number of turns in a chat is reached
- An agent’s termination function passes on a received message
- An agent automatically replies a maximum number of times
- A human replies with ‘exit’ when prompted
- In a group chat, there’s no next agent
- In a swarm, transitioning to AfterWorkOption.TERMINATE
- Custom reply functions
1. Maximum turns
For GroupChat and swarm, use max_round
to set a limit on the number of replies. Each round represents an agent speaking and includes the initial message.
For initiate_chat
use max_turns
. Each turn represents a round trip of both agents speaking and includes the initial message.
2. Terminating message
Agents can check their received message for a termination condition and, if that condition returns True
, the chat will be ended. This check is carried out before they reply.
When constructing an agent, use the is_termination_msg
parameter with a Callable. To save creating a function, you can use a lambda function as in the example below.
It’s important to put the termination check on the agents that will receive the message, not the agent creating the message.
If the termination condition is met and the agent’s human_input_mode
is “ALWAYS” or ‘TERMINATE’ (ConversableAgent’s default), you will be asked for input and can decide to end the chat. If it is “NEVER” it will end immediately.
3. Number of automatic replies
A conversation can be ended when an agent has responded to another agent a certain number of times. An agent evaluates this when it is next their time to reply, not immediately after they have replied.
When constructing an agent, use the max_consecutive_auto_reply
parameter to set this.
If the agent’s human_input_mode
is “ALWAYS” or ‘TERMINATE’ (ConversableAgent’s default), you will be asked for input and can decide to end the chat. If it is “NEVER” it will end immediately.
4. Human replies with ‘exit’
During the course of the conversation, if you are prompted and reply ‘exit’, the chat will end.
5. GroupChat, no next agent
If the next agent in a GroupChat can’t be determined the chat will end.
If you are customizing the speaker selection method with a Callable, return None
to end the chat.
6. Swarm, transitioning to end the chat
In a swarm, if you transition to AfterWorkOption.TERMINATE
it will end the swarm. The default swarm-level AfterWork option is AfterWorkOption.TERMINATE
and this will apply to any agent in the swarm that doesn’t have an AfterWork hand-off specified.
Additionally, if you transition to AfterWorkOption.REVERT_TO_USER
but have not specified a user_agent
in initiate_swarm_chat
then it will end the swarm.
7. Reply functions
AG2 provides the ability to create custom reply functions for an agent using register_reply
.
In your function, return a Tuple
of True, None
to indicate that the reply is final with None
indicating there’s no reply and it should end the chat.