Skip to content

SwarmAgent

Swarm agent.

WaldiezSwarmAgent

Bases: WaldiezAgent

Swarm agent.

It extends a user agent and has swarm related parameters.

Attributes:

NameTypeDescription
agent_typeLiteral['swarm']

The agent type: 'swarm' for a swarm agent.

dataWaldiezSwarmAgentData

The swarm agent's data. See WaldiezSwarmAgentData for more info.

functions: List[str] property

Get the functions that the agent can use.

Returns:

TypeDescription
List[str]

The functions that the agent can use.

handoffs: List[Union[WaldiezSwarmOnCondition, WaldiezSwarmAfterWork]] property

Get the hand offs to register.

Returns:

TypeDescription
List[str]

The hand offs to register.

is_initial: bool property

Check if the agent is the initial agent.

Returns:

TypeDescription
bool

Whether the agent is the initial agent.

nested_chats: List[WaldiezAgentNestedChat] property

Get the nested chats.

Returns:

TypeDescription
List[WaldiezChat]

The nested chats.

update_agent_state_before_reply: List[Union[str, WaldiezSwarmUpdateSystemMessage]] property

Get the functions that update the agent's state before it replies.

Returns:

TypeDescription
List[str]

The functions that update the agent's state before it replies.

Swarm agent data.

WaldiezSwarmAgentData

Bases: WaldiezAgentData

Swarm agent data.

Attributes:

NameTypeDescription
is_initialbool

Whether the agent is the initial agent.

functionsList[str]

A list of functions (skill ids) to register with the agent.

update_agent_state_before_replyList[str]

A list of functions, including UpdateSystemMessage, called to update the agent's state before it replies. Each function is called when the agent is selected and before it speaks.

handoffsList[Union[WaldiezSwarmOnCondition, WaldiezSwarmAfterWork]]

A list of hand offs to register.

Notes

Each agent should have at most one AfterWork and (if any) it should be at the end the list of hand offs.

validate_handoffs() -> Self

Validate the hand offs.

Returns:

TypeDescription
Self

The swarm agent data.

Raises:

TypeDescription
ValueError

If there are more than one AfterWorks.

Source code in waldiez/models/agents/swarm_agent/swarm_agent_data.py
@model_validator(mode="after")
def validate_handoffs(self) -> Self:
    """Validate the hand offs.

    Returns
    -------
    Self
        The swarm agent data.

    Raises
    ------
    ValueError
        If there are more than one `AfterWork`s.
    """
    after_works: List[WaldiezSwarmAfterWork] = [
        hand_off
        for hand_off in self.handoffs
        if isinstance(hand_off, WaldiezSwarmAfterWork)
    ]
    if len(after_works) > 1:
        raise ValueError(
            "Each agent should have at most one `AfterWork` "
            "and (if any) it should be at the end of the list."
        )
    on_conditions: List[WaldiezSwarmOnCondition] = [
        hand_off
        for hand_off in self.handoffs
        if isinstance(hand_off, WaldiezSwarmOnCondition)
    ]
    on_conditions = sorted(on_conditions, key=lambda x: x.target.order)
    handoffs = on_conditions + after_works
    self.handoffs = handoffs
    return self

Swarm condition model for handoff.

WaldiezSwarmOnCondition

Bases: WaldiezBase

Swarm condition to handle handoff.

Attributes:

NameTypeDescription
targetWaldiezSwarmOnConditionTarget

The agent or nested chat configuration to hand off to.

target_typeLiteral['agent', 'nested_chat']

The type of the target. Can be either 'agent' or 'nested_chat'. Default is 'agent'.

conditionstr

The condition for transitioning to the target agent

available(str, optional)

Optional condition to determine if this OnCondition is available. Can be a Callable or a string. If a string, it will look up the value of the context variable with that name, which should be a bool.

available_check_typeLiteral['string', 'callable', 'none']

The type of the available property to check. Default is "none".

get_available(name_prefix: Optional[str] = None, name_suffix: Optional[str] = None) -> Tuple[str, str]

Get the available string.

Parameters:

NameTypeDescriptionDefault
name_prefixstr

The prefix to add to the function name. Default is None.

None
name_suffixstr

The suffix to add to the function name. Default is None.

None

Returns:

TypeDescription
Tuple[str, str]

The available string or function name and code if available.

Source code in waldiez/models/agents/swarm_agent/on_condition.py
def get_available(
    self,
    name_prefix: Optional[str] = None,
    name_suffix: Optional[str] = None,
) -> Tuple[str, str]:
    """Get the available string.

    Parameters
    ----------
    name_prefix : str, optional
        The prefix to add to the function name. Default is None.
    name_suffix : str, optional
        The suffix to add to the function name. Default is None.
    Returns
    -------
    Tuple[str, str]
        The available string or function name and code if available.
    """
    return self.available.get_available(
        name_prefix,
        name_suffix,
    )

WaldiezSwarmOnConditionTargetType = Literal['agent', 'nested_chat'] module-attribute

Possible types for the target of the OnCondition.

Swarm after work model.

Handles the next step in the conversation when an agent doesn't suggest a tool call or a handoff.

WaldiezSwarmAfterWork

Bases: WaldiezBase

Swarm after work.

Attributes:

NameTypeDescription
recipientstr

The agent_id to hand off to, an AfterWork option, or the custom after work method. If it is an AfterWork option, it can be one of ('TERMINATE', 'REVERT_TO_USER', 'STAY', 'SWARM_MANAGER').

recipient_typeWaldiezSwarmAfterWorkRecipientType

The type of recipient. Can be 'agent', 'option', or 'callable'. If 'agent', the recipient is a Swarm Agent. If 'option', the recipient is an AfterWorkOption : ('TERMINATE', 'REVERT_TO_USER', 'STAY', 'SWARM_MANAGER'). If 'callable', it should have the signature: def custom_after_work( last_speaker: ConversableAgent, messages: List[dict], groupchat: GroupChat, ) -> Union[AfterWorkOption, ConversableAgent, str]:

get_recipient(agent_names: Dict[str, str], name_prefix: Optional[str] = None, name_suffix: Optional[str] = None) -> Tuple[str, str]

Get the recipient string.

Parameters:

NameTypeDescriptionDefault
agent_namesDict[str, str]

A mapping of agent id to agent name.

required
name_prefixOptional[str]

The prefix for the function name, by default None.

None
name_suffixOptional[str]

The suffix for the function name, by default None.

None

Returns:

TypeDescription
Tuple[str, str]

The recipient string and the function content if applicable.

Source code in waldiez/models/agents/swarm_agent/after_work.py
def get_recipient(
    self,
    agent_names: Dict[str, str],
    name_prefix: Optional[str] = None,
    name_suffix: Optional[str] = None,
) -> Tuple[str, str]:
    """Get the recipient string.

    Parameters
    ----------
    agent_names : Dict[str, str]
        A mapping of agent id to agent name.
    name_prefix : Optional[str], optional
        The prefix for the function name, by default None.
    name_suffix : Optional[str], optional
        The suffix for the function name, by default None.

    Returns
    -------
    Tuple[str, str]
        The recipient string and the function content if applicable.
    """
    if self.recipient_type == "option":
        return f"AfterWork(AfterWorkOption.{self.recipient})", ""
    if self.recipient_type == "agent":
        # the the recipient is passed as the agent name
        # (and not its id), care should be taken to ensure
        # the all the agents in the flow have unique names
        agent_instance = agent_names.get(self.recipient, self.recipient)
        return f"AfterWork({agent_instance})", ""

    function_name = CUSTOM_AFTER_WORK
    if name_prefix:
        function_name = f"{name_prefix}_{function_name}"
    if name_suffix:
        function_name = f"{function_name}_{name_suffix}"
    return (
        f"AfterWork({function_name})",
        generate_function(
            function_name=function_name,
            function_args=CUSTOM_AFTER_WORK_ARGS,
            function_body=self._recipient_string,
            function_types=CUSTOM_AFTER_WORK_TYPES,
        ),
    )

validate_recipient() -> Self

Validate the recipient.

Returns:

TypeDescription
WaldiezSwarmAfterWork

The validated after work model.

Raises:

TypeDescription
ValueError

If the validation fails.

Source code in waldiez/models/agents/swarm_agent/after_work.py
@model_validator(mode="after")
def validate_recipient(self) -> Self:
    """Validate the recipient.

    Returns
    -------
    WaldiezSwarmAfterWork
        The validated after work model.

    Raises
    ------
    ValueError
        If the validation fails.
    """
    self._recipient_string = self.recipient
    if self.recipient_type == "callable":
        is_valid, error_or_body = check_function(
            code_string=self.recipient,
            function_name=CUSTOM_AFTER_WORK,
            function_args=CUSTOM_AFTER_WORK_ARGS,
        )
        if not is_valid or not error_or_body:
            # pylint: disable=inconsistent-quotes
            raise ValueError(
                f"Invalid custom method: {error_or_body or 'no content'}"
            )
        self._recipient_string = error_or_body
    elif self.recipient_type == "option":
        if self.recipient not in [
            "TERMINATE",
            "REVERT_TO_USER",
            "STAY",
            "SWARM_MANAGER",
        ]:
            raise ValueError("Invalid option.")
    return self

WaldiezSwarmAfterWorkOption = Literal['TERMINATE', 'REVERT_TO_USER', 'STAY', 'SWARM_MANAGER'] module-attribute

The possible AfterWork options.

WaldiezSwarmAfterWorkRecipientType = Literal['agent', 'option', 'callable'] module-attribute

The possible AfterWork recipient types.

Update the agent's system message before they reply.

WaldiezSwarmUpdateFunctionType = Literal['string', 'callable'] module-attribute

Possible types for the update function.

WaldiezSwarmUpdateSystemMessage

Bases: WaldiezBase

Update the agent's system message before they reply.

Attributes:

NameTypeDescription
update_function_typeLiteral['string', 'callable']

The type of the update function. Can be either a string or a callable.

update_functionstr

The string template or function definition to update the agent's system message. Can be a string or a Callable. If the function_type is 'string' it will be used as a template and substitute the context variables. If the function_type is 'callable', it should have the signature:

def custom_update_system_message(
    agent: ConversableAgent,
    messages: List[Dict[str, Any]]
) -> str:

get_update_function(name_prefix: Optional[str] = None, name_suffix: Optional[str] = None) -> Tuple[str, str]

Get the update function.

Parameters:

NameTypeDescriptionDefault
name_prefixstr

The prefix of the name, by default None

None
name_suffixstr

The suffix of the name, by default None

None

Returns:

TypeDescription
Tuple[str, str]

The update function and the function name.

Source code in waldiez/models/agents/swarm_agent/update_system_message.py
def get_update_function(
    self,
    name_prefix: Optional[str] = None,
    name_suffix: Optional[str] = None,
) -> Tuple[str, str]:
    """Get the update function.

    Parameters
    ----------
    name_prefix : str, optional
        The prefix of the name, by default None
    name_suffix : str, optional
        The suffix of the name, by default None

    Returns
    -------
    Tuple[str, str]
        The update function and the function name.

    """
    function_name = CUSTOM_UPDATE_SYSTEM_MESSAGE
    if name_prefix:
        function_name = f"{name_prefix}_{function_name}"
    if name_suffix:
        function_name = f"{function_name}_{name_suffix}"
    return (
        generate_function(
            function_name=function_name,
            function_args=CUSTOM_UPDATE_SYSTEM_MESSAGE_ARGS,
            function_types=CUSTOM_UPDATE_SYSTEM_MESSAGE_TYPES,
            function_body=self._update_function,
        ),
        function_name,
    )

validate_update_system_message() -> Self

Validate the update system message function.

Returns:

TypeDescription
UpdateSystemMessage

The validated update system message.

Raises:

TypeDescription
ValueError

If the type is callable and the function is invalid. or if the function type is not 'string' or 'callable'.

Source code in waldiez/models/agents/swarm_agent/update_system_message.py
@model_validator(mode="after")
def validate_update_system_message(self) -> Self:
    """Validate the update system message function.

    Returns
    -------
    UpdateSystemMessage
        The validated update system message.

    Raises
    ------
    ValueError
        If the type is callable and the function is invalid.
        or if the function type is not 'string' or 'callable'.

    """
    self._update_function = self.update_function
    if self.update_function_type == "callable":
        valid, error_or_body = check_function(
            code_string=self.update_function,
            function_name=CUSTOM_UPDATE_SYSTEM_MESSAGE,
            function_args=CUSTOM_UPDATE_SYSTEM_MESSAGE_ARGS,
        )
        if not valid or not error_or_body:
            # pylint: disable=inconsistent-quotes
            raise ValueError(
                f"Invalid custom method: {error_or_body or 'no content'}"
            )
        self._update_function = error_or_body
    return self