Skip to content

unaiverse.agent

Agent is the class that a developer instantiates or subclasses to put a processor on the network. It extends AgentBasics, the class that holds the processor, the streams, the known peers, the behaviors and the interaction manager. On top of that machinery Agent adds the built-in actions and the statistics that it reports to its world. The narrative guides are Agents, Actions and Interactions.

An action is an async method marked with @action that returns a bool. Three kinds of caller run actions.

  1. A behavior runs the action that labels a transition of its current state. True means that the action completed and the behavior moves to the destination state. False means that the action failed or has not finished yet. The behavior retries it as long as the retry_timeout of the transition lasts and drops the attempt when no retry window is left.
  2. Another agent requests an action with send. The behavior of the target queues the request on the action and runs it when the machine is in the source state of that transition.
  3. The developer awaits an action from code that runs during a tick (another action, a callback, an override of behave). The call then returns the bool and runs outside any behavior.

An action that has a parameter named interaction receives the Interaction that it serves. When nobody requested it, the behavior serves it with a system interaction that the agent creates for itself (requester "system").

Many built-in actions work on a group of peers that earlier actions selected. The agent keeps two such groups: the found agents (filled by find_agents and connect_by_role) and the engaged agents (the partners of a task, filled by the engagement actions). A third group holds the agents that passed the last compare_eval. An action argument named agent follows one rule everywhere in this module.

Value of agent Peers involved
a peer id, a node name or owner/name that peer (the decorator resolves names to peer ids)
"<valid_cmp>" the agents that passed the last compare_eval
a list or set of peer ids those peers
None the engaged agents when there are any, the found agents otherwise

An empty group logs an error and makes the action return False (or send nothing).

from unaiverse.agent import Agent, action

class Teacher(Agent):

    @action
    async def give_exam(self, subject: str = "algebra") -> bool:
        if not await self.find_agents("student", engage=True):
            return False
        return await self.send(action_name="take_exam", action_kwargs={"subject": subject},
                               callback="on_exam_done")

    async def on_exam_done(self, interaction=None):
        print(interaction.target, interaction.target_completion_reason)
        return True

action

action(func: Callable) -> Callable
Source code in unaiverse/agent.py
def action(func: Callable) -> Callable:
    """Decorator (@action) that standardizes action method arguments.

    Applied to action methods to:
    - Resolve agent references from name to peer_id.
    - Mark the function as an action (sets ``_is_action = True``).
    - Handle unexpected exceptions.

    Args:
        func: The action method to decorate.

    Returns:
        The wrapped function.
    """

    @functools.wraps(func)
    async def wrapper(self, *args, **kwargs):
        self: Agent
        resolved_kwargs = {}

        if func.__name__ not in Custom.SPECIAL_ACTION_NAMES:  # Special actions (like 'send') resolve by themselves
            for key, value in kwargs.items():

                if key in Custom.AGENT_ARG_NAMES:
                    if isinstance(value, str):
                        resolved = self.resolve_agent_ref(value)
                        resolved_kwargs[key] = resolved if resolved is not None else value
                    elif isinstance(value, list | tuple):
                        _values = list(value)  # Shallow
                        for i, _value in enumerate(_values):
                            _resolved = self.resolve_agent_ref(_value)
                            if _resolved is not None:
                                _values[i] = _resolved
                        resolved_kwargs[key] = _values
                    else:
                        resolved_kwargs[key] = value

                elif key in Custom.STREAM_ARG_NAMES:
                    public = not self.behaving_in_world()
                    if isinstance(value, str):
                        resolved = self.resolve_stream_ref(value, public)
                        resolved_kwargs[key] = resolved if resolved is not None else value
                    elif isinstance(value, (list, tuple)):
                        _values = list(value)  # Shallow
                        for i, _value in enumerate(_values):
                            _resolved = self.resolve_stream_ref(_value, public)
                            if _resolved is not None:
                                _values[i] = _resolved
                        resolved_kwargs[key] = _values
                    else:
                        resolved_kwargs[key] = value

                else:
                    resolved_kwargs[key] = value
        else:
            resolved_kwargs = kwargs

        # Calling the action
        try:
            ret = await func(self, *args, **resolved_kwargs)
            if ret is None:
                log.critical(f"Invalid action '{func.__name__}' detected, it must return True/False "
                             "(it is tolerated to return non-None stuff and interpreted as True, "
                             "but not if it returns None, as happens here)")
        except Exception as e:
            import traceback  # Debug
            if not isinstance(e, AssertionError):
                log.error(f"Action '{func.__name__}' failed since it raised an exception: {e}")  # No-Debug
                log.error(f"{traceback.format_exc()}")  # Debug
            else:
                log.error(f"Action '{func.__name__}' failed since it raised an AssertionError")  # No-Debug
                log.error(f"{traceback.format_exc()}")
            ret = False
        return ret

    wrapper._is_action = True
    return wrapper

The decorator of every action. It returns an async wrapper that does three things around the decorated coroutine.

  1. It resolves the keyword arguments by name. agent, agents, partner, partners, target and targets go through resolve_agent_ref (a list is resolved item by item). stream and streams go through resolve_stream_ref on the network where the agent behaves. A value that does not resolve stays as it was. Positional arguments are never resolved and send is exempt because it resolves its own arguments.
  2. It catches every exception of the action, logs it with its traceback and returns False. The node keeps running.
  3. It logs a critical message when the action returns None. The None is returned as it is and the behavior reads it as a failure. Any other value is returned unchanged.

The wrapper carries the attribute _is_action = True. No other part of the SDK reads it in the current version.

from unaiverse.agent import Agent, action

class Robot(Agent):

    @action
    async def move_arm(self, angle: float, agent: str | None = None, interaction=None) -> bool:
        # 'agent' arrives already resolved to a peer id
        return self.arm.rotate(angle)

Agent

Agent(*args: Any, **kwargs: Any)

Bases: AgentBasics

Source code in unaiverse/agent.py
def __init__(self, *args: Any, **kwargs: Any) -> None:
    """Initializes the agent and the status variables of its basic actions.

    Args:
        *args: Positional arguments forwarded to AgentBasics.
        **kwargs: Keyword arguments forwarded to AgentBasics.
    """
    super().__init__(*args, **kwargs)

    # Status variables (assumed to start with "_"): Agent exchanges
    self._available = True  # It will be automatically set/changed during the agent's life
    self._found_agents = set()  # Peer IDs discovered
    self._valid_cmp_agents = set()  # Agents for which the last evaluation was positive
    self._engaged_agents = set()
    self._eval_results = {}

    # The agents that disconnected() follows when called with no argument, removed since:
    # the removal empties the sets above, and these are what is left to check. Its name
    # keeps it out of the generic clean-up of the status attributes.
    self.__removed_followed_agents = set()

    # Status variables (assumed to start with "_"): Recordings
    self._last_recorded_stream_num = 1
    self._last_recorded_stream_dict = None
    self._last_recorded_count = 0

    # Status variables (assumed to start with "_"): Playlist
    self._preferred_streams = []  # List of preferred streams
    self._cur_preferred_stream = 0  # ID of the current preferred stream from the list
    self._repeat = 1  # Number of repetitions of the playlist

    # Stats
    self.stats = Stats(is_world=False)
    self.overwrite_stats = False  # Whether to overwrite stats when receiving the next STATS_RESPONSE from the world

The agent class. The constructor takes the arguments of AgentBasics unchanged (proc, proc_inputs, proc_outputs, proc_opts, merge_flat_stream_labels, buffer_generated, buffer_generated_by_others, world_folder, policy_filter, policy_filter_lone_wolf). It then initializes the status of the built-in actions (found and engaged agents, evaluation results, recording counters, playlist) and creates the statistics recorder. The status attributes start with _ and the agent resets them when it leaves a world.

from unaiverse.agent import Agent
from unaiverse.networking.node.node import Node

agent = Agent(proc=lambda text: text[::-1], proc_inputs=["text"], proc_outputs=["text"])
node = Node(node_name="Reverser", hosted=agent)
node.run()

A subclass adds its own actions and overrides the hooks of AgentBasics. A world ships one subclass per role in its role files (see Worlds).

stats instance-attribute

stats = Stats(is_world=False)

The Stats recorder of the agent. The constructor creates it with is_world=False. When the agent joins a world that ships its own statistics class, the node replaces it with an instance of that class. Its view holds the statistics that the world sends back.

overwrite_stats instance-attribute

overwrite_stats = False

bool, False by default. The node passes it to update_stats_view for every statistics answer of the world. With True the answer replaces the local view instead of merging into it.

received_some_asked_data class-attribute instance-attribute

received_some_asked_data = on_received

The former name of on_received, kept as an alias for old behavior files. New code and new behaviors use on_received.

Statistics and the world

collect_and_store_own_stats

collect_and_store_own_stats() -> None
Source code in unaiverse/agent.py
def collect_and_store_own_stats(self) -> None:
    """Collects this agent's own stats and pushes them to the stats recorder."""
    if self.stats is None:
        return

    _, own_private_pid = self.get_peer_ids()
    t = clock.get_time_ms()
    info = self.node_conn.get_world_connected_peers_info()
    if info is None:

        # The FFI call failed (transport state unknown): skip this sample rather than
        # record a false "zero peers", which would poison the world connectivity graph
        # with a phantom drop of every peer on a transient error.
        log.error("[Stats] connected peers unavailable (FFI error); skipping the sample")
    else:
        try:
            peers_list = [i['id'] for i in info]
            self.stats.store_stat('connected_peers', peers_list, group_key=own_private_pid, timestamp=t)
        except Exception as e:
            self.stats.store_stat('connected_peers', [], group_key=own_private_pid, timestamp=t)
            log.error(f"[Stats] Error collecting and storing own stats, clearing: {e}")

    try:
        behav = self.behav
        assert behav is not None
        self.stats.store_stat('state', behav.get_state_name(), group_key=own_private_pid, timestamp=t)
        self.stats.store_stat('action', behav.get_action_name(), group_key=own_private_pid, timestamp=t)
        self.stats.store_stat('last_action', behav.get_last_completed_action_name(),
                              group_key=own_private_pid, timestamp=t)
    except Exception as e:
        log.error(f"[Stats] Error storing HSM stats: {e}")

Records the statistics of the agent itself under its private peer id with the current time in milliseconds: connected_peers (the peer ids that the world connection reports), state, action and last_action (from the world behavior). When the list of connected peers is not available it skips that statistic rather than record an empty list. send_stats_to_world calls it and so does a World for itself. It does nothing when stats is None.

send_stats_to_world async

send_stats_to_world() -> None
Source code in unaiverse/agent.py
async def send_stats_to_world(self) -> None:
    """Sends the agent's currently buffered stats to the world and clears them (async)."""
    if not self.in_world():
        log.debug("[send_stats_to_world] Not in a world, skipping stats send.")
        return

    world_peer_id = self.node_conn.get_world_node_peer_id()
    if world_peer_id is None:
        log.error("Agent in world, but world_peer_id is None.")
        return

    self.collect_and_store_own_stats()  # update own stats
    assert self.stats is not None
    payload = self.stats.get_payload_for_world()
    if not payload:
        log.debug("[send_stats_to_world] No stats to send.")
        return

    # Send all stats
    log.misc(f"Sending stats update to world {world_peer_id}...")
    if not (await self.node_conn.send(world_peer_id,
                                      channel_trail=None,
                                      content=payload,
                                      content_type=Msg.STATS_UPDATE)):
        log.error("Failed to send stats update to world.")

Sends the buffered statistics to the world (async). The node calls it every Custom.SEND_STATS_EVERY seconds (30 by default). Outside a world it does nothing. It first calls collect_and_store_own_stats, takes the payload from Stats.get_payload_for_world() and sends it as a statistics update. An empty payload sends nothing and a failed send is logged.

update_stats_view

update_stats_view(received_view: dict, overwrite: bool = False) -> None
Source code in unaiverse/agent.py
def update_stats_view(self, received_view: dict, overwrite: bool = False) -> None:
    """Updates the stats view with the data received from the world.

    Args:
        received_view: The view dictionary received from the world.
        overwrite: Whether to overwrite existing entries. Defaults to False.
    """
    assert self.stats is not None
    self.stats.update_view(received_view, overwrite)

Merges the statistics sent by the world (received_view) into the local view of stats. With overwrite=True the received entries replace the existing ones. The node calls it with the initial statistics when the agent joins a world and with every answer to ask_world_stats.

ask_world_stats async

ask_world_stats(filters: dict | None = None) -> bool
Source code in unaiverse/agent.py
@action
async def ask_world_stats(self, filters: dict | None = None) -> bool:
    """Ask the world for stats: 'filters' is interpreted by the World subclass (method answer_stats_request);
    the answer arrives asynchronously as a STATS_RESPONSE and is merged into the agent's local stats view
    (see update_stats_view) (async)."""
    world_peer_id = self.node_conn.get_world_node_peer_id()
    if world_peer_id is None:
        log.error("Not in a world: cannot ask stats")
        return False
    return await self.node_conn.send(world_peer_id, channel_trail=None,
                                     content=filters if filters is not None else {},
                                     content_type=Msg.STATS_REQUEST)

Action. Sends a statistics request to the world (async). filters (a dict, {} when None) is read by the answer_stats_request method of the world. The answer arrives later and the node merges it with update_stats_view. It returns the result of the send. Outside a world it returns False.

suggest_role_to_world async

suggest_role_to_world(agent: str | None, role: str) -> bool
Source code in unaiverse/agent.py
@action
async def suggest_role_to_world(self, agent: str | None, role: str) -> bool:
    """Suggests a role change for one or more agents to the world master. It iterates through the involved agents,
    checks if their current role differs from the suggested one, and sends a role suggestion message to the
    world master (async).

    Args:
        agent: The ID of the agent or a wildcard to suggest the role for.
        role: The new role to suggest (as a string).

    Returns:
        True if the suggestion was sent successfully, False otherwise.
    """
    log.misc("Suggesting role to world")

    agents = self.__involved_agents(agent)
    role_bits = (self.ROLE_STR_TO_BITS[role] >> 2) << 2

    content = []

    for _agent in agents:
        cur_role_bits = self.ROLE_STR_TO_BITS[self.all_agents[_agent].get_dynamic_profile()['connections']['role']]
        cur_role_bits = (cur_role_bits >> 2) << 2
        if cur_role_bits == role_bits:
            log.misc(f"Not suggesting to change the role of {_agent} "
                     f"since it has already such a role")
        else:
            log.misc(f"Suggesting to change the role of {_agent} to {self.ROLE_BITS_TO_STR[role_bits]}")
            content.append({'peer_id': _agent, 'role': role_bits})

    if len(content) > 0:
        world_peer_id = self.node_conn.get_world_node_peer_id()
        if not (await self.node_conn.send(world_peer_id, channel_trail=None,
                                          content=content,
                                          content_type=Msg.ROLE_SUGGESTION)):
            log.error("Failed to send role suggestion to the world")
            return False
    return True

Action. Asks the world to change the role of one or more agents (async).

Argument Type Default Meaning
agent str, list or None required The agents (see the table of the agent argument).
role str required The new role, for example "teacher". The comparison ignores the base part of the role (public agent, world agent or world master) and looks only at the role defined by the world.

An agent that already holds the custom role is skipped. The others go to the world in one role suggestion message. It returns False only when that send fails. A call with nothing to send returns True. The world decides whether to apply the change.

suggest_badges_to_world async

suggest_badges_to_world(agent: str | None = None, score: float = -1.0, badge_type: str = 'completed', badge_description: str | None = None) -> bool
Source code in unaiverse/agent.py
@action
async def suggest_badges_to_world(self, agent: str | None = None,
                                  score: float = -1.0, badge_type: str = "completed",
                                  badge_description: str | None = None) -> bool:
    """Suggests one or more badges to the world master for specific agents. This is typically used to reward agents
    for completing tasks, such as for a competition. It sends a message with the badge details, including the score
    and type, to the world master (async).

    Args:
        agent: The ID of the agent or a wildcard for which to suggest the badge.
        score: The score associated with the badge.
        badge_type: The type of badge (e.g., 'completed').
        badge_description: An optional description for the badge.

    Returns:
        True if the badge suggestion was sent successfully, False otherwise.
    """
    log.misc("Suggesting one or more badges to world")

    if score < 0.:
        log.error("Invalid score (did you specify the 'score' argument? it must be positive)")
        return False

    agents = self.__involved_agents(agent)
    world_peer_id = self.node_conn.get_world_node_peer_id()

    if badge_type not in Agent.BADGE_TYPES:
        log.error(f"Unknown badge type: {badge_type}")
        return False

    list_of_badge_dictionaries = []
    for peer_id in agents:
        list_of_badge_dictionaries.append({'peer_id': peer_id,
                                           'score': score,
                                           'badge_type': badge_type,
                                           'badge_description': badge_description,
                                           'agent_token': self.node_conn.get_last_token(peer_id)})

    if not (await self.node_conn.send(world_peer_id, channel_trail=None,
                                      content=list_of_badge_dictionaries,
                                      content_type=Msg.BADGE_SUGGESTIONS)):
        log.error("Failed to send badge suggestions to the world")
        return False
    else:
        return True

Action. Suggests to the world a badge for one or more agents (async). A typical use is the end of a competition.

Argument Type Default Meaning
agent str, list or None None The agents to reward (see the table of the agent argument).
score float -1.0 The score of the badge. Because a negative score fails the action, the argument is required in practice.
badge_type str "completed" One of BADGE_TYPES: "completed", "attended", "intermediate", "pro".
badge_description str or None None A free description.

Each badge carries the peer id, the score, the type, the description and the last token of the agent. It returns True when the message reached the world.

Requests

send async

send(action_name: str | None = None, target: str | list[str] | None = None, action_kwargs: dict | None = None, streams: dict[str, str | list[str]] | list[str] | None = None, data_samples: list | dict[str, Tensor | Image | str] | None = None, num_steps: int = -1, timeout: float = -1.0, from_state: str | None = None, to_state: str | None = None, callback: str | None = None, forced_uuid: str | None = 'do_not_force', id: str | None = 'random', copy_sys: bool = False, wait_completion: bool = False, volatile: bool = False, num_samples_to_stream: int = -1, interaction: Interaction | None = None) -> bool
Source code in unaiverse/agent.py
@action
async def send(self, action_name: str | None = None,
               target: str | list[str] | None = None,
               action_kwargs: dict | None = None,
               streams: dict[str, str | list[str]] | list[str] | None = None,
               data_samples: list | dict[str, torch.Tensor | Image | str] | None = None,
               num_steps: int = -1,
               timeout: float = -1.,
               from_state: str | None = None,
               to_state: str | None = None,
               callback: str | None = None,
               forced_uuid: str | None = "do_not_force",
               id: str | None = "random",
               copy_sys: bool = False,
               wait_completion: bool = False,
               volatile: bool = False,
               num_samples_to_stream: int = -1,
               interaction: Interaction | None = None) -> bool:
    """Send an interaction request to one or more target agents (async).

    Accepts either a pre-built :class:`Interaction` object *or* raw arguments from which one will be created.

    Args:
        action_name: The action name (str) if building one from raw args.
            Ignored when a pre-built Interaction is provided.
        target: Peer ID (or wildcard such as ``"<valid_cmp>"``) of the target
            agent. It can be a list of agents. Ignored when a pre-built Interaction is provided.
        action_kwargs: Action arguments dict.  Ignored when a pre-built Interaction
            is provided.
        streams: List of ``(stream_hash, num_samples)`` tuples (or just stream_hash if num_samples = 1).
            Ignored when a pre-built Interaction is provided. A lot of freedom here: stream_hash can be a net hash
            or a user hash. It is also fine to specify just the stream name or the stream
            group, then the user hash or the net hash will be automatically estimated.
        data_samples: List of actual data samples. Ignored when a pre-built Interaction is provided. It can also be
            a dictionary mapping one or more stream user hashes to data samples that will be artificially loaded on
            such streams, so that the 'streams' argument above is actually automatically populated.
            It can also be a string representing the payload that encodes a list of samples, if it was received
            from the net.
        num_steps: Number of steps the interaction spans (used when building from raw args).
            Ignored when a pre-built Interaction is provided.
        timeout: Maximum time for the interaction. Ignored when a pre-built Interaction is provided.
        from_state: Optional source state. Ignored when a pre-built Interaction provided.
        to_state: Optional destination state. Ignored when a pre-built Interaction provided.
        callback: Callback action (will be called when the interaction completes).
        forced_uuid: UUID of the interaction to explicitly force, use carefully.
        id: Optional ID of the interaction. Ignored when a pre-built Interaction is provided.
        copy_sys: True if the interaction must copy the last added stream data with system UUID
            to prepare initial data form the current interaction.
        wait_completion: If True, this action returns True if and only if we get a feed of interaction completion
            from all the involved agents (Default: False).
        volatile: If True, it is marked so that the recipient is asked to not
            send back any status about its completion.
        num_samples_to_stream: The maximum number of samples to stream. By default, no limits (the nun_steps is on
            the consumer side, the origin keeps streaming until timeout or completion). Default: -1 (no limits)
        interaction: The interaction triggered by the system to run this action (automatically set).

    Returns:
        True if at least of the target agents was reached.
    """

    # This action can only be triggered by the system or by the developer, no ways
    if interaction is not None and not interaction.is_system():
        return False

    if wait_completion and volatile:
        raise GenException("You cannot wait for completion a volatile interaction (it will not return any updates)")

    if wait_completion and interaction is None:
        raise GenException("You cannot wait for completion by directly calling this action, without an interaction"
                           " (the state of the action needs to be saved in the interaction object)")

    if interaction is None:  # This happens when calling 'send' from the code, e.g., inside another action
        system_interaction = None
        first_run = True
    else:
        system_interaction = interaction
        first_run = system_interaction.get_mark() is None

    if first_run:
        target = self.__involved_agents(target)
        sent_interaction = await self._send(None, action_name, target, action_kwargs, streams,
                                            data_samples, num_steps, timeout, from_state, to_state, callback,
                                            forced_uuid, id, copy_sys, volatile, num_samples_to_stream)
        if wait_completion:
            assert system_interaction is not None
            assert isinstance(system_interaction.action_ref, Action)
            system_interaction.action_ref.set_default_timeout()  # This will make the action pedantic
            system_interaction.set_mark(sent_interaction)  # First run, Saving the interaction that was sent
            return False
        else:
            if system_interaction:
                assert isinstance(system_interaction.action_ref, Action)
                if not system_interaction.action_ref.is_pedantic_by_default():
                    system_interaction.action_ref.set_timeout(-1.)  # Clear timeouts to ensure it is not pedantic
            return sent_interaction is not None
    else:
        assert system_interaction is not None
        sent_interaction = system_interaction.get_mark()  # Loading the interaction that was sent at the first run
        sent_interaction: Interaction
        if sent_interaction.is_completed():
            if not system_interaction.action_ref.is_pedantic_by_default():
                system_interaction.action_ref.set_timeout(-1.)  # Clear timeouts to ensure it is not pedantic
            return True  # The mark will be automatically cleared by the Action class
        else:
            return False

Action. Sends an interaction to one or more agents (async). It is the one way to ask another agent to run an action (see Interactions).

Argument Type Default Meaning
action_name str or None None The action that the targets run, such as "process", "learn" or an action of a role file.
target str, list[str] or None None The targets: a peer id, a node name, owner/name, a wildcard of the behavior ("<partner>") or a list. None and "<valid_cmp>" follow the table of the agent argument.
action_kwargs dict or None None The arguments of the action on the target. Names reserved to the framework are refused.
streams list[str], dict or None None The streams of this agent that carry the data. With a list the target decides where each stream goes. A dict with the keys stdin, stdtar, stdext and stdunk asks for inputs, learning targets or extras of the processor of the target. A stream can be given by its name, its group, its user hash or its net hash.
data_samples dict, list or None None The data itself in place of streams. A dict maps a stream of this agent to one sample. The sample is written on that stream under the uuid of the interaction and reaches the targets through that stream. The dict is the recommended form.
num_steps int -1 How many steps the target runs with one sample per step. -1 gives one step to an interaction with data.
timeout float -1.0 The maximum life of the interaction in seconds. A non-positive value means 300 seconds.
from_state, to_state str or None None The states of the behavior of the target where the interaction may start and where it should end.
callback str or None None The name of an async method of this agent that the manager awaits once with interaction= when the interaction completes for any reason.
forced_uuid str or None "do_not_force" A uuid to impose. Reserved for special cases.
id str or None "random" The id of the interaction. The uuid is the id followed by _ and the peer id of this agent.
copy_sys bool False After the send, copy onto the uuid of the interaction the last sample that each owned stream of the interaction holds under the system uuid (outside any interaction). The public behavior uses it to forward the last output of the processor.
wait_completion bool False Only in a behavior: keep the action running until every target has completed the interaction.
volatile bool False Ask the targets not to send a status back. The sent interaction as recorded by this agent completes with TIMEOUT at the next tick.
num_samples_to_stream int -1 The maximum number of samples that this agent streams for the interaction. -1 means no limit.
interaction Interaction or None None Injected by the behavior. A developer never passes it.

The call works as follows.

  1. It returns False when another peer requested the send. Only the agent itself (through a system interaction) or code can send.
  2. It builds the interaction with this agent as requester and registers it with register_sent. Registration resolves targets and streams. A failure returns False.
  3. It sends the interaction to each target and keeps the targets that the message reached. When no target was reached it unregisters the interaction and returns False.
  4. It records the interaction for get_last_sent_interaction and returns True.

Without wait_completion, a send that labels a transition is not retried after a False because the action clears its retry timeout. Only a retry timeout declared by the transition survives. With wait_completion=True the first call sends, stores the sent interaction in the mark of the system interaction, gives the action the default retry timeout (Custom.DEFAULT_TIMEOUT, 10 seconds) unless the transition declared one and returns False. Each later call returns True once the sent interaction is completed. Any completion reason counts (OK, REJECTED or TIMEOUT). A target that needs more time than the retry timeout makes the action fail. When the first call reached nobody, the next call sends again.

Two combinations are errors: (1) wait_completion=True with volatile=True and (2) wait_completion=True without an interaction (a call from code). The body raises GenException for both. The @action wrapper turns it into an error in the log and a False return value.

# From an action or a callback of the agent:
ok = await self.send(action_name="process", target="ResNetAgent",
                     data_samples={"proc_output_0": picture}, callback="on_label")
{"action": "send",
 "action_kwargs": {"action_name": "take_exam", "target": "<valid_cmp>",
                   "wait_completion": true}}

all_sent_completed async

all_sent_completed(action_name: str | None = None) -> bool
Source code in unaiverse/agent.py
@action
async def all_sent_completed(self, action_name: str | None = None) -> bool:
    """True iff every sent interaction with the given `action_name` (or any, if None) has been
    completed by the IM. Negation of "are there any still-pending sends out there?". Useful as an
    HSM exit predicate after `send(action_name="...", ...)` was dispatched without `wait_completion` (async)."""
    for inter in self.im.sent.values():
        if action_name is None or inter.action_name == action_name:
            if not inter.is_completed():
                return False
    return True

Action. Returns True when no open sent interaction has the action name action_name. With action_name=None the check covers every open sent interaction. A behavior uses it as the exit condition after several send calls without wait_completion (async).

on_received async

on_received(processing_fcn: str | None = None, data_type: str | None = None) -> bool
Source code in unaiverse/agent.py
@action
async def on_received(self, processing_fcn: str | None = None, data_type: str | None = None) -> bool:
    """Checks if any of the agents that received interactions from you have sent a stream
    sample back. Optionally, it can process the received data with a specified function (async).

    Args:
        processing_fcn: The name of a function to process the received data.
        data_type: Optional. A string with the type of data to consider (discarding the rest).

    Returns:
        True if at least one data sample was received, False otherwise.
    """
    _processing_fcn = None
    if processing_fcn is not None:
        if hasattr(self, processing_fcn):
            _processing_fcn = getattr(self, processing_fcn)
            if not callable(_processing_fcn):
                _processing_fcn = None
        if _processing_fcn is None:
            log.error(f"Processing function not found: {processing_fcn}")

    got_something = False
    sent = list(self.im.sent.values()) + list(self.im.sent_recently_completed)
    for interaction in sent:
        uuid = interaction.uuid
        agents = interaction.target
        for agent in agents:
            net_hash_to_stream_dict = self.find_streams(agent, "processor", discard_owned=True)
            for stream_dict in net_hash_to_stream_dict.values():
                for stream_obj in stream_dict.values():
                    assert stream_obj.props is not None
                    if data_type is not None and stream_obj.props.data_type != data_type:
                        continue
                    assert stream_obj.props is not None
                    if not stream_obj.props.is_public():
                        data = stream_obj.get("received_some_asked_data", uuid=uuid)
                        data_tag = stream_obj.get_tag(uuid=uuid)

                        if data is not None:
                            if _processing_fcn is None:
                                return True  # If some data arrived and no further processing is expected, just True
                            else:
                                got_something = True
                                _processing_fcn: Callable
                                _processing_fcn(agent, stream_obj.props, data, data_tag)
    return got_something

Action. Checks whether the answers to the requests of this agent have arrived (async). It scans the open sent interactions and the completed ones that are not yet drained. For each target it reads the processor streams of that target under the uuid of the interaction.

Argument Type Default Meaning
processing_fcn str or None None The name of a method of the agent. It is called as method(peer_id, props, data, data_tag) for each answer found. A name that is not a method is logged and treated as None.
data_type str or None None Consider only the streams of this data type ("text", "img", "tensor", "file").

Without processing_fcn it returns True at the first answer found. With processing_fcn it calls the method for every answer and returns True when there was at least one. Reading does not consume the samples. The same answer is therefore found again at the next call until the interaction is drained. Because only private streams are scanned, the action always returns False on the public network.

class Asker(Agent):
    def keep_answer(self, peer_id, props, data, data_tag):
        print(peer_id, props.get_name(), data)
{"action": "on_received", "action_kwargs": {"processing_fcn": "keep_answer", "data_type": "text"}}

Data and models

process async

process(interaction: Interaction | None = None) -> bool
Source code in unaiverse/agent.py
@action
async def process(self, interaction: Interaction | None = None) -> bool:
    """Runs one inference step: reads from stdin, calls the processor, and writes to stdout (async).

    Returns:
        True if the step ran successfully, False otherwise.
    """

    # Getting UUID of the interaction (used for tags and stdout)
    if interaction is not None:
        uuid = interaction.uuid
    else:
        uuid = Custom.SYSTEM_INTERACTION_UUID

    # Possibly re-binding stdin to cope with human processor (it might also let the action fail, if needed)
    if not self.__rebind_stdin_if_human(interaction):
        return False

    # Getting input data from the input stream
    input_data = self.stdin.get(uuid=uuid, requested_by="process")  # Use kwargs

    if input_data is None:
        return False

    # Getting data tag
    data_tag = self.stdin.get_tag(uuid=uuid)

    if data_tag is None:
        return False

    # Post get actions to finalize what possibly started with the previous call to the rebind operation
    # (do this only after having received valid data from stdin)
    self.__rebind_stdin_if_human_finalizer(interaction)

    # Customizable input hook
    try:
        input_data = self.hook_proc_tweak_inputs(input_data)
        if input_data is None:
            return False
    except Exception as e:
        log.error(f"Error tweaking the processor inputs: {e}")
        return False

    # Processing data
    try:

        # A ModuleWrapper runs the module in its worker thread (the node keeps running meanwhile); any other
        # callable is called as it is. The steps of a multistep interaction run on the event loop instead (still
        # awaited: an async module, as the JS one of the AI mode in the browser, waits for its answer): its samples
        # come one per tick, and the ones arriving while the module runs in its worker would move stdin past the
        # samples not processed yet (skipped steps, lost answers). A long module goes to the worker all the same
        # (runs_long): a step of seconds would stop the node, Sessions included, and its samples come late anyway
        first, last = self.get_action_step() == 0, self.is_last_action_step()
        if isinstance(self.proc, ModuleWrapper):
            output_data = await self.proc.aforward(*input_data, first=first, last=last,
                                                   offload=self.__offload_step())
        else:
            output_data = self.proc(*input_data, first=first, last=last)

        if not isinstance(output_data, tuple):
            output_data = (output_data,)
    except AnswerWithheld as e:

        # What the processor produced was an answer to a form that does not honour it, and the agent
        # decided that nothing travels: the step fails quietly, the interaction that asked stays open,
        # and whoever is at the keyboard has already been told to answer again
        log.debug(f"Processor output withheld: {e}")
        return False
    except Exception as e:
        log.error(f"Error running the processor: {e}")
        return False

    # Customizable output hook
    try:
        output_data = self.hook_proc_tweak_outputs(output_data)
    except Exception as e:
        log.error(f"Error tweaking the processor outputs: {e}")
        return False

    # Pushing output data to the output stream
    self.stdout.set(output_data, data_tag=data_tag, uuid=uuid)  # Use kwargs for data_tag and uuid
    return True

Action. Runs one inference step of the processor (async). It is the action that a requester asks for with action_name="process" and that the public behavior runs on its own.

  1. It reads the inputs from stdin under the uuid of the interaction (the system uuid when interaction is None) together with their tag. When the inputs or their tag are missing, it returns False. This is how a step waits for its data.
  2. The inputs go through hook_proc_tweak_inputs. None or an exception returns False.
  3. It calls the processor with first (step 0) and last (last step) flags. A ModuleWrapper is awaited through aforward. That method renders the interactive messages for the module and checks its answer to a form (see Interactive messages).
  4. The outputs (wrapped in a tuple when needed) go through hook_proc_tweak_outputs and are written on stdout with the tag of the inputs under the same uuid. From there they travel to the requester.

An answer withheld by the interactive-message policy returns False without an error and leaves the interaction open. Any other exception of the processor is logged and returns False.

In a single-step interaction the processor runs in a worker thread of its wrapper (offloading) and the node keeps running during a long call. In a multi-step interaction it runs inline on the event loop to let each step take the sample of its own tick. A processor whose last call lasted at least Custom.OFFLOAD_SLOW_S seconds (0.5 by default, environment variable NODE_OFFLOAD_SLOW) is offloaded in multi-step interactions too. The wrapper never offloads in the browser or with NODE_OFFLOAD=0. Modules that echo their input or declare UAI_OFFLOAD = False are never offloaded either (see Agents).

For the agent of a person process does not call a model. The agent stores the request of a peer as the pending request of that peer until the person writes. In a world the pending request is stored under the peer id of the world whoever the requester is. A run on the initiative of the agent is refused while a request of the partner is pending. When the message of the person arrives on stdin, the pending request is cleared together with the input data of the interaction.

learn async

learn(interaction: Interaction | None = None) -> bool
Source code in unaiverse/agent.py
@action
async def learn(self, interaction: Interaction | None = None) -> bool:
    """Runs one learning step: first performs inference, then runs a backward pass (async).

    Returns:
        True if the learning step ran successfully, False otherwise.
    """
    if not self.is_human() and (self.proc_opts is None or self.proc_opts['optimizer'] is None
                                or self.proc_opts['losses'] is None
                                or len(self.proc_opts['losses']) == 0):
        log.misc(f"Current processor has no learning skills (or learning options not specified)")
        return False

    assert interaction is not None

    # Humans learn by themselves :)
    if self.is_human():

        # Printing
        log.debug(f"[learn] Step: {self.get_action_step()}, Tag: {self.stdin.get_tag()}, "
                  f"Last Step: {interaction.num_steps - 1}", rep=True),
        return True

    # Inference first
    if await self.process(interaction):

        # Getting the UUID of the interaction
        uuid = interaction.uuid

        # Getting input data from the input stream
        target_data = self.stdtar.get(uuid=uuid, requested_by="learn")  # Use kwargs

        # Learning from the last performed inference and the current targets (inline in a multistep interaction,
        # as the inference in process)
        try:
            assert isinstance(self.proc, ModuleWrapper)
            loss_values = await self.proc.alearn_backward(target_data, offload=self.__offload_step())
        except Exception as e:
            log.error(f"Error while learning: {e}")
            return False

        # Printing
        log.user(f"Losses: {[x.item() for x in loss_values]}, "
                 f"Step: {self.get_action_step()}, Tag: {self.stdin.get_tag()}, "
                 f"Last Step: {interaction.num_steps-1}", rep=True),
        return True
    else:
        return False

Action. Runs one learning step (async). It needs an interaction (a request or a behavior run with streams). It returns False for an artificial agent without optimizer or without losses in proc_opts.

  1. It runs process on the interaction.
  2. It reads the learning targets from stdtar under the uuid of the interaction.
  3. It awaits alearn_backward of the wrapper. That call computes the losses of the outputs against the targets and makes one optimizer step. Offloading follows the rules of process.
  4. It prints the loss values with the step and the tag.

It returns False when the inference fails or the backward raises. For the agent of a person it returns True without doing anything. See Learning over time.

record async

record(interaction: Interaction | None = None, record_uuid: str | None = 'see_interaction_uuid') -> bool
Source code in unaiverse/agent.py
@action
async def record(self, interaction: Interaction | None = None,
                 record_uuid: str | None = "see_interaction_uuid") -> bool:
    """Records `interaction.num_steps` samples from the interaction's stdin stream group into a
    new owned `BufferedStream` group and exposes it via pubsub. Multistep by virtue of the
    interaction's `num_steps`; the framework's readiness gate already pauses execution on
    no-fresh-data cycles (async).

    Args:
        interaction: The driving interaction (auto-injected by the dispatch layer).
        record_uuid: Which `uuid` to read each source stream under. The default sentinel
            `"see_interaction_uuid"` means "use `interaction.uuid`" — the right choice when the
            source agent is a peer that knows about this interaction and publishes under it
            (process-style flow). Pass `record_uuid=None` (or any other explicit uuid string)
            when the source publishes under a different uuid — for instance when recording a
            world stream that has no per-interaction publish, in which case data lives in the
            source's `data_by_uuid[None]` slot.

    Triggered from HSM transits via:

        behav.add_transit("init", "next_state", action="record",
                          args={"streams": {"stdin": ["<world>:group"]},
                                "num_steps": "<wildcard_or_int>",
                                "record_uuid": None})
    """
    if interaction is None:
        return False

    read_uuid = interaction.uuid if record_uuid == "see_interaction_uuid" else record_uuid
    k = self.get_action_step()

    if k == 0:
        dest = {}
        for s_obj in interaction.stream_proxy.values():
            if not isinstance(s_obj, Stream):
                continue
            assert s_obj.props is not None
            props = s_obj.props.clone()
            props.set_group("recorded" + str(self._last_recorded_stream_num))
            dest[s_obj.props.get_name()] = BufferedStream(props=props)
        self._last_recorded_stream_dict = dest

    dest = self._last_recorded_stream_dict

    for s_obj in interaction.stream_proxy.values():
        if not isinstance(s_obj, Stream):
            continue
        x = s_obj.get(uuid=read_uuid, requested_by="record")
        if x is None:
            return False
        assert s_obj.props is not None
        dest_stream = dest[s_obj.props.get_name()]
        if k % 10 == 0:
            log.user(f"Recording Stream: {dest_stream.props.get_group()}.{dest_stream.props.get_name()}, "
                     f"Step: {k}, Last: {interaction.num_steps - 1}")
        dest_stream.set(x, k)

    if self.is_last_action_step():
        for s_obj in dest.values():
            log.user(f"Recording Stream: {s_obj.props.get_name()}, Step: {k}, Last: {interaction.num_steps - 1}")
            s_obj.is_read_only = True
            s_obj.get(requested_by="send_stream_samples")
        self.add_streams(list(dest.values()), owned=True)
        self.update_streams_in_profile()
        await self.subscribe_to_pubsub_owned_streams()
        await self.send_profile_to_all()
        self._last_recorded_stream_num += 1
        self._last_recorded_stream_dict = None
    return True

Action. Records the streams of an interaction into new owned buffered streams and offers them to the other agents (async). It is multi-step: the interaction gives the number of samples in num_steps.

Argument Type Default Meaning
interaction Interaction or None None The interaction that drives the recording (injected). Without it the action returns False.
record_uuid str or None "see_interaction_uuid" The uuid under which the source streams are read. The default reads under the uuid of the interaction and suits a source that publishes for this interaction. None reads the data published outside any interaction (a world stream that broadcasts).

At step 0 it creates one BufferedStream per stream of the interaction with the same properties and the group recorded<n>. At each step it reads one sample of every source and stores it with the step index as tag. A missing sample returns False and the step is retried at the next tick. At the last step it marks the recorded streams read-only, adds them to the owned streams, writes them in the profile, opens their broadcast channels and sends the profile to every known agent. The counter n then advances.

{"action": "record",
 "action_kwargs": {"streams": {"stdin": ["<world>:lesson"]}, "num_steps": 200, "record_uuid": null}}

show async

show(interaction: Interaction | None = None) -> bool
Source code in unaiverse/agent.py
@action
async def show(self, interaction: Interaction | None = None) -> bool:
    """A generic action that exploit the information in the interaction object for printing purposes, commonly used
    (by overriding it) to handle interaction-completion callbacks (async).

    Args:
        interaction: The interaction object that triggered this action.

    Returns:
        True all the times.
    """
    if interaction is None:
        return False
    log.debug(f"[show] The following interaction was completed: "
              f"{interaction.to_code_str(True, True)}")
    return True

Action. Logs the completed interaction at debug level and returns True (async). It returns False without an interaction. It is the default callback of the public behavior and a starting point for a custom callback.

nop async

nop(message: str | None = None) -> bool
Source code in unaiverse/agent.py
@action
async def nop(self, message: str | None = None) -> bool:
    """Do nothing (async).

    Args:
        message: An optional message to print. Defaults to None.

    Returns:
        Always True.
    """
    if message is not None:
        log.misc(message)
    return True

Action. Does nothing and returns True (async). With message it logs that text. Behaviors use it for transitions that only change state.

Engagement

Engagement pairs an agent with others for a task inside a world. The requester finds candidates, offers engagement with send_engage and each candidate accepts with engage. An agent is available while it has no engaged agents and only an available agent accepts.

set_engaged_partner async

set_engaged_partner(agent: str | list[str] | set[str] | None, clear_found: bool = True) -> bool
Source code in unaiverse/agent.py
@action
async def set_engaged_partner(self, agent: str | list[str] | set[str] | None, clear_found: bool = True) -> bool:
    """Virtually forces the engagement with a single agent (or a group of agents), clearing all existing
    engagements and results of previous find operations (async).

    Args:
        agent: The agent or the list of agents to engage (if None, we only clear the list of engaged partners).
        clear_found: Clears results of previously run find operations (True by default).

    Returns:
        True all the times.
    """
    if clear_found:
        self._found_agents.clear()
    self._engaged_agents.clear()
    if agent is not None:
        if isinstance(agent, str):
            agent = [agent]
        for a in agent:
            self._engaged_agents.add(a)
    self._available = len(self._engaged_agents) == 0
    return True

Action. Makes agent (a peer id, a list or a set) the only engaged agents (async). None only clears them. With clear_found=True (default) it also clears the found agents. The agent is available again when the result is empty. It returns True.

send_engage async

send_engage() -> bool
Source code in unaiverse/agent.py
@action
async def send_engage(self) -> bool:
    """Offer engagement to the agents whose identifiers are in self._found_agents (async).

    Returns:
        True if engagement requests were successfully sent to at least one found agent, False otherwise.
    """
    if len(self._found_agents) > 0:
        log.misc(f"Sending engagement request to {', '.join([x for x in self._found_agents])}")
    my_role_str = self.node_profile.get_dynamic_profile()['connections']['role']
    ret = await self.send(target=self._found_agents, action_name="engage",
                          action_kwargs={"sender_role": my_role_str}, wait_completion=True,
                          timeout=Custom.DEFAULT_TIMEOUT,
                          interaction=self.im.get_current())
    if ret:
        marked = self.im.get_current().get_mark()  # the exact interaction this "send" dispatched
        engaged = marked.target if marked is not None else None
        if (engaged is not None) and isinstance(engaged, list) and len(engaged) > 0:
            for eng in engaged:
                self._engaged_agents.add(eng)

                # Marking this agent as not available since it engaged with another one
                self._available = False

                # Removing the agent from the list of asked agents
                self._found_agents.discard(eng)
            return True
        else:
            return False
    else:
        return False

Action. Offers engagement to the found agents (async). It sends them an engage request with the role of this agent as sender_role and a timeout of Custom.DEFAULT_TIMEOUT (10 seconds). It then waits for completion as send with wait_completion=True does. It returns False while it waits. When the request has completed it moves every target of the request from the found agents to the engaged agents, marks the agent unavailable and returns True. Every target counts as engaged once the request completed for any reason. A target that refused is therefore counted too. The action needs a behavior and returns False when called from code.

engage async

engage(acceptable_role: str | None = None, sender_role: str | None = None, interaction: Interaction | None = None) -> bool
Source code in unaiverse/agent.py
@action
async def engage(self, acceptable_role: str | None = None, sender_role: str | None = None,
                 interaction: Interaction | None = None) -> bool:
    """Receive engagement from another agent whose authority is in the specified range (async).

    Args:
        acceptable_role: The role that the sender must have for engagement to be accepted. Defaults to None.
        sender_role: The role of the agent sending the engagement request. Defaults to None.
        interaction: The interaction triggered by the agent requesting engagement (automatically set).

    Returns:
        True if the engagement was successfully received and confirmed, False otherwise.
    """
    _requester = interaction.requester if interaction is not None else None
    log.misc(
        f"Getting engagement from {_requester}, whose role is {sender_role} (looking for {acceptable_role})")
    if _requester not in self.world_agents and _requester not in self.world_masters:
        log.error(f"Unknown agent: {_requester}")
        return False

    if sender_role is None:
        log.error(f"Unknown role of {_requester}")
        return False

    if acceptable_role is None:
        log.error(f"Invalid acceptable role: {acceptable_role}")
        return False

    # Confirming
    if self._available:
        acceptable_role_int = self.ROLE_STR_TO_BITS[acceptable_role]
        if "~" not in acceptable_role:
            sender_role_int = (self.ROLE_STR_TO_BITS[sender_role] >> 2) << 2
        else:
            sender_role_int = self.ROLE_STR_TO_BITS[sender_role]

        if acceptable_role_int == sender_role_int:
            self._engaged_agents.add(_requester)

            # Marking this agent as not available since it engaged with another one
            self._available = False
            return True
        else:
            log.error(f"Cannot engage to {_requester}")
            return False
    else:
        log.error(f"Cannot engage to {_requester}")
        return False

Action, request-only. Accepts an engagement offer (async).

Argument Type Default Meaning
acceptable_role str or None None The role that the requester must hold, written in the behavior of this agent. A plain custom role ("teacher") accepts a member or a master with that role. An augmented role ("world_master~teacher") must match exactly.
sender_role str or None None The role of the requester as filled by send_engage.
interaction Interaction or None None The request (injected).

It returns False in four cases: (1) the requester is not a member or master of the world, (2) either role is missing, (3) this agent is not available and (4) the roles do not match. Otherwise it adds the requester to the engaged agents, marks this agent unavailable and returns True.

send_disengage async

send_disengage(send_disconnection_too: bool = False) -> bool
Source code in unaiverse/agent.py
@action
async def send_disengage(self, send_disconnection_too: bool = False) -> bool:
    """Ask for disengagement (async).

    Args:
        send_disconnection_too: Whether to send a disconnect-suggestion together with the disengagement.

    Returns:
        True if disengagement requests were successfully sent to at least one engaged agent, False otherwise.
    """
    if len(self._engaged_agents) > 0:
        log.misc(f"Sending disengagement request to {', '.join([x for x in self._engaged_agents])}")
    if await self._send(target=list(self._engaged_agents), action_name="disengage",
                        action_kwargs={"disconnect_too": send_disconnection_too}):
        self._engaged_agents.clear()  # There is no "got_disengagement"
        return True
    else:
        log.error(f"Unable to send disengagement to {self._engaged_agents}")
        return False

Action. Sends a disengage request to every engaged agent and clears the engaged agents (async). With send_disconnection_too=True the request asks the receivers to close the connection too. It returns False when there is no engaged agent or nobody was reached. The availability flag stays unchanged. To accept new engagements, call disengage_all or set_engaged_partner(None).

disengage async

disengage(disconnect_too: bool = False, interaction: Interaction | None = None) -> bool
Source code in unaiverse/agent.py
@action
async def disengage(self, disconnect_too: bool = False, interaction: Interaction | None = None) -> bool:
    """Get a disengagement request from an agent (async).

    Args:
        disconnect_too: Whether to disconnect the agent who sent the disengagement.
        interaction: The interaction triggered by the agent requesting disengagement (automatically set).

    Returns:
        True if the disengagement request was successfully processed, False otherwise.
    """

    _requester = interaction.requester if interaction is not None else None
    log.misc(f"Getting a disengagement request from {_requester}")
    if _requester not in self.world_agents and _requester not in self.world_masters:
        log.error(f"Unknown agent: {_requester}")
        return False

    if _requester not in self._engaged_agents:
        log.error(f"Not previously engaged to {_requester}")
        return False

    self._engaged_agents.discard(_requester)  # Remove if present

    if disconnect_too:

        # Graceful disengage: carry WORLD_DISENGAGEMENT so __purge GOAWAYs the Session
        # and the remote sees Session.Closed instead of timing out via liveness (the
        # transport falls with the deferred settlement cut, after the farewell).
        await self.node_purge_fcn(_requester, reason=WORLD_DISENGAGEMENT)

    # Marking this agent as available if not engaged to any agent
    self._available = len(self._engaged_agents) == 0
    return True

Action, request-only. Accepts a disengagement request (async). The requester must be a member or master of the world and an engaged agent. The action removes the requester from the engaged agents. With disconnect_too=True the connection with the requester is closed with a world-disengagement reason. The agent becomes available when no engaged agent is left. It returns True when the checks pass and False otherwise.

disengage_all async

disengage_all() -> bool
Source code in unaiverse/agent.py
@action
async def disengage_all(self) -> bool:
    """Disengage all the previously engaged agents (async).

    Returns:
        True if the disengagement procedure was successfully executed, False otherwise.
    """
    log.misc(f"Disengaging all agents")
    self._engaged_agents = set()

    # Marking this agent as available
    self._available = True
    return True

Action. Clears the engaged agents and marks the agent available (async). No message is sent. It returns True.

all_engagements_completed async

all_engagements_completed() -> bool
Source code in unaiverse/agent.py
@action
async def all_engagements_completed(self) -> bool:
    """Checks if all engagement requests that were sent have been confirmed. It returns True if there are no agents
    remaining in the `_found_agents` list, implying all have been engaged with or discarded (async).

    Returns:
        True if all engagements are complete, False otherwise.

    """
    return len(self._found_agents) == 0

Action. Returns True when the found agents are empty (async). An empty group means that every candidate was engaged or dropped.

Connections

find_agents async

find_agents(role: str | list[str], engage: bool = False, handshake_completed: bool = False) -> bool
Source code in unaiverse/agent.py
@action
async def find_agents(self, role: str | list[str], engage: bool = False, handshake_completed: bool = False) -> bool:
    """Locally searches through the agent's known peers (world and public agents) to find agents with a specific
    role. It populates the `_found_agents` set with the peer IDs of matching agents (async).

    Args:
        role: The role or list of roles to search for.
        handshake_completed: If True, only consider agents that have completed the handshake.
        engage: If you want to force the found agents to be the ones that you are engaged with.

    Returns:
        True if at least one agent is found, False otherwise.
    """
    log.misc(f"Finding an available agent whose role is {role}")
    self._found_agents.clear()
    self._found_agents.update(self.get_agents_by_role(role, handshake_completed=handshake_completed))

    log.debug(f"[find_agents] Found these agents: {self._found_agents}")
    if engage:
        self._engaged_agents = copy.deepcopy(self._found_agents)
    return len(self._found_agents) > 0

Action. Replaces the found agents with the known agents that hold role (async).

Argument Type Default Meaning
role str or list[str] required Role names as in get_agents_by_role.
engage bool False Also make the found agents the engaged agents.
handshake_completed bool False Keep only the agents whose handshake is complete. The default also counts peers that are still connecting.

It returns True when at least one agent was found.

connect_by_role async

connect_by_role(role: str | list[str], filter_fcn: str | None = None, accept_already_connected: bool = False) -> bool
Source code in unaiverse/agent.py
@action
async def connect_by_role(self, role: str | list[str], filter_fcn: str | None = None,
                          accept_already_connected: bool = False) -> bool:
    """Finds and attempts to connect with agents whose profiles match a specific role. It can be optionally
    filtered by a custom function. It returns True if at least one valid agent is found (async).

    Args:
        role: The role or list of roles to search for.
        filter_fcn: The name of an optional filter function.
        accept_already_connected: If you want to consider the already connected peers as valid to make this method
            return True.

    Returns:
        True if at least one agent is found and a NEW connection request is made (and also if it was already
            established - if return_true_if_already_connected=True), False otherwise.
    """
    log.misc(f"Asking to get in touch with all agents whose role is {role}")

    self._found_agents.clear()
    role_list = role if isinstance(role, list) else [role]
    at_least_one_is_valid = False

    for role in role_list:
        role = self.ROLE_STR_TO_BITS[role]

        found_addresses1, found_peer_ids1 = self.node_conn.find_addrs_by_role(Agent.ROLE_WORLD_MASTER | role,
                                                                              return_peer_ids_too=True,
                                                                              discard_yourself=True)
        found_addresses2, found_peer_ids2 = self.node_conn.find_addrs_by_role(Agent.ROLE_WORLD_AGENT | role,
                                                                              return_peer_ids_too=True,
                                                                              discard_yourself=True)
        found_addresses = found_addresses1 + found_addresses2
        found_peer_ids = found_peer_ids1 + found_peer_ids2

        if filter_fcn is not None:
            if isinstance(filter_fcn, str):
                if hasattr(self, filter_fcn):
                    filter_fcn = getattr(self, filter_fcn)
                else:
                    log.error(f"Filter function not found: {filter_fcn}")
                    return False
            if callable(filter_fcn):
                found_addresses, found_peer_ids = filter_fcn(found_addresses, found_peer_ids)

        log.misc(f"Found addresses ({len(found_addresses)}) with role: {role}")
        for f_addr, f_peer_id in zip(found_addresses, found_peer_ids):

            # is_connected reads pool residency, which a Session riding its reconnect
            # grace (up to 45s) still holds: the re-dial is deliberately skipped there,
            # RESUME on the surviving Session is the preferred recovery. Only the
            # terminal LOST evicts the pool and re-opens this dial path.
            if not self.node_conn.is_connected(f_peer_id):
                log.misc(f"Asking to get in touch with {f_peer_id}...")
                peer_id = await self.node_ask_to_get_in_touch_fcn(addresses=f_addr, public=False)
                if peer_id is not None:
                    at_least_one_is_valid = True
                    self._found_agents.add(peer_id)
            else:
                log.misc(f"Not-asking to get in touch with {f_addr}, "
                         f"since I am already connected to the corresponding peer...")
                peer_id = f_peer_id
                if accept_already_connected:
                    at_least_one_is_valid = True
                    self._found_agents.add(peer_id)
            log.misc(f"...returned {peer_id}")
    return at_least_one_is_valid

Action. Connects to the peers of the world that hold a role (async). It clears the found agents and looks up the other members and masters with each role in the rendezvous of the world.

Argument Type Default Meaning
role str or list[str] required Custom role names.
filter_fcn str, callable or None None A method name or a function f(addresses, peer_ids) -> (addresses, peer_ids) that filters the candidates. A name that is not an attribute returns False.
accept_already_connected bool False Count the peers already connected as found.

For each candidate that is not connected it starts a connection and adds the peer to the found agents on success. A connection that is still within its reconnection grace period counts as connected and is not dialed again. It returns True when at least one peer was added.

connect_to async

connect_to(peer_id: str) -> bool
Source code in unaiverse/agent.py
@action
async def connect_to(self, peer_id: str) -> bool:
    """Gets in touch with a peer of the world, unless already connected to it (async).

    Args:
        peer_id: The peer to connect to.

    Returns:
        True if already connected or if getting in touch started, False otherwise.
    """
    addresses = self.node_conn.get_addrs(peer_id)
    if not self.node_conn.is_connected(peer_id):
        log.misc(f"Asking to get in touch with {peer_id}...")
        peer_id = await self.node_ask_to_get_in_touch_fcn(addresses=addresses, public=False)
        if peer_id is not None:
            return True
        else:
            return False
    else:
        log.misc(f"Not-asking to get in touch with {peer_id}, "
                 f"since I am already connected to the corresponding peer...")
        return True

Action. Starts a connection to peer_id in the world using the addresses that the connection pool knows (async). It returns True when the connection started or already existed. peer_id must be a peer id because the decorator does not resolve this argument name.

connected async

connected(agent: str | list[str] | None = None, handshake_completed: bool = False) -> bool
Source code in unaiverse/agent.py
@action
async def connected(self, agent: str | list[str] | None = None, handshake_completed: bool = False) -> bool:
    """Checks if an agent is connected to us or not (async).

    Args:
        agent: The agent to check (or None if there are other already set engaged agents).
        handshake_completed: If True, only consider agents that have completed the handshake.

    Returns:
        True if all the requested agents are indeed connected.
    """

    # - if "agent" is a peer ID, the involved agents will be a list with one element.
    # - if "agent" is a known wildcard, as "<valid_cmp>", then involved agents will be self._valid_cmp_agents
    # - if "agent" is None, then the current agent in self._engaged_agents will be returned
    involved_agents = self.__involved_agents(agent)
    if len(involved_agents) == 0:
        return False

    log.misc(f"Checking if all these agents are connected to me now: {involved_agents}")

    for agent in involved_agents:
        if handshake_completed:
            if agent not in self.all_agents:
                return False
        else:
            if not self.node_conn.is_connected(agent):
                return False
    return True

Action. Returns True when every agent involved is connected (async). agent follows the table of the agent argument and an empty group returns False. With handshake_completed=True an agent counts only when it is in all_agents. Otherwise an open connection is enough.

disconnected async

disconnected(agent: str | None = None, handshake_completed: bool = False) -> bool
Source code in unaiverse/agent.py
@action
async def disconnected(self, agent: str | None = None, handshake_completed: bool = False) -> bool:
    """Checks if a specific set of agents (by ID or wildcard) are no longer connected to the agent.
    It returns False if any of the specified agents are still connected (async).

    Args:
        agent: The ID of the agent or a wildcard to check.
        handshake_completed: If True, only consider agents that have completed the handshake.

    Returns:
        True if all involved agents are disconnected, False otherwise.

    """

    # - if "agent" is a peer ID, the involved agents will be a list with one element.
    # - if "agent" is a known wildcard, as "<valid_cmp>", then involved agents will be self._valid_cmp_agents
    # - if "agent" is None, then the current agent in self._engaged_agents will be returned
    # With no argument, once the agents followed were removed (which empties the sets that
    # say whom we follow), the ones removed are checked.
    follows_nobody = agent is None and len(self._engaged_agents) == 0 and len(self._found_agents) == 0
    if follows_nobody and len(self.__removed_followed_agents) > 0:
        involved_agents = list(self.__removed_followed_agents)
    else:
        if agent is None:
            self.__removed_followed_agents.clear()   # We follow agents again, or nobody
        involved_agents = self.__involved_agents(agent)
    if len(involved_agents) == 0:
        return False

    log.misc(f"Checking if all these agents are not connected to me anymore: {involved_agents}")
    all_disconnected = True
    for agent in involved_agents:
        if handshake_completed:
            if agent in self.all_agents:
                all_disconnected = False
                break
        else:
            if agent in self.all_agents or self.node_conn.is_connected(agent):
                all_disconnected = False
                break
    return all_disconnected

Action. Returns True when every agent involved is gone (async). agent follows the table of the agent argument and an empty group returns False. With handshake_completed=True an agent counts as gone when it is not in all_agents. Otherwise its connection must be closed too. A peer that leaves is removed from the found and engaged agents and the agent remembers it. With agent=None and both groups empty the action checks these remembered peers. A behavior can thus wait until all its partners have left.

disconnect async

disconnect(agent: str) -> bool
Source code in unaiverse/agent.py
@action
async def disconnect(self, agent: str) -> bool:
    """Disconnects an agent (async).

    Args:
        agent: The peer ID of the agent to disconnect.

    Returns:
        Always True.
    """
    log.misc(f"Disconnecting agent: {agent}")

    # Deliberate local teardown: GRACEFUL_SHUTDOWN so the remote sees a clean close.
    await self.node_purge_fcn(agent, reason=GRACEFUL_SHUTDOWN)  # also calls remove_agent -> remove_streams
    return True

Action. Closes the connection with agent gracefully and removes it with its streams (async). It returns True.

disconnect_by_role async

disconnect_by_role(role: str | list[str], disengage_too: bool = False) -> bool
Source code in unaiverse/agent.py
@action
async def disconnect_by_role(self, role: str | list[str], disengage_too: bool = False) -> bool:
    """Disconnects from all agents that match a specified role (async).
    It finds the agents and calls the node's purge function on each.

    Args:
        role: A string or list of strings representing the role(s) of agents to disconnect from.
        disengage_too: Also forces the sending of a disengagement (before disconnecting - default False).

    Returns:
        Always True.
    """
    log.misc(f"Disconnecting agents with role: {role}")
    if disengage_too:
        await self.send_disengage(send_disconnection_too=True)

    # Target only enrolled peers (handshake done), not every role match in the
    # rendezvous roster: disconnecting is meaningful only towards agents we are
    # actually connected to. Without this, in the template engage-by-role loop
    # this fires purge on not-yet-connected peers every behavior tick — a flood
    # of "close called in state known" no-ops plus a synchronous cgo
    # DisconnectFrom per peer, right on the main task's pump.
    if await self.find_agents(role, handshake_completed=True):
        found_agents = copy.deepcopy(self._found_agents)
        for agent in found_agents:

            # Role-based disconnect happens only in a world (roles exist only there), so
            # carry WORLD_DISENGAGEMENT, consistent with disengage.
            await self.node_purge_fcn(agent, reason=WORLD_DISENGAGEMENT)  # Also calls remove_agent->remove_streams
    return True

Action. Closes the connections with the connected agents that hold role (async). With disengage_too=True it first sends a disengagement with disconnection to the engaged agents. It replaces the found agents with the agents of that role whose handshake is complete and closes each connection with a world-disengagement reason. It returns True.

agents_are_waiting async

agents_are_waiting() -> bool
Source code in unaiverse/agent.py
@action
async def agents_are_waiting(self) -> bool:
    """Checks if there are any agents who have connected but have not yet been fully processed or added to the
    agent's known lists. This indicates that new agents are waiting to be managed (async).

    Returns:
        True if there are waiting agents, False otherwise.
    """

    # Session-era replacement for the old `_node_agents_waiting` dict: a found
    # agent is "waiting" while its per-peer Session exists but has not yet
    # reached ESTABLISHED (handshake in flight). The hosted entity only holds
    # `conn`, so this state is queried through NodeConn.is_peer_session_pending.
    waiting = [a for a in self._found_agents if self.node_conn.is_peer_session_pending(a)]
    log.misc(f"Current set of {len(waiting)} found agents with an in-flight (not yet "
             f"established) session: {waiting}")
    return len(waiting) > 0

Action. Returns True when at least one found agent has a connection whose handshake is still in progress (async).

Subscriptions

send_subscribe async

send_subscribe(agent: str | None = None, stream_hashes: list[str] | None = None, unsubscribe: bool = False) -> bool
Source code in unaiverse/agent.py
@action
async def send_subscribe(self, agent: str | None = None,
                         stream_hashes: list[str] | None = None, unsubscribe: bool = False) -> bool:
    """Requests a remote agent or a group of agents to subscribe to or unsubscribe from a list of specified PubSub
    streams. It normalizes the stream hashes and sends an action request containing the stream properties (async).

    Args:
        agent: The target agent's ID or a wildcard.
        stream_hashes: A list of streams to subscribe to or unsubscribe from.
        unsubscribe: A boolean to indicate if it's an unsubscription request.

    Returns:
        True if the request was sent to at least one agent, False otherwise.
    """

    # - if "agent" is a peer ID, the involved agents will be a list with one element.
    # - if "agent" is a known wildcard, as "<valid_cmp>", then involved agents will be self._valid_cmp_agents
    # - if "agent" is None, then the current agent in self._engaged_agents will be returned
    involved_agents = self.__involved_agents(agent)
    log.debug(f"[send_subscribe] Involved_agents: {involved_agents}")

    if len(involved_agents) == 0:
        log.debug(f"[send_subscribe] No involved agents, action ask_gen returns False")
        return False

    # Create a copy of the stream hashes, normalizing them in the appropriate way
    stream_hashes_copy = self.__normalize_user_hash(stream_hashes)

    # Getting properties
    stream_owners = []
    stream_props = []
    for i in range(len(stream_hashes_copy)):
        stream_dict = self.known_streams[stream_hashes_copy[i]]
        peer_id = DataProps.peer_id_from_net_hash(stream_hashes_copy[i])
        for name, stream_obj in stream_dict.items():
            stream_owners.append(peer_id)
            stream_props.append(json.dumps(stream_obj.props.to_dict()))

    what = "subscribe to" if not unsubscribe else "unsubscribe from "
    log.misc(f"Asking {', '.join(involved_agents)} to {what} {stream_hashes}")
    interaction = await self._send(target=involved_agents, action_name="subscribe",
                                   action_kwargs={"stream_owners": stream_owners,
                                                  "stream_props": stream_props,
                                                  "unsubscribe": unsubscribe})
    if interaction is not None:
        correctly_asked = list(interaction.target)
    else:
        correctly_asked = []

    log.debug(f"[send_subscribe] Overall, the action send_subscribe (unsubscribe: {unsubscribe})"
              f" will return {len(correctly_asked) > 0}")
    return len(correctly_asked) > 0

Action. Asks other agents to subscribe to (or leave) broadcast streams (async).

Argument Type Default Meaning
agent str, list or None None The agents to ask (see the table of the agent argument).
stream_hashes list[str] or None None The groups as <peer_id>:<group> or net hashes. "<playlist>" means the current stream of the playlist.
unsubscribe bool False Ask to leave instead of joining.

It sends a subscribe request with the owner and the properties of every stream of the groups. A group that the agent does not know makes the action fail. It returns True when at least one agent was reached.

subscribe async

subscribe(stream_owners: list[str] | None = None, stream_props: list[str] | None = None, unsubscribe: bool = False, interaction: Interaction | None = None) -> bool
Source code in unaiverse/agent.py
@action
async def subscribe(self, stream_owners: list[str] | None = None, stream_props: list[str] | None = None,
                    unsubscribe: bool = False, interaction: Interaction | None = None) -> bool:
    """Executes a subscription or unsubscription request received from another agent. It processes the stream
    properties, adds or removes the streams from the agent's known streams, and handles the underlying PubSub topic
    subscriptions (async).

    Args:
        stream_owners: A list of peer IDs who own the streams.
        stream_props: A list of JSON-serialized stream properties.
        unsubscribe: A boolean to indicate unsubscription.
        interaction: The interaction that triggered this subscription.

    Returns:
        True if the action is successful, False otherwise.
    """
    if stream_props is None or stream_owners is None:
        log.debug("[subscribe] Called without specifying required arguments")
        return False

    log.debug(f"[subscribe] unsubscribe: {unsubscribe}, "
              f"stream_owners: {stream_owners}, stream_props: ... ({len(stream_props)} props)")

    # Building properties
    props_dicts = []
    props_objs = []
    for i in range(len(stream_props)):
        p_dict = json.loads(stream_props[i])
        props = DataProps.from_dict(p_dict)
        if props.is_pubsub():
            props_dicts.append(p_dict)
            props_objs.append(props)
        else:
            log.error(f"Expecting a pubsub stream, got a stream named {props.get_name()} "
                      f"(group is {props.get_group()}), which is not pubsub")
            return False

    # Adding new streams and subscribing (if compatible with our processor)
    something_good_happened = False
    for stream_owner, prop_dict, prop_obj in zip(stream_owners, props_dicts, props_objs):
        if not unsubscribe:
            if not (await self.add_compatible_streams(peer_id=stream_owner, streams_in_profile=[prop_dict],
                                                      buffered=False, public=False)):
                log.error(f"Unable to add a pubsub stream ({prop_obj.get_name()}) from agent {stream_owner}: "
                          f"no compatible streams were found")
            else:
                something_good_happened = True
        else:
            if not (await self.remove_streams(peer_id=stream_owner, name=prop_obj.get_name())):
                log.misc(f"Unable to unsubscribe from pubsub stream ({prop_obj.get_name()}) "
                         f"of agent {stream_owner}")
            else:
                something_good_happened = True
    return something_good_happened

Action, request-only. Executes a subscription request (async).

Argument Type Default Meaning
stream_owners list[str] or None None The owner of each stream.
stream_props list[str] or None None The properties of each stream as JSON.
unsubscribe bool False Leave the streams instead of joining.
interaction Interaction or None None The request (injected).

Missing lists return False and so does a stream that is not a broadcast one. To join, it adds every stream compatible with the processor among the private streams and subscribes to it. To leave, it removes the streams. It returns True when at least one stream was added. When leaving it always returns False although the streams are removed. The removal method returns None and the action reads that as a failure.

Playlists

A playlist is an ordered list of stream groups that an agent goes through, for example the lessons that a teacher streams one after the other. The playlist repeats repeat times and a pointer marks the current group. The stream reference "<playlist>" stands for the current group in evaluate, send_subscribe and in the stream arguments of actions.

set_pref_streams async

set_pref_streams(net_hashes: list[str], repeat: int = 1) -> bool
Source code in unaiverse/agent.py
@action
async def set_pref_streams(self, net_hashes: list[str], repeat: int = 1) -> bool:
    """Fills the agent's list of preferred streams (a playlist). It can repeat the playlist a specified number of
    times and resolves user-provided stream hashes to their full network hashes (async).

    Args:
        net_hashes: A list of stream hashes to add to the playlist.
        repeat: The number of times to repeat the playlist.

    Returns:
        Always True.
    """
    log.misc(f"Setting up a list of {len(net_hashes)} preferred streams")
    self._cur_preferred_stream = 0
    self._preferred_streams = []
    self._repeat = repeat
    for i in range(0, self._repeat):
        for net_hash in net_hashes:

            # We are tolerating both peer_id:name_or_group and also peer_id::ps:name_or_group
            components = net_hash.split(":")
            peer_id = components[0]
            name_or_group = components[-1]
            net_hash_to_streams = self.find_streams(peer_id=peer_id, name_or_group=name_or_group)
            for _net_hash in net_hash_to_streams.keys():
                self._preferred_streams.append(_net_hash)

    return True

Action. Fills the playlist and puts the pointer on the first entry (async). Each item of net_hashes is <peer_id>:<name or group> (a net hash with ::ps: is accepted too) and adds every known group of that peer that matches. The whole list is repeated repeat times (default 1). An item that matches nothing adds nothing. It returns True.

first_pref_stream async

first_pref_stream() -> bool
Source code in unaiverse/agent.py
@action
async def first_pref_stream(self) -> bool:
    """Resets the internal pointer to the first stream in the list of preferred streams. This is useful for
    restarting a playback or processing loop (async).

    Returns:
        True if the move is successful, False if the list is empty.
    """
    if len(self._preferred_streams) == 0:
        log.error(f"Cannot move to the first stream because the list of preferred streams is empty")
        return False

    self._cur_preferred_stream = 0
    log.misc(f"Moving to the first preferred stream ({self._preferred_streams[self._cur_preferred_stream]})")
    return True

Action. Moves the pointer to the first entry (async). It returns False for an empty playlist.

next_pref_stream async

next_pref_stream() -> bool
Source code in unaiverse/agent.py
@action
async def next_pref_stream(self) -> bool:
    """Moves the internal pointer to the next stream in the list of preferred streams, which is often used for
    playlist-like operations. It wraps around to the beginning if it reaches the end (async).

    Returns:
        True if the move is successful, False if the list is empty.
    """
    if len(self._preferred_streams) == 0:
        log.error(f"Cannot move to the next stream because the list of preferred streams is empty")
        return False

    self._cur_preferred_stream = (self._cur_preferred_stream + 1) % len(self._preferred_streams)
    suffix = ", warning: restarted" if self._cur_preferred_stream == 0 else ""
    log.misc(
        f"Moving to the next preferred stream ({self._preferred_streams[self._cur_preferred_stream]}){suffix}")
    return True

Action. Moves the pointer to the next entry and back to the first after the last one (async). It returns False for an empty playlist.

check_pref_stream async

check_pref_stream(what: str = 'last') -> bool
Source code in unaiverse/agent.py
@action
async def check_pref_stream(self, what: str = "last") -> bool:
    """Checks the position of the current preferred stream within the list. It can check if it's the first, last,
    or if it has completed a full round, among other checks (async).

    Args:
        what: A string specifying the type of check to perform (e.g., 'first', 'last', 'last_round').

    Returns:
        True if the condition is met, False otherwise.
    """
    valid = ['first', 'last', 'not_first', 'not_last', 'last_round', 'not_last_round', 'last_song', 'not_last_song']
    assert what in valid, f"The what argument can only be one of {valid}"

    log.misc(f"Checking if the current preferred playlist item "
             f"(id: {self._cur_preferred_stream}) is the '{what}' one")

    if what == "first":
        return self._cur_preferred_stream == 0
    elif what == "last":
        return self._cur_preferred_stream == len(self._preferred_streams) - 1
    elif what == "not_first":
        return self._cur_preferred_stream != 0
    elif what == "not_last":
        return self._cur_preferred_stream != len(self._preferred_streams) - 1
    elif what == "last_round":
        return (self._cur_preferred_stream + len(self._preferred_streams) // self._repeat >=
                len(self._preferred_streams))
    elif what == "not_last_round":
        return (self._cur_preferred_stream + len(self._preferred_streams) // self._repeat <
                len(self._preferred_streams))
    elif what == "last_song":
        if self._repeat <= 0 or len(self._preferred_streams) == 0:
            return False
        num_streams_in_playlist = len(self._preferred_streams) // self._repeat
        return (self._cur_preferred_stream + 1) % num_streams_in_playlist == 0
    elif what == "not_last_song":
        if self._repeat <= 0 or len(self._preferred_streams) == 0:
            return False
        num_streams_in_playlist = len(self._preferred_streams) // self._repeat
        return (self._cur_preferred_stream + 1) % num_streams_in_playlist != 0
    else:
        return False

Action. Tests the position of the pointer (async). Let L be the length of the repeated playlist, r the repetitions and n = L // r the entries of one round.

what True when
"first", "not_first" the pointer is (is not) on entry 0
"last", "not_last" the pointer is (is not) on entry L - 1
"last_round", "not_last_round" the pointer is (is not) in the last round, that is pointer + n >= L
"last_song", "not_last_song" the pointer is (is not) on the last entry of a round. Both return False for an empty playlist.

Any other value fails the action. The default is "last".

Evaluation

evaluate async

evaluate(stream_hash: str, how: str, steps: int = 100, re_offset: bool = False, agents_to_evaluate: str | list[str] | None = None) -> bool
Source code in unaiverse/agent.py
@action
async def evaluate(self, stream_hash: str, how: str, steps: int = 100, re_offset: bool = False,
                   agents_to_evaluate: str | list[str] | None = None) -> bool:
    """Evaluates the performance of agents that have completed a generation task. It compares the generated data
    from each agent with a local stream (which can be a ground truth or reference stream) using a specified
    comparison method (async).

    Args:
        stream_hash: The hash of the local stream to use for comparison.
        how: The name of the comparison method to use.
        steps: The number of steps to perform the evaluation.
        re_offset: A boolean to indicate whether to re-offset the streams.
        agents_to_evaluate: peer ID or list of peer IDs of agents that returned streams that were buffered, and
            that we are going to evaluate (default is None, meaning: "take the engaged agents").

    Returns:
        True if the evaluation is successful, False otherwise.
    """
    if self.buffer_generated_by_others == 'none':
        log.error("Cannot evaluate if not buffering data generated by others")
        return False

    if stream_hash == "<playlist>":
        if len(self._preferred_streams) > self._cur_preferred_stream >= 0:
            net_hash = self._preferred_streams[self._cur_preferred_stream]
        else:
            log.error("Invalid playlist index!")
            return False
    else:
        net_hash = self.user_stream_hash_to_net_hash(stream_hash)

    assert net_hash is not None

    # Agents to evaluate
    if agents_to_evaluate is None:
        agents_to_evaluate = self._engaged_agents
    else:
        if isinstance(agents_to_evaluate, str):
            agents_to_evaluate = [agents_to_evaluate]

    self._eval_results = {}
    log.debug(f"[evaluate] Agents to evaluate: {agents_to_evaluate}")
    for peer_id in agents_to_evaluate:
        if peer_id not in self.last_buffered_peer_id_to_info:
            log.error(f"Missing buffered stream for {peer_id}, cannot evaluate it (skipping)")
            continue
        received_net_hash = self.last_buffered_peer_id_to_info[peer_id]["net_hash"]
        log.misc(f"Comparing {net_hash} with {received_net_hash}")
        eval_result, ret = self.__compare_streams(net_hash_a=net_hash,
                                                  net_hash_b=received_net_hash,
                                                  how=how, steps=steps, re_offset=re_offset)
        log.misc(f"Result of the comparison: {eval_result}")
        if not ret:
            return False
        else:
            peer_id = DataProps.peer_id_from_net_hash(received_net_hash)
            self._eval_results[peer_id] = eval_result

    return True

Action. Compares what other agents generated with a reference stream of this agent (async). The outputs of the other agents are read from their buffered copies. The action therefore needs buffer_generated_by_others other than "none".

Argument Type Default Meaning
stream_hash str required The reference group as <peer_id>:<group> or net hash. "<playlist>" means the current entry of the playlist.
how str required The dissimilarity: "mse", "max" or "geq<x>" (see below).
steps int 100 How many samples to compare.
re_offset bool False Align the first tags of the two streams before comparing.
agents_to_evaluate str, list[str] or None None The peers to evaluate. None means the engaged agents.

For each peer it compares the reference sample by sample along the tags with the last buffered copy of the processor output of that peer. A peer without a buffered copy is skipped with an error. Both streams must be buffered and compatible. The result is a dissimilarity in [0, +inf) averaged over steps. Lower is better.

how Score of one pair of samples
"mse" The mean squared error of the two tensors.
"max" 0 when the arguments of the maximum coincide and 1 when they differ.
"geq<x>" The fraction of components on different sides of the threshold x = float(how[3:]). "geq0.5" uses 0.5. "geq-0.5" uses -0.5.

Three cases override how: (1) tensors of class indices (torch.long) score 1 - accuracy, (2) strings score 0 when equal and 1 when different and (3) tensors of different shapes score 1. A sample missing from the copy adds 1 (with "mse", 1.1 times the average so far). A sample of the copy that comes earlier than expected fails the action. The scores go to the evaluation results that compare_eval reads. It returns False at the first comparison that fails and True otherwise.

compare_eval async

compare_eval(cmp: str, thres: float, good_if_true: bool = True) -> bool
Source code in unaiverse/agent.py
@action
async def compare_eval(self, cmp: str, thres: float, good_if_true: bool = True) -> bool:
    """Compares the results of a previous evaluation to a given threshold or finds the best result among all
    agents. It can check for minimum, maximum, or simple threshold-based comparisons, and it populates a list of
    'valid' agents that passed the comparison (async).

    Args:
        cmp: The comparison operator (e.g., '<', '>', 'min').
        thres: The threshold value for comparison.
        good_if_true: A boolean to invert the pass/fail logic.

    Returns:
        True if at least one agent passed the comparison, False otherwise.
    """
    assert cmp in ["<", ">", ">=", "<=", "min", "max"], f"Invalid comparison operator: {cmp}"
    assert thres >= 0. or cmp in ["min", "max"], f"Invalid evaluation threshold: {thres} (it must be in >= 0.)"

    self._valid_cmp_agents = set()
    msgs = []
    best_so_far = -1

    min_or_max = None
    leq_or_geq = None
    if cmp in ["min", "max"]:
        min_or_max = "minimum" if cmp == "min" else "maximum"
        leq_or_geq = "<=" if cmp == "min" else ">="

    if len(self._eval_results) == 0:
        log.user("No results to evaluate!")

    for agent_peer_id, eval_result in self._eval_results.items():
        if cmp not in ["min", "max"]:
            log.misc(f"Checking if result {eval_result} {cmp} {thres}, for agent {agent_peer_id}")
        else:
            if thres >= 0:
                log.misc(f"Checking if result {eval_result} is the {min_or_max} so far, "
                         f"only if {leq_or_geq} {thres}, for agent {agent_peer_id}")
            else:
                log.misc(
                    f"Checking if result {eval_result} is the {min_or_max} so far, for agent {agent_peer_id}")

        if eval_result < 0.:
            log.user(f"Invalid evaluation result: {eval_result}")
            return False

        owner_account = owner_handle(self.all_agents[agent_peer_id].get_static_profile())
        agent_name = self.all_agents[agent_peer_id].get_static_profile()['node_name']

        if cmp != "min" and cmp != "max":
            outcome = False
            if cmp == "<" and eval_result < thres:
                outcome = True
            elif cmp == "<=" and eval_result <= thres:
                outcome = True
            elif cmp == ">" and eval_result > thres:
                outcome = True
            elif cmp == ">=" and eval_result >= thres:
                outcome = True

            if cmp[0] == "<":
                alias = 'error level' if good_if_true else 'mark'
            else:
                alias = 'mark' if good_if_true else 'error level'

            if good_if_true:
                if outcome:
                    msgs.append(f"Agent {owner_account}/{agent_name} passed with {alias} {eval_result}/{thres}")
                    self._valid_cmp_agents.add(agent_peer_id)
                else:
                    msgs.append(f"Agent {owner_account}/{agent_name} did not pass, {alias} {eval_result}/{thres}")
            else:
                if outcome:
                    msgs.append(f"Agent {owner_account}/{agent_name} did not pass, {alias} {eval_result}/{thres}")
                else:
                    msgs.append(f"Agent {owner_account}/{agent_name} passed with {alias} {eval_result}/{thres}")
                    self._valid_cmp_agents.add(agent_peer_id)
        else:
            if ((cmp == "min" and (thres < 0 or eval_result <= thres) and
                 (eval_result < best_so_far or best_so_far < 0)) or
                    (cmp == "max" and (thres < 0 or eval_result >= thres) and
                     (eval_result > best_so_far or best_so_far < 0))):
                best_so_far = eval_result
                self._valid_cmp_agents = {agent_peer_id}
                msgs = [f"The best agent is {owner_account}/{agent_name}"]
            elif best_so_far < 0:
                msgs = [f"No best agent found for the considered threshold ({thres})"]

    for msg in msgs:
        log.user(msg)

    if len(self._valid_cmp_agents) == 0:

        # # cheating (hack):
        # self._valid_cmp_agents.append(agent_peer_id)
        # log.misc(", ".join(msgs))
        # return True
        return False
    else:
        return True

Action. Selects the agents whose last evaluation passes a test and makes them the group "<valid_cmp>" (async).

Argument Type Default Meaning
cmp str required "<", ">", "<=", ">=", "min" or "max".
thres float required The threshold. It must be non-negative with a comparison operator. With "min" and "max" a negative value means no threshold.
good_if_true bool True With a comparison operator, False inverts the test: an agent passes when the comparison is false.

With a comparison operator every agent that passes enters the group. With "min" or "max" the group holds the single agent with the lowest or highest score within the threshold. The outcome of each agent is printed with its account and node name. It returns True when the group is not empty. A negative score or an unknown operator fails the action.

[{"action": "evaluate", "action_kwargs": {"stream_hash": "<playlist>", "how": "mse", "steps": 50}},
 {"action": "compare_eval", "action_kwargs": {"cmp": "<=", "thres": 0.1}},
 {"action": "suggest_badges_to_world", "action_kwargs": {"agent": "<valid_cmp>", "score": 1.0}}]

Overrides of AgentBasics

resolve_stream_ref

resolve_stream_ref(ref: str, public: bool) -> str | None
Source code in unaiverse/agent.py
def resolve_stream_ref(self, ref: str, public: bool) -> str | None:
    """Resolve a stream name to a stream user or net hash (heuristic, gives priority to owned streams).

    Args:
        ref: A stream name, without peer IDs, just the name.
        public: A boolean to inform the resolve procedure whether it must look for streams among public agents
            (True) or world-related agents (False).

    Returns:
        The stream user hash or net hash if found, None otherwise.
    """

    if ref == "<playlist>":
        return self._preferred_streams[self._cur_preferred_stream] \
            if len(self._preferred_streams) > self._cur_preferred_stream >= 0 else None
    else:
        return super().resolve_stream_ref(ref, public)

Resolves "<playlist>" to the net hash of the current entry of the playlist (None for an empty playlist) and every other reference as AgentBasics.resolve_stream_ref does.

remove_peer_from_agent_status_attrs

remove_peer_from_agent_status_attrs(peer_id: str) -> None
Source code in unaiverse/agent.py
def remove_peer_from_agent_status_attrs(self, peer_id: str) -> None:
    """Removes a peer from all agent-level status tracking sets (overrides parent) (async).

    Args:
        peer_id: The peer ID to remove from status tracking structures.
    """
    if peer_id in (self._engaged_agents if len(self._engaged_agents) > 0 else self._found_agents):
        self.__removed_followed_agents.add(peer_id)
    super().remove_peer_from_agent_status_attrs(peer_id)
    self._available = len(self._engaged_agents) == 0

Removes peer_id from the status attributes as the base method does. When the peer was among the engaged agents (or among the found agents when no agent was engaged) it is remembered for disconnected. The agent becomes available when no engaged agent is left.

reset_agent_status_attrs

reset_agent_status_attrs() -> None
Source code in unaiverse/agent.py
def reset_agent_status_attrs(self) -> None:
    """Resets all agent-level status attributes to their initial values (overrides parent)."""
    super().reset_agent_status_attrs()  # this sets status vars to [], {}, 0, 0., False, in function of their type
    self.__removed_followed_agents = set()
    self._available = True
    self._repeat = 1
    self._last_recorded_stream_num = 1
    self._last_recorded_count = 0

Resets the status attributes as the base method does and restores the values that are not zero at start. The agent becomes available, the playlist repeats once and the recording counter restarts from 1.