Skip to content
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
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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]):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
class TerminationCondition(ABC, Component[Any]):
class TerminationCondition(ABC, Component[BaseModel]):

Copy link
Collaborator Author

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.

 conditions = [
            ComponentLoader.load_component(
                condition_model, TerminationCondition)
            for condition_model in config.conditions
        ]

"""A stateful condition that determines when a conversation should be terminated.
A termination condition is a callable that takes a sequence of ChatMessage objects
Expand Down Expand Up @@ -43,6 +48,8 @@ async def main() -> None:
asyncio.run(main())
"""

component_type = "termination"

@property
@abstractmethod
def terminated(self) -> bool:
Expand Down Expand Up @@ -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"

Copy link
Collaborator

Choose a reason for hiding this comment

The 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] = []
Expand All @@ -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]
Expand All @@ -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

Expand All @@ -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)
Loading
Loading