[docs]classStopMessageTermination(TerminationCondition,Component[StopMessageTerminationConfig]):"""Terminate the conversation if a StopMessage is received."""component_config_schema=StopMessageTerminationConfigcomponent_provider_override="autogen_agentchat.conditions.StopMessageTermination"def__init__(self)->None:self._terminated=False@propertydefterminated(self)->bool:returnself._terminatedasyncdef__call__(self,messages:Sequence[AgentEvent|ChatMessage])->StopMessage|None:ifself._terminated:raiseTerminatedException("Termination condition has already been reached")formessageinmessages:ifisinstance(message,StopMessage):self._terminated=TruereturnStopMessage(content="Stop message received",source="StopMessageTermination")returnNone
[docs]classMaxMessageTermination(TerminationCondition,Component[MaxMessageTerminationConfig]):"""Terminate the conversation after a maximum number of messages have been exchanged. Args: max_messages: The maximum number of messages allowed in the conversation. include_agent_event: If True, include :class:`~autogen_agentchat.messages.AgentEvent` in the message count. Otherwise, only include :class:`~autogen_agentchat.messages.ChatMessage`. Defaults to False. """component_config_schema=MaxMessageTerminationConfigcomponent_provider_override="autogen_agentchat.conditions.MaxMessageTermination"def__init__(self,max_messages:int,include_agent_event:bool=False)->None:self._max_messages=max_messagesself._message_count=0self._include_agent_event=include_agent_event@propertydefterminated(self)->bool:returnself._message_count>=self._max_messagesasyncdef__call__(self,messages:Sequence[AgentEvent|ChatMessage])->StopMessage|None:ifself.terminated:raiseTerminatedException("Termination condition has already been reached")self._message_count+=len([mforminmessagesifself._include_agent_eventorisinstance(m,BaseChatMessage)])ifself._message_count>=self._max_messages:returnStopMessage(content=f"Maximum number of messages {self._max_messages} reached, current message count: {self._message_count}",source="MaxMessageTermination",)returnNone
[docs]classTextMentionTermination(TerminationCondition,Component[TextMentionTerminationConfig]):"""Terminate the conversation if a specific text is mentioned. Args: text: The text to look for in the messages. sources: Check only messages of the specified agents for the text to look for. """component_config_schema=TextMentionTerminationConfigcomponent_provider_override="autogen_agentchat.conditions.TextMentionTermination"def__init__(self,text:str,sources:Sequence[str]|None=None)->None:self._termination_text=textself._terminated=Falseself._sources=sources@propertydefterminated(self)->bool:returnself._terminatedasyncdef__call__(self,messages:Sequence[AgentEvent|ChatMessage])->StopMessage|None:ifself._terminated:raiseTerminatedException("Termination condition has already been reached")formessageinmessages:ifself._sourcesisnotNoneandmessage.sourcenotinself._sources:continueifisinstance(message.content,str)andself._termination_textinmessage.content:self._terminated=TruereturnStopMessage(content=f"Text '{self._termination_text}' mentioned",source="TextMentionTermination")elifisinstance(message,MultiModalMessage):foriteminmessage.content:ifisinstance(item,str)andself._termination_textinitem:self._terminated=TruereturnStopMessage(content=f"Text '{self._termination_text}' mentioned",source="TextMentionTermination")returnNone
[docs]classTokenUsageTermination(TerminationCondition,Component[TokenUsageTerminationConfig]):"""Terminate the conversation if a token usage limit is reached. Args: max_total_token: The maximum total number of tokens allowed in the conversation. max_prompt_token: The maximum number of prompt tokens allowed in the conversation. max_completion_token: The maximum number of completion tokens allowed in the conversation. Raises: ValueError: If none of max_total_token, max_prompt_token, or max_completion_token is provided. """component_config_schema=TokenUsageTerminationConfigcomponent_provider_override="autogen_agentchat.conditions.TokenUsageTermination"def__init__(self,max_total_token:int|None=None,max_prompt_token:int|None=None,max_completion_token:int|None=None,)->None:ifmax_total_tokenisNoneandmax_prompt_tokenisNoneandmax_completion_tokenisNone:raiseValueError("At least one of max_total_token, max_prompt_token, or max_completion_token must be provided")self._max_total_token=max_total_tokenself._max_prompt_token=max_prompt_tokenself._max_completion_token=max_completion_tokenself._total_token_count=0self._prompt_token_count=0self._completion_token_count=0@propertydefterminated(self)->bool:return((self._max_total_tokenisnotNoneandself._total_token_count>=self._max_total_token)or(self._max_prompt_tokenisnotNoneandself._prompt_token_count>=self._max_prompt_token)or(self._max_completion_tokenisnotNoneandself._completion_token_count>=self._max_completion_token))asyncdef__call__(self,messages:Sequence[AgentEvent|ChatMessage])->StopMessage|None:ifself.terminated:raiseTerminatedException("Termination condition has already been reached")formessageinmessages:ifmessage.models_usageisnotNone:self._prompt_token_count+=message.models_usage.prompt_tokensself._completion_token_count+=message.models_usage.completion_tokensself._total_token_count+=message.models_usage.prompt_tokens+message.models_usage.completion_tokensifself.terminated:content=f"Token usage limit reached, total token count: {self._total_token_count}, prompt token count: {self._prompt_token_count}, completion token count: {self._completion_token_count}."returnStopMessage(content=content,source="TokenUsageTermination")returnNone
[docs]classHandoffTermination(TerminationCondition,Component[HandoffTerminationConfig]):"""Terminate the conversation if a :class:`~autogen_agentchat.messages.HandoffMessage` with the given target is received. Args: target (str): The target of the handoff message. """component_config_schema=HandoffTerminationConfigcomponent_provider_override="autogen_agentchat.conditions.HandoffTermination"def__init__(self,target:str)->None:self._terminated=Falseself._target=target@propertydefterminated(self)->bool:returnself._terminatedasyncdef__call__(self,messages:Sequence[AgentEvent|ChatMessage])->StopMessage|None:ifself._terminated:raiseTerminatedException("Termination condition has already been reached")formessageinmessages:ifisinstance(message,HandoffMessage)andmessage.target==self._target:self._terminated=TruereturnStopMessage(content=f"Handoff to {self._target} from {message.source} detected.",source="HandoffTermination")returnNone
[docs]classTimeoutTermination(TerminationCondition,Component[TimeoutTerminationConfig]):"""Terminate the conversation after a specified duration has passed. Args: timeout_seconds: The maximum duration in seconds before terminating the conversation. """component_config_schema=TimeoutTerminationConfigcomponent_provider_override="autogen_agentchat.conditions.TimeoutTermination"def__init__(self,timeout_seconds:float)->None:self._timeout_seconds=timeout_secondsself._start_time=time.monotonic()self._terminated=False@propertydefterminated(self)->bool:returnself._terminatedasyncdef__call__(self,messages:Sequence[AgentEvent|ChatMessage])->StopMessage|None:ifself._terminated:raiseTerminatedException("Termination condition has already been reached")if(time.monotonic()-self._start_time)>=self._timeout_seconds:self._terminated=TruereturnStopMessage(content=f"Timeout of {self._timeout_seconds} seconds reached",source="TimeoutTermination")returnNone
[docs]classExternalTermination(TerminationCondition,Component[ExternalTerminationConfig]):"""A termination condition that is externally controlled by calling the :meth:`set` method. Example: .. code-block:: python from autogen_agentchat.conditions import ExternalTermination termination = ExternalTermination() # Run the team in an asyncio task. ... # Set the termination condition externally termination.set() """component_config_schema=ExternalTerminationConfigcomponent_provider_override="autogen_agentchat.conditions.ExternalTermination"def__init__(self)->None:self._terminated=Falseself._setted=False@propertydefterminated(self)->bool:returnself._terminated
[docs]defset(self)->None:"""Set the termination condition to terminated."""self._setted=True
asyncdef__call__(self,messages:Sequence[AgentEvent|ChatMessage])->StopMessage|None:ifself._terminated:raiseTerminatedException("Termination condition has already been reached")ifself._setted:self._terminated=TruereturnStopMessage(content="External termination requested",source="ExternalTermination")returnNone
[docs]classSourceMatchTermination(TerminationCondition,Component[SourceMatchTerminationConfig]):"""Terminate the conversation after a specific source responds. Args: sources (List[str]): List of source names to terminate the conversation. Raises: TerminatedException: If the termination condition has already been reached. """component_config_schema=SourceMatchTerminationConfigcomponent_provider_override="autogen_agentchat.conditions.SourceMatchTermination"def__init__(self,sources:List[str])->None:self._sources=sourcesself._terminated=False@propertydefterminated(self)->bool:returnself._terminatedasyncdef__call__(self,messages:Sequence[AgentEvent|ChatMessage])->StopMessage|None:ifself._terminated:raiseTerminatedException("Termination condition has already been reached")ifnotmessages:returnNoneformessageinmessages:ifmessage.sourceinself._sources:self._terminated=TruereturnStopMessage(content=f"'{message.source}' answered",source="SourceMatchTermination")returnNone
classTextMessageTerminationConfig(BaseModel):"""Configuration for the TextMessageTermination termination condition."""source:str|None=None"""The source of the text message to terminate the conversation."""
[docs]classTextMessageTermination(TerminationCondition,Component[TextMessageTerminationConfig]):"""Terminate the conversation if a :class:`~autogen_agentchat.messages.TextMessage` is received. This termination condition checks for TextMessage instances in the message sequence. When a TextMessage is found, it terminates the conversation if either: - No source was specified (terminates on any TextMessage) - The message source matches the specified source Args: source (str | None, optional): The source name to match against incoming messages. If None, matches any source. Defaults to None. """component_config_schema=TextMessageTerminationConfigcomponent_provider_override="autogen_agentchat.conditions.TextMessageTermination"def__init__(self,source:str|None=None)->None:self._terminated=Falseself._source=source@propertydefterminated(self)->bool:returnself._terminatedasyncdef__call__(self,messages:Sequence[AgentEvent|ChatMessage])->StopMessage|None:ifself._terminated:raiseTerminatedException("Termination condition has already been reached")formessageinmessages:ifisinstance(message,TextMessage)and(self._sourceisNoneormessage.source==self._source):self._terminated=TruereturnStopMessage(content=f"Text message received from '{message.source}'",source="TextMessageTermination")returnNone
classFunctionCallTerminationConfig(BaseModel):"""Configuration for the :class:`FunctionCallTermination` termination condition."""function_name:str
[docs]classFunctionCallTermination(TerminationCondition,Component[FunctionCallTerminationConfig]):"""Terminate the conversation if a :class:`~autogen_core.models.FunctionExecutionResult` with a specific name was received. Args: function_name (str): The name of the function to look for in the messages. Raises: TerminatedException: If the termination condition has already been reached. """component_config_schema=FunctionCallTerminationConfig"""The schema for the component configuration."""def__init__(self,function_name:str)->None:self._terminated=Falseself._function_name=function_name@propertydefterminated(self)->bool:returnself._terminatedasyncdef__call__(self,messages:Sequence[AgentEvent|ChatMessage])->StopMessage|None:ifself._terminated:raiseTerminatedException("Termination condition has already been reached")formessageinmessages:ifisinstance(message,ToolCallExecutionEvent):forexecutioninmessage.content:ifexecution.name==self._function_name:self._terminated=TruereturnStopMessage(content=f"Function '{self._function_name}' was executed.",source="FunctionCallTermination",)returnNone