-
Notifications
You must be signed in to change notification settings - Fork 5.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Make termination condition config declarative #4984
Draft
victordibia
wants to merge
1
commit into
main
Choose a base branch
from
agentchat_termination_config_vd
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+237
−29
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,14 +1,19 @@ | ||
import asyncio | ||
from abc import ABC, abstractmethod | ||
from typing import List, Sequence | ||
from typing import Any, List, Sequence | ||
from typing_extensions import Self | ||
|
||
from pydantic import BaseModel | ||
|
||
from ..messages import AgentEvent, ChatMessage, StopMessage | ||
from autogen_core import Component, ComponentModel, ComponentLoader | ||
|
||
|
||
class TerminatedException(BaseException): ... | ||
class TerminatedException(BaseException): | ||
... | ||
|
||
|
||
class TerminationCondition(ABC): | ||
class TerminationCondition(ABC, Component[Any]): | ||
"""A stateful condition that determines when a conversation should be terminated. | ||
A termination condition is a callable that takes a sequence of ChatMessage objects | ||
|
@@ -43,6 +48,8 @@ async def main() -> None: | |
asyncio.run(main()) | ||
""" | ||
|
||
component_type = "termination" | ||
|
||
@property | ||
@abstractmethod | ||
def terminated(self) -> bool: | ||
|
@@ -79,7 +86,15 @@ def __or__(self, other: "TerminationCondition") -> "TerminationCondition": | |
return _OrTerminationCondition(self, other) | ||
|
||
|
||
class _AndTerminationCondition(TerminationCondition): | ||
class AndTerminationConditionConfig(BaseModel): | ||
conditions: List[ComponentModel] | ||
|
||
|
||
class _AndTerminationCondition(TerminationCondition, Component[AndTerminationConditionConfig]): | ||
|
||
component_config_schema = AndTerminationConditionConfig | ||
component_type = "termination" | ||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Shall we include component override for cleaner path? |
||
def __init__(self, *conditions: TerminationCondition) -> None: | ||
self._conditions = conditions | ||
self._stop_messages: List[StopMessage] = [] | ||
|
@@ -90,7 +105,8 @@ def terminated(self) -> bool: | |
|
||
async def __call__(self, messages: Sequence[AgentEvent | ChatMessage]) -> StopMessage | None: | ||
if self.terminated: | ||
raise TerminatedException("Termination condition has already been reached.") | ||
raise TerminatedException( | ||
"Termination condition has already been reached.") | ||
# Check all remaining conditions. | ||
stop_messages = await asyncio.gather( | ||
*[condition(messages) for condition in self._conditions if not condition.terminated] | ||
|
@@ -102,17 +118,44 @@ async def __call__(self, messages: Sequence[AgentEvent | ChatMessage]) -> StopMe | |
if any(stop_message is None for stop_message in stop_messages): | ||
# If any remaining condition has not reached termination, it is not terminated. | ||
return None | ||
content = ", ".join(stop_message.content for stop_message in self._stop_messages) | ||
source = ", ".join(stop_message.source for stop_message in self._stop_messages) | ||
content = ", ".join( | ||
stop_message.content for stop_message in self._stop_messages) | ||
source = ", ".join( | ||
stop_message.source for stop_message in self._stop_messages) | ||
return StopMessage(content=content, source=source) | ||
|
||
async def reset(self) -> None: | ||
for condition in self._conditions: | ||
await condition.reset() | ||
self._stop_messages.clear() | ||
|
||
def _to_config(self) -> AndTerminationConditionConfig: | ||
"""Convert the AND termination condition to a config.""" | ||
return AndTerminationConditionConfig( | ||
conditions=[condition.dump_component() | ||
for condition in self._conditions] | ||
) | ||
|
||
@classmethod | ||
def _from_config(cls, config: AndTerminationConditionConfig) -> Self: | ||
"""Create an AND termination condition from a config.""" | ||
conditions = [ | ||
ComponentLoader.load_component( | ||
condition_model, TerminationCondition) | ||
for condition_model in config.conditions | ||
] | ||
return cls(*conditions) | ||
|
||
|
||
class OrTerminationConditionConfig(BaseModel): | ||
conditions: List[ComponentModel] | ||
"""List of termination conditions where any one being satisfied is sufficient.""" | ||
|
||
|
||
class _OrTerminationCondition(TerminationCondition, Component[OrTerminationConditionConfig]): | ||
component_config_schema = OrTerminationConditionConfig | ||
component_type = "termination" | ||
|
||
class _OrTerminationCondition(TerminationCondition): | ||
def __init__(self, *conditions: TerminationCondition) -> None: | ||
self._conditions = conditions | ||
|
||
|
@@ -122,14 +165,34 @@ def terminated(self) -> bool: | |
|
||
async def __call__(self, messages: Sequence[AgentEvent | ChatMessage]) -> StopMessage | None: | ||
if self.terminated: | ||
raise RuntimeError("Termination condition has already been reached") | ||
raise RuntimeError( | ||
"Termination condition has already been reached") | ||
stop_messages = await asyncio.gather(*[condition(messages) for condition in self._conditions]) | ||
if any(stop_message is not None for stop_message in stop_messages): | ||
content = ", ".join(stop_message.content for stop_message in stop_messages if stop_message is not None) | ||
source = ", ".join(stop_message.source for stop_message in stop_messages if stop_message is not None) | ||
content = ", ".join( | ||
stop_message.content for stop_message in stop_messages if stop_message is not None) | ||
source = ", ".join( | ||
stop_message.source for stop_message in stop_messages if stop_message is not None) | ||
return StopMessage(content=content, source=source) | ||
return None | ||
|
||
async def reset(self) -> None: | ||
for condition in self._conditions: | ||
await condition.reset() | ||
|
||
def _to_config(self) -> OrTerminationConditionConfig: | ||
"""Convert the OR termination condition to a config.""" | ||
return OrTerminationConditionConfig( | ||
conditions=[condition.dump_component() | ||
for condition in self._conditions] | ||
) | ||
|
||
@classmethod | ||
def _from_config(cls, config: OrTerminationConditionConfig) -> Self: | ||
"""Create an OR termination condition from a config.""" | ||
conditions = [ | ||
ComponentLoader.load_component( | ||
condition_model, TerminationCondition) | ||
for condition_model in config.conditions | ||
] | ||
return cls(*conditions) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I was gonna ask about this ... it leads to a flurry of pyright/mypy errors .. was not sure how to deal :) .
Also, ComponentLoader does not want an abstract class (TerminationCondition) and it will be too disruptive to make a concrete BaseTerminationCondition and then refactor the rest of the code to do this.