Termination#

In the previous section, we explored how to define agents, and organize them into teams that can solve tasks by communicating (a conversation). However, conversations can go on forever, and in many cases, we need to know when to stop them. This is the role of the termination condition.

AgentChat supports several termination condition by providing a base TerminationCondition class and several implementations that inherit from it.

A termination condition is a callable that takes a sequence of ChatMessage objects since the last time the condition was called, and returns a StopMessage if the conversation should be terminated, or None otherwise. Once a termination condition has been reached, it must be reset before it can be used again.

Some important things to note about termination conditions:

  • They are stateful, and must be reset before they can be used again.

  • They can be combined using the AND and OR operators.

  • They are implemented/enforced by the team, and not by the agents. An agent may signal or request termination e.g., by sending a StopMessage, but the team is responsible for enforcing it.

To begin, let us define a simple team with only one agent and then explore how multiple termination conditions can be applied to guide the resulting behavior.

import logging

from autogen_agentchat import EVENT_LOGGER_NAME
from autogen_agentchat.agents import CodingAssistantAgent
from autogen_agentchat.logging import ConsoleLogHandler
from autogen_agentchat.task import MaxMessageTermination, StopMessageTermination
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_core.components.models import OpenAIChatCompletionClient

logger = logging.getLogger(EVENT_LOGGER_NAME)
logger.addHandler(ConsoleLogHandler())
logger.setLevel(logging.INFO)


model_client = OpenAIChatCompletionClient(
    model="gpt-4o-2024-08-06",
    temperature=1,
    # api_key="sk-...", # Optional if you have an OPENAI_API_KEY env variable set.
)

writing_assistant_agent = CodingAssistantAgent(
    name="writing_assistant_agent",
    system_message="You are a helpful assistant that solve tasks by generating text responses and code.",
    model_client=model_client,
)

round_robin_team = RoundRobinGroupChat([writing_assistant_agent])

MaxMessageTermination#

The simplest termination condition is the MaxMessageTermination condition, which terminates the conversation after a fixed number of messages.

round_robin_team = RoundRobinGroupChat([writing_assistant_agent])
round_robin_team_result = await round_robin_team.run(
    "Write a unique, Haiku about the weather in Paris", termination_condition=MaxMessageTermination(max_messages=3)
)
--------------------------------------------------------------------------- 
[2024-10-19T12:19:28.807176]:

Write a unique, Haiku about the weather in Paris
--------------------------------------------------------------------------- 
[2024-10-19T12:19:29.604935], writing_assistant_agent:

Gentle rain whispers,  
Eiffel veiled in mist’s embrace,  
Spring’s soft sigh in France.
--------------------------------------------------------------------------- 
[2024-10-19T12:19:30.168531], writing_assistant_agent:

Gentle rain whispers,  
Eiffel veiled in mist’s embrace,  
Spring’s soft sigh in France.
--------------------------------------------------------------------------- 
[2024-10-19T12:19:31.213291], writing_assistant_agent:

Gentle rain whispers,  
Eiffel veiled in mist’s embrace,  
Spring’s soft sigh in France.
--------------------------------------------------------------------------- 
[2024-10-19T12:19:31.213655], Termination:

Maximal number of messages 3 reached, current message count: 3

We see that the conversation is terminated after the specified number of messages have been sent by the agent.

StopMessageTermination#

In this scenario, the team terminates the conversation if any agent sends a StopMessage. So, when does an agent send a StopMessage? Typically, this is implemented in the on_message method of the agent, where the agent can check the incoming message and decide to send a StopMessage based on some condition.

A common pattern here is prompt the agent (or some agent participating in the conversation) to emit a specific text string in it’s response, which can be used to trigger the termination condition.

In fact, if you review the code implementation for the default CodingAssistantAgent class provided by AgentChat, you will observe two things

  • The default system_message instructs the agent to end their response with the word “terminate” if they deem the task to be completed

  • in the on_message method, the agent checks if the incoming message contains the text “terminate” and returns a StopMessage if it does.

writing_assistant_agent = CodingAssistantAgent(
    name="writing_assistant_agent",
    system_message="You are a helpful assistant that solve tasks by generating text responses and code. Respond with TERMINATE when the task is done.",
    model_client=model_client,
)


round_robin_team = RoundRobinGroupChat([writing_assistant_agent])

round_robin_team_result = await round_robin_team.run(
    "Write a unique, Haiku about the weather in Paris", termination_condition=StopMessageTermination()
)
--------------------------------------------------------------------------- 
[2024-10-19T12:19:31.218855]:

Write a unique, Haiku about the weather in Paris
--------------------------------------------------------------------------- 
[2024-10-19T12:19:31.752676], writing_assistant_agent:

Mist hugs the Eiffel,  
Soft rain kisses cobblestones,  
Autumn whispers past.  

TERMINATE
--------------------------------------------------------------------------- 
[2024-10-19T12:19:31.753265], Termination:

Stop message received