Skip to content

unaiverse.interaction

An interaction is a request from one agent to one or more other agents: run this action, with these arguments, on these data. The agent that asks is the requester and the agents that run the action are the targets. A developer creates interactions with Agent.send and reads them in callbacks and actions. Everything else in this module runs inside the node: the node registers an incoming interaction, the behavior runs its action and the manager completes it, notifies the requester and frees the stream data. The narrative guide is Interactions.

The module holds five objects.

Object Role
Interaction One request, with its action, arguments, streams or samples, timing, status and per-target outcome. It is also the unit that travels on the network (to_dict and from_dict).
InteractionManager The bookkeeper of one agent. The agent holds it in agent.im. It keeps the interactions sent, received and lazy, binds the standard streams of the agent to the interaction being served and completes the expired ones.
InteractionStatus The life cycle of an interaction.
CompletionReason Why an interaction ended.
InteractionType Whether the manager registered it as sent, received or lazy.

The life of a request on the two sides follows these steps.

  1. The requester builds an Interaction (status CREATED) and register_sent stores it in im.sent with status REQUESTED.
  2. The target rebuilds it with Interaction.from_dict. Its behavior links it to the requested action and register_received stores it in im.received with status RECEIVED.
  3. When the behavior serves it, set_current marks it RUNNING and binds the standard streams of the agent to the streams of the interaction. Another interaction can pause it (PAUSED).
  4. When the action ends, complete marks it COMPLETED with a CompletionReason and moves it to received_recently_completed. At the next tick drain_completed returns it and the agent sends its status to the requester.
  5. The requester applies that status with update_sent_status. When every target has completed, the copy of the requester becomes COMPLETED and its callback runs.
from unaiverse.agent import Agent
from unaiverse.interaction import CompletionReason

class Asker(Agent):
    async def on_label(self, interaction=None):
        if interaction.completion_reason == CompletionReason.OK:
            print("Target reached", interaction.destination_state)
        else:
            print("Ended with", interaction.completion_reason.value)
        return True

# Inside an action or a behave() override of Asker:
#     await self.send(action_name="process", target="ResNetAgent",
#                     data_samples={"proc_output_0": picture}, callback="on_label")

Three identifiers recur on this page. The id is a short string chosen by the requester (eight hexadecimal characters by default). The uuid is the id followed by _ and the peer id of the requester. Both agents store the interaction and its stream data under this key. A system interaction is one that an agent creates for itself when a behavior runs an action that nobody requested. Its requester is the label "system" (Custom.SYSTEM_INTERACTION_LABEL) and it never travels.

Interaction

Interaction(action_name: 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] | str | None = None, num_steps: int = -1, requester: str | None = None, target: str | list[str] | None = None, from_state: str | None = None, to_state: str | None = None, timeout: float = -1.0, callback: str | None = None, volatile: bool = False, forced_uuid: str | None = 'do_not_force', id: str | None = 'random', num_samples_to_stream: int = -1)
Source code in unaiverse/interaction.py
def __init__(self,
             action_name: 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.Image | str] | str | None = None,
             num_steps: int = -1,
             requester: str | None = None,
             target: str | list[str] | None = None,
             from_state: str | None = None,
             to_state: str | None = None,
             timeout: float = -1.,
             callback: str | None = None,
             volatile: bool = False,
             forced_uuid: str | None = "do_not_force",
             id: str | None = "random",
             num_samples_to_stream: int = -1) -> None:
    """Create a new Interaction.

    Args:
        action_name: The name of the action being requested (e.g. "process", "learn").
        action_kwargs: Action arguments (dict, no streams).
        streams: List of (stream_name - a.k.a. stream user hash, num_samples) tuples specifying expected data.
        data_samples: List of actual data samples (alternative to streams specification). 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: Total number of steps for this interaction (-1 means no data-based steps).
        requester: Peer ID of the agent originating this interaction.
        target: Peer ID of the target agent or list of peer IDs.
        from_state: Name of the state from which the interaction is expected to happen.
        to_state: Name of the state where the interaction is supposed to yield.
        timeout: Maximum retry_timeout until which the interaction is valid (-1 means no limit: the
            InteractionManager will override this with its internal retry_timeout valid for all actions).
        callback: Name of the method to call on the agent (the InteractionManager will do it) when this
            interaction finishes (it must be a method with a single argument, which is the interaction object).
        volatile: If True, it is marked so that the recipient is asked to not
            send back any status about its completion.
        forced_uuid: A very custom option to force a specific UUID (None is a valid UUID here), that is by default
            a mixture of the id (below) and the target fields. To be used only in very special cases.
            Defaults to "do_not_force".
        id: Identifier string (might not be unique); ``"random"`` generates one automatically (default).
            When set to None, it defaults to the UUID of a system interaction. The requester will be appended to
            it (separated by "_") to get the final UUID, that is the "unique" identification of the interaction.
        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)
    """

    # Participants
    self.requester: str | None = requester

    # Shallow copy targets, since they will be resolved later
    self.target: list[str | None] = list(target) if isinstance(target, list) else [target]

    # Identity
    self.id = _uuid.uuid4().hex[0:8] if (id is not None and id == 'random') else id \
        if id is not None else Custom.SYSTEM_INTERACTION_UUID

    # Indexing string (the actual unique identifier of the interaction, that also involves the requester)
    self.uuid = Interaction.build_uuid(self.id, str(self.requester))

    # Forcing a specific UUID (if needed)
    if forced_uuid != "do_not_force":
        self.id = None
        self.uuid = forced_uuid

    # Action requested
    self.action_name = action_name
    self.action_kwargs: dict = action_kwargs if action_kwargs is not None else {}

    # Timing information
    self.timestamp_created: float = -1.
    self.timestamp_started: float = -1.
    self.timeout: float = timeout
    self.cycle_created: int = -1
    self.cycle_started: int = -1
    self.timestamp_completed: float = -1.
    self.cycle_completed: int = -1

    # States
    self.from_state: str | None = from_state
    self.to_state: str | None = to_state

    # Samples specification: list of (stream_name, num_samples)
    self.streams: dict = {}
    self.data_samples = []
    self.num_steps: int = num_steps  # Generic not-data-based interactions have -1 here
    self.num_samples_to_stream: int = num_samples_to_stream

    # Stream-based specification
    if streams is not None and len(streams) > 0:
        self.parse_streams(streams)  # This will create a specific stream structure

    if isinstance(data_samples, str):

        # If it is JSON string of a list of dicts, each is type_name->base64...
        data_samples = deserialize_payload(data_samples)  # List of PIL.Image, torch.Tensor, str, ...

    # Actual data (alternative to samples above)
    if len(self.streams) > 0 and (data_samples is not None and len(data_samples) > 0):
        log.error("You are not expected to build an interaction object specifying both streams and data_samples. "
                  "Keeping streams only!")

    # Ensure all data-involving-interactions have at least self.num_steps = 1
    if len(self.streams) > 0 and (not isinstance(self.num_steps, str) and self.num_steps < 0):  # Could be wildcard
        self.num_steps = 1
    elif len(self.streams) == 0 and (data_samples is not None and len(data_samples) > 0):
        self.data_samples = data_samples  # List of PIL.Image, torch.Tensor, str, or dict user hash -> sample
        self.num_steps = 1

    # Checking
    if self.num_samples_to_stream >= 0 and self.num_steps > self.num_samples_to_stream:
        log.error(f"You cannot ask to stream {self.num_samples_to_stream} samples and require the consumer to "
                  f"run {self.num_steps} action steps.")

    # Status
    self.status: InteractionStatus = InteractionStatus.CREATED
    self.volatile: bool = volatile

    # Pointers
    self.action_ref = None  # Reference to the actual Action object

    # Data tags
    self.data_tags: dict[str, list[int]] = {}  # Streams could have different data tags

    # Completion reason
    self.completion_reason: CompletionReason | None = None

    # Destination state reached, if the action was completed (for status messages)
    self.destination_state: str | None = None

    # Params that depends on the way it is stored in the action
    self.by_insertion_order_id = -1
    self.by_requester_insertion_order_id = -1

    # Status of the running action
    self.__step_idx = -1  # The first done step will have index 0, while -1 means "no steps done so far"
    self.__starting_time = 0.
    self.__timeout_starting_time = 0.
    self.__mark = None
    self.__num_streamed_samples = 0
    self.stdin_streams = {}  # User hash to stream object
    self.stdtar_streams = {}  # User hash to stream object
    self.stdext_streams = {}  # User hash to stream object
    self.owned_streams = {}  # User hash to stream object
    self.lazy_streams = {}  # User hash to stream object
    self.stream_proxy = StreamProxy()  # Virtual stream IO associated to all streams above (not the lazy ones)

    # Target-related info
    self.target_data_tags: list[dict[str, list[int]]] = [{} for _ in range(len(self.target))]
    self.target_cycle_completed: list[int] = [-1] * len(self.target)
    self.target_timestamp_completed: list[float] = [-1.] * len(self.target)
    self.target_completion_reason: list[CompletionReason | None] = [None] * len(self.target)
    self.target_destination_state: list[str | None] = [None] * len(self.target)

    # Back-reference to the InteractionManager (set when registered)
    self.__im: InteractionManager | None = None

    # Interaction type (from Interaction Manager)
    self.type: InteractionType | None = None

    # Callback method name
    self.callback = callback

    # Checking
    if self.callback is not None and self.volatile:
        raise GenException("You cannot set a callback on a volatile interaction")

One request between agents, on the side of the requester or on the side of a target. The two copies are distinct objects. The requester keeps its copy in im.sent and each target rebuilds its own from the dictionary that travels on the network. A developer rarely calls the constructor directly because Agent.send builds the interaction from its own arguments and the node rebuilds the received ones.

Argument Type Default Meaning
action_name str or None None The action that the targets run, for example "process", "learn" or an action of a role file. An interaction with no action name is completed with TIMEOUT at the first tick of the manager.
action_kwargs dict or None None The arguments of that action. None becomes {}. The manager refuses names reserved to the framework (max_duration, retry_timeout, delay, action_kwargs, interaction) and fields of the interaction echoed with a different value (see check_consistency_between_action_kwargs_and_interaction_fields).
streams list[str], dict[str, list[str]] or None None The streams that carry the data. parse_streams parses them. Each entry can be a stream name, a group, a user hash (peer_id:name) or a net hash. When streams are given and num_steps is negative, num_steps becomes 1.
data_samples list, dict, str or None None The data itself in place of streams. A dict maps a stream of the requester to one sample and the manager later moves it onto that stream (see resolve). A list holds samples (PIL.Image.Image, torch.Tensor, str). A str is the serialized payload of a list received from the network and is decoded at once. Samples given together with streams are dropped with an error in the log. Samples alone force num_steps to 1.
num_steps int or str -1 How many steps the target runs with one sample per step. -1 means no data-based steps. A behavior file may pass a wildcard string such as "<eval_steps>" that the behavior replaces later.
requester str or None None The peer id of the requester. send fills it with the peer id of the agent on the network where it behaves.
target str, list[str] or None None The targets. A string becomes a one-element list and None becomes [None]. The list is copied.
from_state, to_state str or None None The state of the behavior of the target where the interaction may start and the state where it should end.
timeout float -1.0 The maximum life of the interaction in seconds from its registration. A non-positive value leaves the limit to the manager. The manager applies Custom.DEFAULT_INTER_TIMEOUT (300 seconds) to every interaction and a positive value lower than 300 wins.
callback str or None None The name of an async method of the requester that the manager awaits once with interaction= when the interaction completes.
volatile bool False Asks the targets not to send any status back. The requester completes its own copy with TIMEOUT at the next tick.
forced_uuid str or None "do_not_force" Any value other than the sentinel "do_not_force" becomes the uuid as it is (None included) and the id becomes None. Reserved for special cases.
id str or None "random" "random" draws eight hexadecimal characters. None uses Custom.SYSTEM_INTERACTION_UUID ("sys_system"). Any other string is used as it is.
num_samples_to_stream int -1 The maximum number of samples that the owner of the streams sends for this interaction. -1 streams until completion or timeout. A non-negative value lower than num_steps is logged as an error.

The constructor raises GenException in two cases: (1) a callback on a volatile interaction and (2) a malformed streams argument. It does not contact anybody and does not register the interaction.

from unaiverse.interaction import Interaction

inter = Interaction(action_name="process", target="12D3KooW...",
                    streams={"stdin": ["camera"], "stdtar": ["labels"]},
                    num_steps=50, requester="12D3KooX...")
print(inter.uuid)        # e.g. "3fa1c2d9_12D3KooX..."
print(inter.num_steps)   # 50
print(inter.streams)     # {'stdin': ['camera'], 'stdtar': ['labels'], 'stdext': [], 'stdunk': []}

uuid instance-attribute

uuid = Interaction.build_uuid(self.id, str(self.requester))

The unique key of the interaction, a str of the form <id>_<requester> built by build_uuid. Both sides store the interaction under this key and the samples of its streams travel under it. A forced uuid replaces it as it is.

id instance-attribute

id = _uuid.uuid4().hex[0:8] if id is not None and id == 'random' else id if id is not None else Custom.SYSTEM_INTERACTION_UUID

The short identifier chosen by the requester (str). Two requesters can use the same id because the uuid appends the requester. It is None when the uuid was forced.

requester instance-attribute

requester: str | None = requester

The peer id of the requester (str or None). It is "system" for a system interaction and None for an interaction built without one (see has_dummy_requester).

target instance-attribute

target: list[str | None] = list(target) if isinstance(target, list) else [target]

The list of the targets. Before registration an entry can be a node name, an owner/name reference or a wildcard. register_sent replaces every entry with a peer id and Agent.send then keeps only the targets that the message reached (see update_target). The per-target lists below follow the order of this list.

action_name instance-attribute

action_name = action_name

The name of the requested action (str or None).

action_kwargs instance-attribute

action_kwargs: dict = action_kwargs if action_kwargs is not None else {}

The arguments of the requested action as a dict (never None). Read one argument with get_arg.

status instance-attribute

The current InteractionStatus. The properties created, running, paused and completed read it.

completion_reason instance-attribute

completion_reason: CompletionReason | None = None

The CompletionReason of the whole interaction. It stays None until the interaction completes. With several targets it is the reason of the last target that completed.

destination_state instance-attribute

destination_state: str | None = None

The state that the behavior of the target reached when it completed the action (str or None). On the requester it comes from the status message of the target. A successful process in the default public behavior ends in "generated".

timeout instance-attribute

timeout: float = timeout

The timeout given at construction in seconds (float). A non-positive value means that the interaction has no limit of its own. It travels in the dictionary under the key retry_timeout.

timestamp_created instance-attribute

timestamp_created: float = -1.0

The time of the node clock (clock.get_time(), seconds) at which a manager registered the interaction. It is -1.0 before registration. Four other attributes complete the timing of the interaction.

Attribute Type Meaning
timestamp_started float Clock time of the first mark_running (-1.0 before it).
timestamp_completed float Clock time of the completion (-1.0 before it).
cycle_created, cycle_started, cycle_completed int The same three moments as clock cycles from clock.get_cycle() (-1 before each of them).

num_steps instance-attribute

num_steps: int = num_steps

The number of steps (int, or a wildcard str before the behavior replaces it). -1 marks an interaction without data-based steps. Read it with get_total_steps.

num_samples_to_stream instance-attribute

num_samples_to_stream: int = num_samples_to_stream

The cap on the samples that the owner of the streams sends for this interaction (int). -1 means no cap. See all_samples_streamed.

streams instance-attribute

streams: dict = {}

The stream specification after parsing: a dict with the keys stdin, stdtar, stdext and stdunk, each holding a list of stream references. It is {} for an interaction without streams. During registration the manager replaces the references with user hashes or net hashes.

data_samples instance-attribute

data_samples = []

The samples carried by the interaction itself. It is a list of samples or a dict from stream to sample. The manager moves the samples of a dict onto their streams and then empties this attribute.

callback instance-attribute

callback = callback

The name of the method of the requester to await on completion (str or None). The callback is not part of the dictionary that travels. The copy of a target therefore never has one.

volatile instance-attribute

volatile: bool = volatile

True when the targets must not send a status back (bool).

type instance-attribute

type: InteractionType | None = None

The InteractionType assigned at registration. It is None before registration.

action_ref instance-attribute

action_ref = None

The Action of the behavior that serves the interaction, assigned by set_action_ref on the target and on system interactions. It is None on the copy of the requester.

data_tags instance-attribute

data_tags: dict[str, list[int]] = {}

The data tags that this agent has consumed for the interaction, a dict from stream user hash to the list of tags in the order of consumption. get_new_stream_data_tags compares the current tag of each stream with the last one here to decide whether a sample is fresh. The status message sends this dictionary to the requester.

target_completion_reason instance-attribute

target_completion_reason: list[CompletionReason | None] = [None] * len(self.target)

On the copy of the requester, a list aligned with target that holds the completion reason of each target. Four sibling lists share the same alignment and are reset by update_target.

Attribute Type of each entry Meaning
target_completion_reason CompletionReason or None Why that target completed. It is None until the target completes.
target_destination_state str or None The state that target reached.
target_timestamp_completed float Clock time of its completion (-1.0 before it).
target_cycle_completed int Clock cycle of its completion (-1 before it).
target_data_tags dict[str, list[int]] The data tags that target reported as consumed.

stream_proxy instance-attribute

stream_proxy = StreamProxy()

A StreamProxy bound under the uuid of the interaction to every stream that the manager assigned to it (stdin_streams, stdtar_streams, stdext_streams, owned_streams) and to the samples of data_samples under the keys <data_sample_0>, <data_sample_1> and so on. Iterating over it yields the bound objects. An action such as record reads the streams of the interaction through it.

stdin_streams instance-attribute

stdin_streams = {}

The streams that feed the inputs of the processor for this interaction, a dict from user hash to stream object in the order of the inputs. A missing input with a default value appears under the key <default_input_pos_i> with that value. Four sibling dictionaries complete the assignment made by the manager.

Attribute Content
stdtar_streams The streams used as learning targets of the outputs of the processor.
stdext_streams The streams that fit no input or output of the processor.
owned_streams The streams among the ones above that this agent owns.
lazy_streams The streams attached after registration by add_lazy_stream.

by_insertion_order_id instance-attribute

by_insertion_order_id = -1

The position of the interaction in the queue of its action (int, -1 until the action queues it). Its sibling by_requester_insertion_order_id is the position among the requests of the same requester. Both are maintained by the action and read by is_valid.

set_status_to_created

set_status_to_created() -> None
Source code in unaiverse/interaction.py
def set_status_to_created(self) -> None:
    """Sets the status of the interaction to CREATED."""
    self.status = InteractionStatus.CREATED

Puts the status back to CREATED. It changes nothing else.

build_uuid staticmethod

build_uuid(id: str | None, requester: str | None = None) -> str
Source code in unaiverse/interaction.py
@staticmethod
def build_uuid(id: str | None, requester: str | None = None) -> str:
    """Builds the uuid of an interaction from its id and its requester.

    Args:
        id: The id of the interaction (None means the system interaction id).
        requester: The requester (None means the system interaction label) (default: None).

    Returns:
        The uuid, "<id>_<requester>".
    """
    if id is None:
        id = Custom.SYSTEM_INTERACTION_ID
    if requester is None:
        requester = Custom.SYSTEM_INTERACTION_LABEL
    return id + "_" + requester

Static method that returns the uuid id + "_" + requester. A None id becomes Custom.SYSTEM_INTERACTION_ID ("sys") and a None requester becomes Custom.SYSTEM_INTERACTION_LABEL ("system"). With both None the result is "sys_system". Every system interaction has this uuid.

Interaction.build_uuid("3fa1c2d9", "12D3KooX")  # '3fa1c2d9_12D3KooX'
Interaction.build_uuid(None)                    # 'sys_system'

get_id_from_uuid staticmethod

get_id_from_uuid(uuid: str | None) -> str | None
Source code in unaiverse/interaction.py
@staticmethod
def get_id_from_uuid(uuid: str | None) -> str | None:
    """Extracts the id of an interaction from its uuid.

    Args:
        uuid: The uuid of the interaction.

    Returns:
        The id, or None when the uuid is None.
    """
    if uuid is None:
        return None  # Safety guard
    return uuid.split("_")[0]

Static method that returns the part of uuid before the first _. A None uuid gives None. A forced uuid without _ comes back whole.

created property

created: bool

Read-only property, True when the status is CREATED.

completed property

completed: bool

Read-only property, True when the status is COMPLETED. It gives the same answer as is_completed().

running property

running: bool

Read-only property, True when the status is RUNNING.

paused property

paused: bool

Read-only property, True when the status is PAUSED.

registered_as_sent property

registered_as_sent: bool

Read-only property, True when type is InteractionType.SENT.

registered_as_received property

registered_as_received: bool

Read-only property, True when type is InteractionType.RECEIVED.

registered_as_lazy property

registered_as_lazy: bool

Read-only property, True when type is InteractionType.LAZY.

update_target

update_target(target: str | list[str]) -> None
Source code in unaiverse/interaction.py
def update_target(self, target: str | list[str]) -> None:
    """Sets the target(s) of the interaction, resetting the per-target completion data.

    Args:
        target: A target or a list of targets.
    """
    if isinstance(target, str):
        target = [target]
    self.target = target
    self.target_completion_reason = [None] * len(self.target)
    self.target_data_tags = [{} for _ in range(len(self.target))]
    self.target_timestamp_completed = [-1.] * len(self.target)
    self.target_destination_state = [None] * len(self.target)
    self.target_cycle_completed = [-1] * len(self.target)

Replaces the attribute target with the argument target (a string becomes a one-element list) and resets the five per-target lists to their initial values. After sending, Agent.send calls it with the list of the targets that the message reached.

inc_streamed_samples

inc_streamed_samples() -> None
Source code in unaiverse/interaction.py
def inc_streamed_samples(self) -> None:
    """Increments the counter of the samples streamed for this interaction."""
    self.__num_streamed_samples += 1

Adds one to the private count of the samples streamed for this interaction. The agent calls it after a sample of an owned stream left for at least one recipient.

all_samples_streamed

all_samples_streamed() -> bool
Source code in unaiverse/interaction.py
def all_samples_streamed(self) -> bool:
    """Tells whether all the samples to stream for this interaction were streamed.

    Returns:
        True if the count of streamed samples reached the (positive) number of samples to stream.
    """
    return self.__num_streamed_samples >= self.num_samples_to_stream > 0

Returns True when num_samples_to_stream is positive and the count of streamed samples has reached it. With the default -1 it always returns False. The agent stops sending samples of an interaction for which it returns True.

set_manager

set_manager(im: InteractionManager, stdin_streams: dict[str, Stream | object], stdtar_streams: dict[str, Stream | object], stdext_streams: dict[str, Stream | object], owned_streams: dict[str, Stream | object]) -> None
Source code in unaiverse/interaction.py
def set_manager(self,
                im: 'InteractionManager',
                stdin_streams: dict[str, Stream | object],
                stdtar_streams: dict[str, Stream | object],
                stdext_streams: dict[str, Stream | object],
                owned_streams: dict[str, Stream | object]) -> None:
    """Bind this interaction to its owning InteractionManager and initialize its stream references.

    Args:
        im: The InteractionManager that owns this interaction.
        stdin_streams: Mapping from user-hash to stream objects used as processor inputs.
        stdtar_streams: Mapping from user-hash to stream objects used as processor targets.
        stdext_streams: Mapping from user-hash to stream objects used as extra (non-input) streams.
        owned_streams: Mapping from user-hash to stream objects owned by this agent.
    """
    self.__im = im
    self.timestamp_created = clock.get_time()
    self.cycle_created = clock.get_cycle()

    self.stdin_streams = stdin_streams
    self.stdtar_streams = stdtar_streams
    self.stdext_streams = stdext_streams
    self.owned_streams = owned_streams
    data_samples_dict = {"<data_sample_" + str(i) + ">": self.data_samples[i]
                         for i in range(0, len(self.data_samples))}
    self.stream_proxy.bind(self.stdin_streams | self.stdtar_streams | self.stdext_streams | self.owned_streams |
                           data_samples_dict, uuid=self.uuid)

Binds the interaction to its manager and to the streams that the manager chose. The manager calls it during registration.

Argument Type Meaning
im InteractionManager The manager that owns the interaction.
stdin_streams dict User hash to stream object (or default value) for the inputs of the processor.
stdtar_streams dict The same for the learning targets.
stdext_streams dict The same for the extra streams.
owned_streams dict The same for the streams owned by the agent.

It records timestamp_created and cycle_created from the node clock, stores the four dictionaries and binds stream_proxy to all of them and to the data samples under the uuid of the interaction.

reset_state

reset_state() -> None
Source code in unaiverse/interaction.py
def reset_state(self) -> None:
    """Resets the state, including the step counter and timing metrics, allowing it to be re-run from the
    beginning.
    """
    self.__step_idx = -1
    self.__starting_time = 0.
    self.__timeout_starting_time = 0.

Brings the step index back to -1 and the starting time and timeout starting time back to 0.0. The behavior calls it to rerun an action from its first step. Status, mark and data tags are untouched.

set_mark

set_mark(mark: object) -> None
Source code in unaiverse/interaction.py
def set_mark(self, mark: object) -> None:
    """Store an arbitrary marker object on the interaction."""
    self.__mark = mark

Stores an arbitrary object on the interaction. An action keeps its state in the mark across the ticks in which it returns False. Agent.send with wait_completion=True keeps the sent interaction there and AgentBasics.stepwise keeps its generator there. The action clears the mark when it completes.

get_mark

get_mark() -> object
Source code in unaiverse/interaction.py
def get_mark(self) -> object:
    """Return the marker object previously set by set_mark."""
    return self.__mark

Returns the object stored by set_mark. Without a mark it returns None.

clear_mark

clear_mark() -> None
Source code in unaiverse/interaction.py
def clear_mark(self) -> None:
    """Clear the arbitrary marker object on the interaction."""
    self.__mark = None

Removes the mark.

get_step_idx

get_step_idx() -> int
Source code in unaiverse/interaction.py
def get_step_idx(self) -> int:
    """Return the index of the last completed step (-1 if no steps done yet)."""
    return self.__step_idx

Returns the index of the last step done (int). It is -1 before the first step and num_steps - 1 after the last one.

set_step_idx

set_step_idx(steps: int) -> None
Source code in unaiverse/interaction.py
def set_step_idx(self, steps: int) -> None:
    """Directly assign the current step index.

    Args:
        steps: The step index to set.
    """
    self.__step_idx = steps

Writes the step index directly. The action uses it. A developer who needs to move the step of the running action calls AgentBasics.force_action_step instead.

inc_step_idx

inc_step_idx() -> None
Source code in unaiverse/interaction.py
def inc_step_idx(self) -> None:
    """Increment the step index by one."""
    self.__step_idx += 1

Adds one to the step index. The action calls it after a step that returned True.

dec_step_idx

dec_step_idx() -> None
Source code in unaiverse/interaction.py
def dec_step_idx(self) -> None:
    """Decrement the step index by one."""
    self.__step_idx -= 1

Subtracts one from the step index.

set_starting_time

set_starting_time(t: float) -> None
Source code in unaiverse/interaction.py
def set_starting_time(self, t: float) -> None:
    """Record the wall-clock time at which execution started.

    Args:
        t: Starting timestamp (from ``time.perf_counter()``).
    """
    self.__starting_time = t

Records the time.perf_counter() value t as the moment the action started serving the interaction. is_timed_out measures the max_duration of the transition from it.

set_timeout_starting_time

set_timeout_starting_time(t: float) -> None
Source code in unaiverse/interaction.py
def set_timeout_starting_time(self, t: float) -> None:
    """Record the wall-clock time used as the baseline for next-step retry_timeout checks.

    Args:
        t: Timeout baseline timestamp (from ``time.perf_counter()``).
    """
    self.__timeout_starting_time = t

Records the time.perf_counter() value t as the baseline of the retry_timeout of the transition. The action moves it forward after each successful step.

get_total_steps

get_total_steps() -> int
Source code in unaiverse/interaction.py
def get_total_steps(self) -> int:
    """Retrieves the total number of steps configured for the action.

    Returns:
        An integer representing the total steps.
    """
    return self.num_steps

Returns num_steps.

get_starting_time

get_starting_time() -> float
Source code in unaiverse/interaction.py
def get_starting_time(self) -> float:
    """Retrieves the timestamp when the action's current execution started.

    Returns:
        A float representing the starting time.
    """
    return self.__starting_time

Returns the value recorded by set_starting_time (0.0 before).

get_timeout_starting_time

get_timeout_starting_time() -> float
Source code in unaiverse/interaction.py
def get_timeout_starting_time(self) -> float:
    """Retrieves the timestamp used as the baseline for next-step retry_timeout checks.

    Returns:
        A float representing the retry_timeout starting time.
    """
    return self.__timeout_starting_time

Returns the value recorded by set_timeout_starting_time (0.0 before).

is_multi_steps

is_multi_steps() -> bool
Source code in unaiverse/interaction.py
def is_multi_steps(self) -> bool:
    """Determines if the action is configured to be a multistep action (i.e., not a single-step action).

    Returns:
        A boolean indicating if the action is multistep.
    """

    # The first part of this check sounds weird, I know,
    # it happens if num_steps is specified as a wildcard like <eval_steps>
    return isinstance(self.num_steps, str) or self.num_steps > 1

Returns True when num_steps is greater than one or is still a wildcard string.

is_single_step

is_single_step() -> bool
Source code in unaiverse/interaction.py
def is_single_step(self) -> bool:
    """Return True if this is a single-step action (one data sample or no data at all)."""
    return self.num_steps == 1 or self.num_steps < 0  # Action with a single data sample or no data samples at all

Returns True when num_steps is 1 or negative. With a wildcard string still in num_steps the comparison raises TypeError.

is_valid

is_valid() -> bool
Source code in unaiverse/interaction.py
def is_valid(self) -> bool:
    """Return True if the interaction has been assigned insertion-order IDs by the action."""
    return self.by_insertion_order_id >= 0 and self.by_requester_insertion_order_id >= 0

Returns True once an action has queued the interaction. This happens when both by_insertion_order_id and by_requester_insertion_order_id are non-negative.

is_system

is_system() -> bool
Source code in unaiverse/interaction.py
def is_system(self) -> bool:
    """Return True if the interaction is a system-level interaction."""
    return self.requester == Custom.SYSTEM_INTERACTION_LABEL

Returns True when the requester is "system", the label of the interactions that an agent creates for itself. Several built-in actions branch on it. For example send refuses to run for any requester other than the system.

is_completed

is_completed() -> bool
Source code in unaiverse/interaction.py
def is_completed(self) -> bool:
    """Return True if the interaction status is COMPLETED."""
    return self.status == InteractionStatus.COMPLETED

Returns True when the status is COMPLETED for any reason. A rejected or expired interaction is completed too. Its completion_reason tells these cases apart.

has_dummy_requester

has_dummy_requester() -> bool
Source code in unaiverse/interaction.py
def has_dummy_requester(self) -> bool:
    """Return True if no requester peer ID is set (system-generated interaction)."""
    return self.requester is None

Returns True when requester is None.

set_arg

set_arg(arg_name: str, arg_value: object) -> None
Source code in unaiverse/interaction.py
def set_arg(self, arg_name: str, arg_value: object) -> None:
    """Set or overwrite an action keyword argument.

    Args:
        arg_name: The argument name.
        arg_value: The value to assign.
    """
    self.action_kwargs[arg_name] = arg_value

Writes action_kwargs[arg_name] = arg_value and adds the key when it is missing.

get_arg

get_arg(arg_name: str) -> object
Source code in unaiverse/interaction.py
def get_arg(self, arg_name: str) -> object:
    """Retrieve an action keyword argument by name.

    Args:
        arg_name: The argument name to look up.

    Returns:
        The argument value, or ``None`` if the argument is not present.
    """
    return self.action_kwargs[arg_name] if arg_name in self.action_kwargs else None

Returns action_kwargs[arg_name]. A missing key gives None. A stored None and a missing key give the same result.

was_at_least_one_step_done

was_at_least_one_step_done() -> bool
Source code in unaiverse/interaction.py
def was_at_least_one_step_done(self) -> bool:
    """Return True if at least one execution step has been completed."""
    return self.__step_idx >= 0

Returns True when the step index is non-negative.

was_last_step_done

was_last_step_done() -> bool
Source code in unaiverse/interaction.py
def was_last_step_done(self) -> bool:
    """Determines if the action has reached its completion criteria, either by reaching the total number of steps
    or by exceeding the maximum allowed execution time.

    Returns:
        True if the action is completed, False otherwise.
    """
    return ((self.num_steps < 0 and self.__step_idx == 0) or  # Action with no data (no steps)
            (self.num_steps > 0 and self.__step_idx == self.num_steps - 1))  # Action with one or more steps

Returns True when the last step is done: step 0 for an interaction without data-based steps (num_steps < 0) and step num_steps - 1 otherwise. AgentBasics.is_last_action_step reads it on the current interaction.

is_delayed

is_delayed(starting_time: float) -> bool
Source code in unaiverse/interaction.py
def is_delayed(self, starting_time: float) -> bool:
    """Checks if the action is currently in a delayed state and cannot be executed yet, based on a defined delay
    period.

    Args:
        starting_time: The time the delay period began.

    Returns:
        True if the action is delayed, False otherwise.
    """
    return self.action_ref.get_delay() > 0 and (time.perf_counter() - starting_time) <= self.action_ref.get_delay()

Returns True while less than the delay of the action has passed since starting_time (a time.perf_counter() value). It returns False when the action has no delay. The method needs action_ref.

is_timed_out

is_timed_out() -> bool
Source code in unaiverse/interaction.py
def is_timed_out(self) -> bool:
    """Checks if the action has exceeded its configured retry_timeout period since the last successful
     execution attempt.

    Returns:
        True if the action has timed out, False otherwise.
    """

    # If the action was never started (even a failed attempt), this method has no sense
    if self.__starting_time <= 0.:
        return False

    # Checking global retry_timeout: if too much time passed, no matter if the action started or not,
    # it's retry_timeout!
    if self.action_ref.get_total_time() > 0:
        if self.action_ref.get_total_time() <= (time.perf_counter() - self.__starting_time):
            log.inter(f"Timeout for {self.action_name}! "
                      f"({(time.perf_counter() - self.__starting_time)}/"
                      f"{self.action_ref.get_total_time()})!")
            return True
        else:
            log.debug(f"Running retry_timeout for {self.action_name}! "
                      f"({(time.perf_counter() - self.__starting_time)}/"
                      f"{self.action_ref.get_total_time()})!")

    # Checking next-step retry_timeout
    if self.__timeout_starting_time > 0. and self.action_ref.get_timeout() > 0:
        if self.action_ref.get_timeout() <= (time.perf_counter() - self.__timeout_starting_time):
            log.inter(
                f"Hot retry_timeout for {self.action_name}! "
                f"({(time.perf_counter() - self.__timeout_starting_time)}/"
                f"{self.action_ref.get_timeout()})!")
            return True
        else:
            log.debug(f"Running hot retry_timeout for {self.action_name} "
                      f"({(time.perf_counter() - self.__timeout_starting_time)}/"
                      f"{self.action_ref.get_timeout()})!")
            return False
    else:
        return False

Tells the action whether to give up on the interaction. It returns False before the first attempt. It requires action_ref and returns True in two cases: (1) the action has a positive max_duration and that many seconds have passed since set_starting_time and (2) the action has a positive retry_timeout and that many seconds have passed since set_timeout_starting_time.

set_action_ref

set_action_ref(action_ref: Action) -> None
Source code in unaiverse/interaction.py
def set_action_ref(self, action_ref: "Action") -> None:
    """Bind the interaction to its Action object and validate/augment its argument list.

    Args:
        action_ref: The Action instance that will execute this interaction.
    """
    self.action_ref = action_ref

    # Augmenting argument list, by fusing with the arguments defined in the HSM
    action_kwargs = self.action_kwargs if self.action_kwargs is not None else {}
    self.action_ref.check_provided_args(action_kwargs, exception=True)

    # Force a default retry_timeout on multistep actions, to avoid infinite trials
    if self.is_multi_steps() and self.action_ref.get_timeout() <= 0:
        self.action_ref.set_default_timeout()

Links the interaction to the Action that serves it. The behavior calls it when it accepts a request. It checks action_kwargs against the signature of the action and raises ValueError on an argument that the action does not accept. A multi-step interaction on an action without a retry_timeout gets the default one (Custom.DEFAULT_TIMEOUT, 10 seconds) to prevent endless retries.

has_stream

has_stream(user_hash: str) -> bool
Source code in unaiverse/interaction.py
def has_stream(self, user_hash: str) -> bool:
    """Return True if a stream with the given user hash is already registered.

    Args:
        user_hash: The stream's user-level hash identifier.
    """
    return user_hash in self.stream_proxy or user_hash in self.lazy_streams

Returns True when the stream with user hash user_hash is bound to the stream proxy or attached as a lazy stream.

add_lazy_stream

add_lazy_stream(user_hash: str, stream_obj: Stream, is_owned: bool = False) -> None
Source code in unaiverse/interaction.py
def add_lazy_stream(self, user_hash: str, stream_obj: Stream, is_owned: bool = False) -> None:
    """Lazily attach an additional stream to this interaction after it was created.

    Args:
        user_hash: The stream's user-level hash identifier.
        stream_obj: The stream object to attach.
        is_owned: Whether the stream is owned by the current agent.
    """
    if not self.has_stream(user_hash):
        self.lazy_streams[user_hash] = stream_obj
        if is_owned:
            self.owned_streams[user_hash] = stream_obj
        self.stream_proxy.add_new_bind(user_hash, stream_obj)

Attaches a stream after registration. It does nothing when the stream is already there. Otherwise it stores stream_obj in lazy_streams and binds it to the stream proxy under user_hash. With is_owned=True the stream also goes into owned_streams. The manager calls it through add_lazy_stream_to_interaction.

mark_running

mark_running() -> None
Source code in unaiverse/interaction.py
def mark_running(self) -> None:
    """Mark this interaction as currently running."""
    self.status = InteractionStatus.RUNNING
    if self.timestamp_started <= 0:
        self.timestamp_started = clock.get_time()
        self.cycle_started = clock.get_cycle()

Changes the status to RUNNING. At the first call it also records timestamp_started and cycle_started.

mark_paused

mark_paused() -> None
Source code in unaiverse/interaction.py
def mark_paused(self) -> None:
    """Mark this interaction as currently paused."""
    self.status = InteractionStatus.PAUSED

Changes the status to PAUSED.

mark_completed

mark_completed(reason: CompletionReason, dest_state: str | None = None, target: str | None = None) -> None
Source code in unaiverse/interaction.py
def mark_completed(self, reason: 'CompletionReason', dest_state: str | None = None,
                   target: str | None = None) -> None:
    """Mark this interaction as completed.

    Args:
        reason: The reason for completion.
        dest_state: The destination state reached by completing this action.
        target: The target agent who completed this interaction (Default: None).
    """
    if target is None:
        self.destination_state = dest_state
        self.completion_reason = reason
        self.timestamp_completed = clock.get_time()
        self.cycle_completed = clock.get_cycle()
        self.status = InteractionStatus.COMPLETED

        _time = clock.get_time()
        _cycle = clock.get_cycle()
        self.target: list
        for i, tar in enumerate(self.target):
            if self.target_completion_reason[i] is None:
                self.target_destination_state[i] = dest_state
                self.target_completion_reason[i] = reason  # The completion reason of the whole interaction
                self.target_timestamp_completed[i] = _time
                self.target_cycle_completed[i] = _cycle
    else:
        num_completed = 0
        _time = clock.get_time()
        _cycle = clock.get_cycle()
        for i, tar in enumerate(self.target):
            if tar == target:
                self.target_destination_state[i] = dest_state
                self.target_completion_reason[i] = reason
                self.target_timestamp_completed[i] = _time
                self.target_cycle_completed[i] = _cycle
            if self.target_completion_reason[i] is not None:
                num_completed += 1
        if num_completed == len(self.target):
            self.mark_completed(reason, dest_state)  # The completion reason of the last target who completed

Records a completion. The manager calls it through complete.

Argument Type Default Meaning
reason CompletionReason required Why it completed.
dest_state str or None None The state reached.
target str or None None The target that completed. None completes the whole interaction.

With target=None the interaction becomes COMPLETED with this reason, state and time. Every target that has no reason yet receives the same values. With a target, only the entries of that target change. When the last target completes, the whole interaction completes with the reason and state of that last target.

clear_from_action

clear_from_action() -> None
Source code in unaiverse/interaction.py
def clear_from_action(self) -> None:
    """Deregister this interaction from its action's interaction list."""

    # Clearing interaction from action list
    if self.action_ref is not None:
        self.action_ref.get_list_of_interactions().remove(self)

Removes the interaction from the queue of its action. Without an action_ref it does nothing.

is_expired

is_expired(timeout_secs: float | None = None) -> bool
Source code in unaiverse/interaction.py
def is_expired(self, timeout_secs: float | None = None) -> bool:
    """Check if this interaction has expired based on an external retry_timeout.

    Args:
        timeout_secs: Maximum higher-priority retry_timeout in seconds (default: None).

    Returns:
        True if the interaction is older than timeout_secs.
    """

    # Deciding the real value of timeout_specs also in function of the interaction-specific retry_timeout (if given)
    if timeout_secs is not None and timeout_secs > 0. and self.timeout is not None and self.timeout > 0.:
        timeout_secs = min(timeout_secs, self.timeout)
    elif timeout_secs is None or timeout_secs <= 0.:
        timeout_secs = self.timeout  # It could still be None or < 0.

    if timeout_secs is None or timeout_secs <= 0.:  # Perpetual interaction
        return False
    else:
        return (clock.get_time() - self.timestamp_created) >= timeout_secs

Returns True when the interaction is older than its timeout, measured on the node clock from timestamp_created. The timeout is the smaller positive value between timeout_secs and the timeout of the interaction. Without any positive value the interaction never expires. The manager calls it with Custom.DEFAULT_INTER_TIMEOUT (300 seconds).

get_new_stream_data_tags

get_new_stream_data_tags(all_fresh_or_fail: bool = False) -> dict[str, list[int]] | None
Source code in unaiverse/interaction.py
def get_new_stream_data_tags(self, all_fresh_or_fail: bool = False) -> dict[str, list[int]] | None:
    """Checks all streams involved in this interaction, and if they have fresh data it returns their tags.

    Args:
        all_fresh_or_fail: If True, return None if there is at least one stream with no fresh data (Default: False).

    Returns:
        A dictionary "stream user hash to data tag", only involving streams with fresh data. It can return None if
            the all_fresh_or_fail option was turned on.
    """
    data_tags = {}
    for stream_user_hash, stream_obj in self.stream_proxy.items():

        # Skipping data samples and default input values
        if not isinstance(stream_obj, Stream):
            continue

        if (stream_user_hash in self.data_tags and
                len(self.data_tags[stream_user_hash]) > 0):
            last_handled_data_tag = self.data_tags[stream_user_hash][-1]
        else:
            last_handled_data_tag = None

        # Check if stream has data with a tag not yet consumed by this interaction
        current_tag = stream_obj.get_tag(self.uuid)
        if current_tag is None and self.is_system():

            # Lazy/system interactions may read sources that publish under uuid=None
            # (e.g. 'record' with record_uuid=None reading world streams): evaluate
            # freshness on the None slot in that case.
            current_tag = stream_obj.get_tag(None)

        if current_tag is None or (last_handled_data_tag is not None and current_tag == last_handled_data_tag):
            if all_fresh_or_fail:
                return None
            else:
                continue

        # Storing
        data_tags[stream_user_hash] = [current_tag]
    return data_tags

Finds the streams of the interaction that carry a sample not yet consumed. For each stream in the stream proxy (data samples and default values are skipped) it reads the tag stored under the uuid. For a system interaction without data under its uuid the method reads the tag of the None slot. A stream keeps in that slot the data published outside any interaction. A stream counts as fresh when it has a tag that differs from the last one in data_tags.

Argument Type Default Meaning
all_fresh_or_fail bool False Return None as soon as one stream is not fresh.

It returns a dict from stream user hash to a one-element list with the fresh tag. With all_fresh_or_fail=True and a stale stream it returns None. An interaction without streams returns {}.

record_data_tags

record_data_tags(data_tags: dict[str, list[int]] | None = None, target: str | None = None) -> None
Source code in unaiverse/interaction.py
def record_data_tags(self, data_tags: dict[str, list[int]] | None = None, target: str | None = None) -> None:
    """Record that data with the given tag was received for this interaction.

    Args:
        data_tags: The data tags/sequence numbers.
        target: The agent who handled the data tags (if None, then it's the current agent).
    """
    if data_tags is None:
        data_tags: dict[str, list[int]] | None = self.get_new_stream_data_tags()

    if data_tags is None or len(data_tags) == 0:
        return

    if target is None:
        handled_data_tags = self.data_tags
    else:
        if target in self.target:
            i = self.target.index(target)
            handled_data_tags = self.target_data_tags[i]
        else:
            log.error(f"Invalid target {target} specified to record data tags: "
                      f"it does not exist in the list of targets ({self.target}) of "
                      f"interaction with UUID {self.uuid}")
            return

    _time = clock.get_time()
    for stream_name, list_of_data_tag in data_tags.items():
        if stream_name not in handled_data_tags:
            handled_data_tags[stream_name] = []
        handled_data_tags[stream_name] += list_of_data_tag

Appends consumed tags to the tag history of this agent or of one target.

Argument Type Default Meaning
data_tags dict[str, list[int]] or None None The tags to record. None takes the fresh tags from get_new_stream_data_tags().
target str or None None None records in data_tags (this agent). A target records in its entry of target_data_tags. An unknown target is logged and ignored.

The action calls it after a step and the manager calls it with the tags of a status message.

check_if_doable

check_if_doable() -> bool
Source code in unaiverse/interaction.py
def check_if_doable(self) -> bool:
    """Return True if the interaction can currently be executed.

    Delegates to the owning InteractionManager when present; for system interactions without a manager,
    returns True as long as the interaction is not yet completed.
    """
    if self.__im is not None:
        return self.__im.check_if_doable(self)
    else:
        return not self.completed  # System interactions does not have an interaction manager

Returns True when the interaction can run now. With a manager it delegates to InteractionManager.check_if_doable. Without one (a system interaction) it returns True until the interaction completes.

alter_arg

alter_arg(arg_name: str, arg_value: object) -> bool
Source code in unaiverse/interaction.py
def alter_arg(self, arg_name: str, arg_value: object) -> bool:
    """Overwrite an existing action keyword argument, leaving the dict unchanged if the key is absent.

    Args:
        arg_name: The argument name to update.
        arg_value: The new value to assign.

    Returns:
        True if the argument existed and was updated; False otherwise.
    """
    if arg_name in self.action_kwargs:
        self.action_kwargs[arg_name] = arg_value
        return True
    else:
        return False

Overwrites action_kwargs[arg_name] only when the key exists. It returns True when it changed the value and False when the key is missing.

to_dict

to_dict() -> dict
Source code in unaiverse/interaction.py
def to_dict(self) -> dict:
    """Serialize this interaction for network transmission.

    Returns:
        A dictionary representation of this interaction.
    """
    assert isinstance(self.data_samples, list)
    if len(self.data_samples) > 0 and len(self.streams) > 0:
        log.critical("You are trying to convert to dictionary (to_dict) an interaction object where both streams "
                     "and data_samples are specified, that is unexpected, and might create troubles when sent "
                     "through the net. Only one of them can be provided")
    return {
        'id': self.id,
        'uuid': self.uuid,
        'action_name': self.action_name,
        'requester': self.requester,
        'target': self.target,
        'action_kwargs': self.action_kwargs,
        'streams': self.streams,
        'data_samples': serialize_payload(self.data_samples),
        'num_steps': self.num_steps,
        'completion_reason': self.completion_reason.value if self.completion_reason else None,
        'destination_state': self.destination_state,
        'from_state': self.from_state,
        'to_state': self.to_state,
        'retry_timeout': self.timeout,
        'volatile': self.volatile,
        'status': self.status.value,
        'num_samples_to_stream': self.num_samples_to_stream
    }

Returns the dictionary that travels on the network. Its keys are id, uuid, action_name, requester, target, action_kwargs, streams, data_samples (serialized), num_steps, completion_reason (the value or None), destination_state, from_state, to_state, retry_timeout (the timeout attribute), volatile, status (the value) and num_samples_to_stream. The callback and every local attribute stay on the requester. It logs a critical message when both streams and data samples are present.

from_dict classmethod

from_dict(d: dict) -> Interaction
Source code in unaiverse/interaction.py
@classmethod
def from_dict(cls, d: dict) -> 'Interaction':
    """Deserialize an Interaction from a dictionary.

    Args:
        d: Dictionary from to_dict().

    Returns:
        A new Interaction instance.
    """
    interaction = cls(
        id=d['id'],
        action_name=d['action_name'],
        action_kwargs=d.get('action_kwargs', {}),
        streams=d.get('streams', None),
        data_samples=d.get('data_samples', None),
        num_steps=d.get('num_steps', -1),
        requester=d.get('requester'),
        target=d.get('target'),
        from_state=d.get('from_state'),
        to_state=d.get('to_state'),
        volatile=d.get('volatile', False),
        timeout=d.get('retry_timeout', -1.),
        num_samples_to_stream=d.get('num_samples_to_stream', -1),
    )
    interaction.uuid = d['uuid']
    interaction.status = InteractionStatus(d['status'])
    if d.get('completion_reason'):
        interaction.completion_reason = CompletionReason(d['completion_reason'])
    interaction.destination_state = d.get('destination_state')
    return interaction

Class method that rebuilds an interaction from the output of to_dict. It passes the fields to the constructor and then restores uuid, status, completion_reason and destination_state from the dictionary. The node calls it on every incoming interaction.

to_status_dict

to_status_dict(status_generated_by: str) -> dict
Source code in unaiverse/interaction.py
def to_status_dict(self, status_generated_by: str) -> dict:
    """Build a minimal status dict for status update messages.

    Args:
        status_generated_by: The agent who generate this dict.

    Returns:
        A dictionary with status_generated_by, uuid, status, completion_reason, destination_state, and data_tag.
    """
    return {
        'status_generated_by': status_generated_by,
        'uuid': self.uuid,
        'status': self.status.value,
        'completion_reason': self.completion_reason.value if self.completion_reason else None,
        'destination_state': self.destination_state,
        'data_tags': self.data_tags if len(self.data_tags) > 0 else None,
    }

Returns the status message that a target sends to the requester: status_generated_by (the argument, the peer id of the target on the network of the interaction), uuid, status, completion_reason, destination_state and data_tags (None when empty).

to_code_str

to_code_str(include_id: bool = False, include_received_tags: bool = False) -> str
Source code in unaiverse/interaction.py
def to_code_str(self, include_id: bool = False, include_received_tags: bool = False) -> str:
    """Return a compact single-line representation for logs and debugging.

    Args:
        include_id: Prepend the interaction UUID to the output when True.
        include_received_tags: Append the received data tags when True.

    Returns:
        A compact string describing the interaction.
    """
    s = ""
    t = self.target

    if include_id:
        s = f"{self.uuid} => "
    if include_received_tags:
        t: list[str] = []
        for i, tar in enumerate(self.target):
            all_tags = [str(num) for sublist in self.target_data_tags[i].values() for num in sublist]
            if all_tags:
                t.append(f"{tar}_(" + ",".join(all_tags) + ")")
            else:
                t.append(f"{tar}")

    return s + (f"artss:{self.action_name}|{self.requester}|{t}|"
                f"{self.stream_proxy}|{self.status.value[0:3]}" +
                (("_" + self.completion_reason.value[0:3]) if self.completion_reason is not None else ""))

Returns a one-line description for the logs: artss:<action>|<requester>|<targets>|<stream proxy>|<first three letters of the status> followed by _ and the first three letters of the completion reason when there is one. include_id=True prepends <uuid> =>. include_received_tags=True writes each target as <peer id>_(<tags>) with the tags that it reported.

to_str

to_str() -> str
Source code in unaiverse/interaction.py
def to_str(self) -> str:
    """Return a JSON-encoded string with the core interaction fields for logging.

    Returns:
        A JSON string containing requester, action_kwargs, timestamp_created, and uuid.
    """
    return json.dumps([self.requester, self.action_kwargs, self.timestamp_created, self.uuid])

Returns the JSON string of the list [requester, action_kwargs, timestamp_created, uuid].

parse_streams

parse_streams(streams: list | dict) -> None
Source code in unaiverse/interaction.py
def parse_streams(self, streams: list | dict) -> None:
    """Parse the list of streams provided by the user, standardizing its format and saving it.

    The user can specify streams in these two ways, where "stream_hash_j" can be just the stream name, the stream
    group, the net hash, or the user hash.
        (1) [..., stream_hash_j (str), ...]
        (2) {
                "stdin": [..., stream_hash_j (str), ...],
                "stdtar": [..., stream_hash_k (str), ...],
                "stdext": [..., stream_hash_z (str), ...],
                "stdunk": [..., stream_hash_z (str), ...],
            }

        The last one (2) optionally specifies if the stream is expected to become an input of the processor
        ('stdin'), a target ('stdtar'), and extra stream ('stdext'), or no preferences (None).
        Notice that this choice could be re-arranged by the Interaction Manager, in function of the actual
        capabilities of the processor.

    Args:
        streams (list | dict): The list or dict of streams (see the example above).
    """
    invalid_msg = f'Invalid syntax for streams involved in an interaction: {streams}'
    self.streams = {"stdin": [], "stdtar": [], "stdext": [], "stdunk": []}

    if isinstance(streams, list):
        for stream in streams:
            if not isinstance(stream, str):
                raise GenException(invalid_msg)
            self.streams["stdunk"].append(stream)
    elif isinstance(streams, dict):
        for redirect, streams_list in streams.items():
            if redirect not in self.streams:
                raise GenException(invalid_msg)
            for stream in streams_list:
                if not isinstance(stream, str):
                    raise GenException(invalid_msg)
            self.streams[redirect] = list(streams_list)  # Shallow copy (that's why we have "list(...)" - NEEDED!)
    else:
        raise GenException(invalid_msg)

Normalizes the stream specification into streams. Each reference is a str: a stream name, a group, a user hash or a net hash.

  1. A list puts every reference under stdunk. The target is then free to place it.
  2. A dictionary with any of the keys stdin, stdtar, stdext and stdunk keeps each list under its key and copies it. stdin asks for an input of the processor of the target, stdtar for a learning target and stdext for an extra stream. The target may still move a stream that does not fit (see match_streams).

Any other type, an unknown key or a reference that is not a string raises GenException. The result always has the four keys.

InteractionManager

InteractionManager(agent: AgentBasics, max_interactions: int = -1)
Source code in unaiverse/interaction.py
def __init__(self, agent: "AgentBasics", max_interactions: int = -1) -> None:
    """Create an InteractionManager.

    Args:
        agent: Back-reference to the owning agent (AgentBasics instance).
        max_interactions: Maximum number of simultaneously tracked interactions (sent + received + lazy).
    """
    self.agent = agent
    self.max_interactions = max_interactions if max_interactions > 0 else Custom.MAX_INTERACTIONS
    self.sent: dict[str | None, Interaction] = {}       # uuid -> Interaction (sent by this agent)
    self.received: dict[str | None, Interaction] = {}   # uuid -> Interaction (received from others)
    self.lazy: dict[str | None, Interaction] = {}   # uuid -> Interaction (added by you)
    self.current: Interaction | None = None      # Currently executing interaction
    self.last_registered: Interaction | None = None
    self.sent_recently_completed: set[Interaction] = set()  # Completed interactions
    self.received_recently_completed: set[Interaction] = set()  # Completed interactions
    self.lazy_recently_completed: set[Interaction] = set()  # Completed interactions

The bookkeeper of the interactions of one agent. AgentBasics creates it in its constructor as agent.im with max_interactions=Custom.MAX_INTERACTIONS (100). A developer reads it (agent.im.sent, agent.im.get_current()) and rarely calls its methods. The node, the behavior and the built-in actions drive it.

Argument Type Default Meaning
agent AgentBasics required The agent that owns the manager. The manager reads its streams, its known agents and its behaviors.
max_interactions int -1 The maximum number of open interactions (sent, received and lazy together). A non-positive value uses Custom.MAX_INTERACTIONS.

The manager keeps three groups. Each group has a dict from uuid to Interaction for the open interactions and a set for the interactions completed and not yet drained.

Group Open Completed, not yet drained Who creates them
Sent sent sent_recently_completed Agent.send on this agent.
Received received received_recently_completed Other agents.
Lazy lazy lazy_recently_completed The behavior of this agent for its own actions (system interactions) and the agent for samples that arrive under an interaction it does not know.

agent instance-attribute

agent = agent

The owning agent.

max_interactions instance-attribute

max_interactions = max_interactions if max_interactions > 0 else Custom.MAX_INTERACTIONS

The capacity of the manager (int). room_for_registration compares the open interactions against it.

sent instance-attribute

sent: dict[str | None, Interaction] = {}

The open interactions sent by this agent as a dict from uuid to Interaction. Agent.all_sent_completed scans it.

received instance-attribute

received: dict[str | None, Interaction] = {}

The open interactions received from other agents as a dict from uuid to Interaction.

lazy instance-attribute

lazy: dict[str | None, Interaction] = {}

The open lazy interactions as a dict from uuid to Interaction.

current instance-attribute

current: Interaction | None = None

The interaction served by the running action (Interaction or None). Read it with get_current.

last_registered instance-attribute

last_registered: Interaction | None = None

The last interaction registered in any group (Interaction or None).

sent_recently_completed instance-attribute

sent_recently_completed: set[Interaction] = set()

The set of the sent interactions completed and not yet drained. Agent.on_received scans it together with sent because an answer can arrive after the status. Its siblings received_recently_completed and lazy_recently_completed hold the other two groups.

room_for_registration

room_for_registration() -> bool
Source code in unaiverse/interaction.py
def room_for_registration(self) -> bool:
    """Return True if there is capacity to register another interaction."""
    return len(self.sent) + len(self.received) + len(self.lazy) < self.max_interactions

Returns True when the open interactions (sent, received and lazy, completed ones excluded) are fewer than max_interactions.

count_interactions

count_interactions() -> int
Source code in unaiverse/interaction.py
def count_interactions(self) -> int:
    """Return the total number of tracked interactions, including recently completed ones."""
    return (len(self.sent) + len(self.received) + len(self.lazy) +
            len(self.sent_recently_completed) + len(self.received_recently_completed) +
            len(self.lazy_recently_completed))

Returns the number of open interactions plus the completed ones not yet drained.

clear_from_all_streams

clear_from_all_streams(interaction: Interaction, clear_data: bool = False) -> None
Source code in unaiverse/interaction.py
def clear_from_all_streams(self, interaction: Interaction, clear_data: bool = False) -> None:
    """Remove the given interaction from every stream that references it.

    Args:
        interaction: The interaction to deregister from all the known streams.
        clear_data: Default False. Forces the removal of the stream data associated to this interaction.
    """
    for stream_obj in self.agent.known_streams_by_user_hash.values():
        if stream_obj.has_interaction(interaction.uuid):
            stream_obj.remove_interaction(interaction)
            if clear_data:
                stream_obj.remove_data(interaction.uuid)

Detaches interaction from every known stream of the agent that references its uuid. With clear_data=True it also deletes the data that those streams hold under the uuid.

unregister_all

unregister_all() -> None
Source code in unaiverse/interaction.py
def unregister_all(self) -> None:
    """Deregister all current interactions"""
    all_interactions = (set(self.sent.values()) | set(self.received.values()) | set(self.lazy.values()))
    for interaction in all_interactions:
        self.unregister(interaction)

Calls unregister on every open interaction. A running interaction stays.

unregister

unregister(interaction: Interaction) -> bool
Source code in unaiverse/interaction.py
def unregister(self, interaction: Interaction) -> bool:
    """Deregister an interaction from all tracking dicts and dissociate it from streams and actions.

    Args:
        interaction: The interaction to remove.

    Returns:
        True if the interaction was found and removed from at least one tracking dict.
    """
    if interaction.status == InteractionStatus.RUNNING:  # Avoid de-registering a currently running interaction
        return False

    interaction.clear_from_action()
    self.clear_from_all_streams(interaction)
    found = False
    if self.sent.get(interaction.uuid) is interaction:
        del self.sent[interaction.uuid]
        found = True
    if self.received.get(interaction.uuid) is interaction:
        del self.received[interaction.uuid]
        found = True
    if self.lazy.get(interaction.uuid) is interaction:
        del self.lazy[interaction.uuid]
        found = True
    return found

Forgets an interaction without completing it. The method removes the interaction from its action and from every stream and deletes it from sent, received and lazy. It returns False without changes for a RUNNING interaction and otherwise True when it found the interaction in at least one group. No status is sent and no callback runs. Agent.send uses it when no target was reached.

register_sent

register_sent(interaction: Interaction, public: bool) -> bool
Source code in unaiverse/interaction.py
def register_sent(self, interaction: Interaction, public: bool) -> bool:
    """Register an interaction that this agent has sent.

    Args:
        interaction: The Interaction to register.
        public: Whether the interaction is about a public agent or a private/world one.

    Returns:
        True if registration succeeded; False if there is no room or the streams are invalid.
    """
    existing = self.sent.get(interaction.uuid)
    if existing is not None and existing is not interaction:
        log.error(f"UUID collision on {interaction.uuid}, refusing to evict an in-flight interaction")
        return False

    self.__check_callback_method(interaction)
    if not self.room_for_registration():
        log.error(f"No more room for interactions (limit: {self.max_interactions})")
        return False

    if not InteractionManager.check_consistency_between_action_kwargs_and_interaction_fields(interaction):
        return False  # The error message is printed inside the method

    # This will resolve target names, data samples, stream names
    if not self.resolve(interaction, public):
        return False

    #  Ensuring all the streams mentioned in the interaction are known, and normalizing them
    _, expanded_owned_streams = self.expand_and_normalize_streams(interaction)

    # Converting format for owned streams (no matter what the matching routine decided)
    owned_user_hashes_to_stream_objs = {_stream_user_hash: self.agent.known_streams_by_user_hash[_stream_user_hash]
                                        for _streams_list in expanded_owned_streams.values()
                                        for _stream_user_hash in _streams_list}

    for stream_obj in owned_user_hashes_to_stream_objs.values():
        stream_obj.add_interaction(interaction)

    interaction.set_manager(self, stdin_streams={}, stdtar_streams={}, stdext_streams={},
                            owned_streams=owned_user_hashes_to_stream_objs)

    # No matter what the interaction does: the processor output streams of the target be aware of the possibility
    # that this interaction might yield new data
    for target_agent in interaction.target:
        assert target_agent is not None
        streams_of_target_agent = self.agent.find_streams(target_agent, 'processor', discard_owned=True)
        for stream_dict in streams_of_target_agent.values():
            for stream in stream_dict.values():
                stream.add_interaction(interaction)

    # Registering
    self.sent[interaction.uuid] = interaction

    interaction.status = InteractionStatus.REQUESTED
    interaction.type = InteractionType.SENT
    self.last_registered = interaction
    return True

Registers an interaction that this agent is about to send. Agent.send calls it before the message leaves.

Argument Type Meaning
interaction Interaction The interaction to register.
public bool True on the public network and False in the world. It decides which streams the names resolve to.

The steps are the following.

  1. It refuses the interaction when a different one is already registered with the same uuid.
  2. It checks the callback (a critical log when the method is missing or its signature is wrong), the capacity and the action arguments.
  3. It resolves targets and streams with resolve.
  4. It attaches the interaction to the owned streams that it names and to the processor streams of every target. The answers that arrive on those streams then belong to it.
  5. It stores it in sent with status REQUESTED and type SENT.

It returns True on success and False with an error in the log otherwise.

register_received

register_received(interaction: Interaction, public: bool) -> bool
Source code in unaiverse/interaction.py
def register_received(self, interaction: Interaction, public: bool) -> bool:
    """Register an interaction received from another agent.

    Args:
        interaction: The Interaction to register.
        public: Whether the interaction is about a public agent or a private/world one.

    Returns:
        True if registration succeeded; False if there is no room, streams are invalid, or matching failed.
    """
    existing = self.received.get(interaction.uuid)
    if existing is not None and existing is not interaction:
        log.error(f"UUID collision on {interaction.uuid}, refusing to evict an in-flight interaction")
        return False

    if self.__register_received_or_lazy(interaction, public):
        self.received[interaction.uuid] = interaction

        interaction.status = InteractionStatus.RECEIVED
        interaction.type = InteractionType.RECEIVED
        return True
    else:
        return False

Registers an interaction received from another agent. The agent calls it after the behavior accepted the request (see AgentBasics.inject_received_interaction). Besides the checks of register_sent it requires a requester that the agent knows. It resolves the streams without touching the targets and assigns them to the inputs, targets and extras of the processor with match_streams. It then attaches the interaction to those streams and to the processor output streams of the same network. The output of the processor thus travels back to the requester. It stores the interaction in received with status and type RECEIVED. It returns False when a check fails or when a required input of the processor has no stream and no default value.

register_lazy

register_lazy(interaction: Interaction, public: bool) -> bool
Source code in unaiverse/interaction.py
def register_lazy(self, interaction: Interaction, public: bool) -> bool:
    """Register an interaction that you manually generated within this agent.

    Args:
        interaction: The Interaction to register.
        public: Whether the interaction is about a public agent or a private/world one.

    Returns:
        True if registration succeeded; False if there is no room or the streams are invalid.
    """
    existing = self.lazy.get(interaction.uuid)
    if existing is not None and existing is not interaction:
        log.error(f"UUID collision on {interaction.uuid}, refusing to evict an in-flight interaction")
        return False

    if self.__register_received_or_lazy(interaction, public):
        self.lazy[interaction.uuid] = interaction

        interaction.status = InteractionStatus.LAZY
        interaction.type = InteractionType.LAZY
        return True
    else:
        return False

Registers an interaction created inside this agent and runs the same checks as register_received. A system requester is accepted. It stores the interaction in lazy with status and type LAZY. The behavior calls it for the system interaction of an action that runs on its own initiative.

resolve

resolve(interaction: Interaction, public: bool, resolve_target: bool = True) -> bool
Source code in unaiverse/interaction.py
def resolve(self, interaction: Interaction, public: bool, resolve_target: bool = True) -> bool:

    # A. Resolving targets
    """Resolves the targets and the streams of an interaction to the ones known by the agent.

    It resolves the target references to peer ids, moves the data samples given as a dictionary into the
    corresponding streams (turning the interaction into a stream-based one), and resolves the stream references.

    Args:
        interaction: The interaction to resolve.
        public: True when the interaction is on the public network, False for the world one.
        resolve_target: Whether to resolve the targets too (default: True).

    Returns:
        True if everything was resolved, False otherwise (the error is logged).
    """
    if resolve_target:
        target = interaction.target
        if target is not None:
            for i, _target in enumerate(target):
                assert _target is not None
                _target_bck = _target
                _target = self.agent.resolve_agent_ref(_target)
                if _target is not None:
                    target[i] = _target
                else:
                    log.error(f"Unknown target specified in an interaction ({_target_bck})")
                    return False

    # B. Moving data samples to streams, if needed (when data_samples is a dictionary)
    # In this case, "streams" must be None (if not None, then the data_samples field is ignored)
    already_resolved = False
    if isinstance(interaction.data_samples, dict):

        # This is already an empty list (otherwise the data_samples field would not be there), but better
        # be extra safe
        streams = []
        for stream_hash, data_sample in interaction.data_samples.items():
            stream_user_hash_or_net_hash = self.agent.resolve_stream_ref(stream_hash, public)
            if Stream.is_net_hash(stream_user_hash_or_net_hash):
                log.error("When using a stream name in the data sample field of an interaction, "
                          "it MUST be provided in the form of a stream hash or something that can be unambiguously "
                          "resolved to a stream hash")
                return False
            if stream_user_hash_or_net_hash is None:
                log.error(f"Unknown stream hash specified in an interaction ({stream_hash})")
                return False
            stream_user_hash = stream_user_hash_or_net_hash
            stream: Stream = self.agent.known_streams_by_user_hash[stream_user_hash]
            stream.set(data_sample, uuid=interaction.uuid)

            # Appending the stream to the interaction, that now looks like a stream-based interaction
            streams.append(stream_user_hash)

        # Purging
        interaction.data_samples = []
        interaction.parse_streams(streams)  # Rebuilding the stream dictionaries
        already_resolved = True

    # C. Resolving streams
    streams = interaction.streams
    if streams is not None and not already_resolved:
        streams: dict
        for redirect, streams_list in streams.items():
            for j, stream_hash in enumerate(streams_list):
                stream_user_hash_or_net_hash = self.agent.resolve_stream_ref(stream_hash, public)
                if stream_user_hash_or_net_hash is None:
                    log.error(f"Unknown stream hash specified in an interaction ({stream_hash})")
                    return False
                streams_list[j] = stream_user_hash_or_net_hash  # If it is a net hash, it will be expanded later
    return True

Resolves the references of an interaction (targets, keys of the samples and streams) to the peer ids and stream hashes that the agent knows. It works in three steps.

  1. With resolve_target=True it replaces every target with the peer id returned by AgentBasics.resolve_agent_ref. An unknown target fails the call.
  2. When data_samples is a dict, it resolves each key to a stream user hash, writes the sample on that stream under the uuid of the interaction, empties data_samples and rebuilds streams from the resolved user hashes. A key that resolves to a net hash (a group with more than one stream) fails the call.
  3. Otherwise it resolves each stream reference with AgentBasics.resolve_stream_ref on the network given by public. An unknown reference fails the call.

It returns True when everything resolved and False with an error in the log otherwise. The interaction is modified in place.

expand_and_normalize_streams

expand_and_normalize_streams(interaction: Interaction) -> tuple[dict[str | None, list[str]], dict[str | None, list[str]]]
Source code in unaiverse/interaction.py
def expand_and_normalize_streams(self, interaction: Interaction) -> (
        tuple[dict[str | None, list[str]], dict[str | None, list[str]]]):
    """Resolve all stream references in an interaction to fully-populated stream dicts.

    Translates user-level and net-level hashes into detailed dicts containing ``user_hash``,
    ``net_hash``, ``name``, ``group``, and the stream object itself, grouped by their suggested
    redirection (``'stdin'``, ``'stdtar'``, ``'stdext'``, or ``None``).

    Args:
        interaction: The interaction whose stream list should be expanded.

    Returns:
        A 2-tuple ``(expanded_streams, expanded_owned_streams)`` where each element is a dict
        keyed by redirection hint (``'stdin'``, ``'stdtar'``, ``'stdext'``, ``None``) mapping to
        lists of fully-populated stream dicts.
    """

    # Guessing net hash and specific name af each stream: if the name was not provided, then all the streams of the
    # group are considered. Generating a full list of streams, distinguishing them in function of their suggested
    # redirection, i.e., 'stdin', 'stdtar', 'stdext', None (meaning 'no suggestions').
    expanded_streams = {'stdin': [], 'stdtar': [], 'stdext': [], "stdunk": []}
    expanded_owned_streams = {'stdin': [], 'stdtar': [], 'stdext': [], "stdunk": []}

    # Checking
    if len(interaction.streams) == 0:
        return expanded_streams, expanded_owned_streams

    for redirect, streams_list in interaction.streams.items():
        for stream_hash in streams_list:

            if Stream.is_user_hash(stream_hash):
                expanded_streams[redirect].append(stream_hash)
                if stream_hash in self.agent.owned_streams_by_user_hash:
                    expanded_owned_streams[redirect].append(stream_hash)

            elif Stream.is_net_hash(stream_hash):
                streams = self.agent.known_streams[stream_hash]
                for stream_obj in streams.values():
                    _stream_hash = DataProps.user_hash_from_net_hash(stream_hash, stream_obj.props.get_name())
                    expanded_streams[redirect].append(_stream_hash)
                    if _stream_hash in self.agent.owned_streams_by_user_hash:
                        expanded_owned_streams[redirect].append(_stream_hash)
    return expanded_streams, expanded_owned_streams

Expands the resolved stream references of an interaction into user hashes. A user hash stays as it is. A net hash becomes the user hashes of all the streams of its group. It returns two dicts with the keys stdin, stdtar, stdext and stdunk: all the expanded user hashes and the ones among them that the agent owns. A net hash that the agent does not know raises KeyError.

match_streams

match_streams(expanded_streams: dict) -> tuple[bool, dict, dict, dict, dict]
Source code in unaiverse/interaction.py
def match_streams(self, expanded_streams: dict) -> tuple[bool, dict, dict, dict, dict]:
    """Assign expanded stream dicts to stdin, stdtar, or stdext based on processor compatibility.

    Attempts to match streams to the processor's input and output argument slots, following any
    redirection hints.  Streams that do not fit a processor slot are placed in stdext.

    Args:
        expanded_streams: The output of ``expand_and_normalize_streams``; a dict keyed by
            redirection hint (``'stdin'``, ``'stdtar'``, ``'stdext'``, ``None``) containing lists
            of fully-populated stream dicts.

    Returns:
        A 5-tuple ``(valid, stdin_streams, stdtar_streams, stdext_streams, stdunk_streams)`` where ``valid`` is
        False if required processor inputs have no matching stream and no default value, and the
        remaining three elements are ``{user_hash: stream_obj}`` dicts for each category.
    """

    # Assigning streams to 'stdin' or 'stdext', following the given suggestions, when possible, and being a bit
    # heuristic for all the not-well-defined cases
    processor_will_be_used = len(expanded_streams['stdin']) > 0 or len(expanded_streams["stdunk"]) > 0
    stdin_streams = {}
    stdtar_streams = {}
    stdext_streams = {}
    owned_streams = {}

    for user_hash in expanded_streams['stdext']:
        if user_hash not in self.agent.known_streams_by_user_hash:
            return False, {}, {}, {}, {}
        stdext_streams[user_hash] = self.agent.known_streams_by_user_hash[user_hash]
        if user_hash in self.agent.owned_streams_by_user_hash:
            owned_streams[user_hash] = stdext_streams[user_hash]

    # We try to match the 'stdin' suggestions with the different input arguments of the processors.
    # We also consider the streams with no specific suggestions (lower priority).
    if processor_will_be_used:
        sources = ['stdin', 'stdunk']
        assert self.agent.proc_inputs is not None
        pos_stdin_streams = [None] * len(self.agent.proc_inputs)
        for i in range(len(self.agent.proc_inputs)):
            found_match = -1
            for source in sources:
                for j, user_hash in enumerate(expanded_streams[source]):
                    if user_hash not in self.agent.known_streams_by_user_hash:
                        return False, {}, {}, {}, {}
                    stream_obj = self.agent.known_streams_by_user_hash[user_hash]
                    net_hash = DataProps.build_net_hash(DataProps.peer_id_from_user_hash(user_hash),
                                                        stream_obj.is_pubsub(),
                                                        stream_obj.props.name_or_group())

                    name = stream_obj.props.get_name()

                    # If the current input stream is compatible with the i-th input slot...
                    if (net_hash, name) in self.agent.compat_in_streams[i]:
                        pos_stdin_streams[i] = user_hash
                        found_match = j
                        break

                if found_match >= 0:
                    del expanded_streams[source][found_match]  # Removing the stream from the suggestions
                    break

        # We ensured that all the not-filled-arguments of the processor have a default value, otherwise no ways
        for i in range(len(self.agent.proc_inputs)):
            if pos_stdin_streams[i] is None:
                assert self.agent.proc_optional_inputs is not None
                if not self.agent.proc_optional_inputs[i]["has_default"]:
                    return False, {}, {}, {}, {}
                else:
                    stdin_streams["<default_input_pos_" + str(i) + ">"] = (
                        self.agent.proc_optional_inputs)[i]["default_value"]
            else:
                stdin_streams[pos_stdin_streams[i]] = self.agent.known_streams_by_user_hash[pos_stdin_streams[i]]
                if pos_stdin_streams[i] in self.agent.owned_streams_by_user_hash:
                    owned_streams[pos_stdin_streams[i]] = stdin_streams[pos_stdin_streams[i]]

        # Matching targets
        sources = ['stdtar', 'stdunk']
        assert self.agent.proc_outputs is not None
        pos_stdtar_streams = [None] * len(self.agent.proc_outputs)
        for i in range(len(self.agent.proc_outputs)):
            found_match = -1
            for source in sources:
                for j, user_hash in enumerate(expanded_streams[source]):
                    if user_hash not in self.agent.known_streams_by_user_hash:
                        return False, {}, {}, {}, {}
                    stream_obj = self.agent.known_streams_by_user_hash[user_hash]
                    net_hash = DataProps.build_net_hash(DataProps.peer_id_from_user_hash(user_hash),
                                                        stream_obj.is_pubsub(),
                                                        stream_obj.props.get_group())

                    name = stream_obj.props.get_name()

                    # If the current input stream is compatible with the i-th input slot...
                    if (net_hash, name) in self.agent.compat_out_streams[i]:
                        pos_stdtar_streams[i] = user_hash
                        found_match = j
                        break

                if found_match >= 0:
                    del expanded_streams[source][found_match]  # Removing the stream from the suggestions
                    break

        # We ensured that the not-filled-arguments of the processor have a default value, otherwise no ways
        for i in range(len(self.agent.proc_outputs)):
            if pos_stdtar_streams[i] is not None:
                stdtar_streams[pos_stdtar_streams[i]] = self.agent.known_streams_by_user_hash[pos_stdtar_streams[i]]
                if pos_stdtar_streams[i] in self.agent.owned_streams_by_user_hash:
                    owned_streams[pos_stdtar_streams[i]] = stdtar_streams[pos_stdtar_streams[i]]

    # We add to 'stdext' all the streams that did not fit the processor (both coming from suggestions in 'stdin' or
    # not suggested at all)
    sources = ['stdin', 'stdtar', 'stdunk']
    for source in sources:
        for user_hash in expanded_streams[source]:
            if user_hash not in self.agent.known_streams_by_user_hash:
                return False, {}, {}, {}, {}
            stdext_streams[user_hash] = self.agent.known_streams_by_user_hash[user_hash]
            if user_hash in self.agent.owned_streams_by_user_hash:
                owned_streams[user_hash] = stdext_streams[user_hash]

    return True, stdin_streams, stdtar_streams, stdext_streams, owned_streams

Assigns the expanded streams to the processor of the agent. It takes the first output of expand_and_normalize_streams and consumes it.

  1. Every stdext stream goes to the extras.
  2. When stdin or stdunk is not empty, each input of the processor takes the first stream of stdin (then of stdunk) compatible with that input. An input without a stream takes its default value. An input without a stream and without a default makes the match invalid.
  3. For each output of the processor it takes the first stream of stdtar (then of stdunk) compatible with that output as its learning target.
  4. Every stream left in stdin, stdtar or stdunk goes to the extras.

It returns (valid, stdin, stdtar, stdext, owned). The last four elements are dicts from user hash to stream object (or default value). A stream that the agent does not know makes the whole match invalid and returns empty dictionaries.

check_if_doable

check_if_doable(interaction: Interaction) -> bool
Source code in unaiverse/interaction.py
def check_if_doable(self, interaction: Interaction) -> bool:
    """Return True if the given interaction can be executed right now.

    An interaction is doable when it is not yet completed, the requester is a known agent, and
    either all involved streams have fresh data.

    Args:
        interaction: The interaction to evaluate.
    """
    requester_is_known = interaction.requester in self.agent.all_agents
    return (not interaction.completed and requester_is_known and
            (interaction.get_new_stream_data_tags(all_fresh_or_fail=True) is not None))

Returns True when interaction is not completed, its requester is a known agent and every one of its streams has a fresh sample (see Interaction.get_new_stream_data_tags). The behavior asks it before running the action for that interaction.

check_consistency_between_action_kwargs_and_interaction_fields staticmethod

check_consistency_between_action_kwargs_and_interaction_fields(interaction: Interaction) -> bool
Source code in unaiverse/interaction.py
@staticmethod
def check_consistency_between_action_kwargs_and_interaction_fields(interaction: Interaction) -> bool:
    """Checks that the action kwargs of an interaction contain no reserved name and agree with its fields.

    Args:
        interaction: The interaction to check.

    Returns:
        True if the kwargs are consistent, False otherwise (the error is logged).
    """
    for k, v in interaction.action_kwargs.items():
        if k in Custom.RESERVED_IN_ACTION_KWARGS:
            log.error(f"Tried to register and interaction that includes a "
                      f"private/not-allowed argument: {k} not allowed in action_kwargs")
            return False
        if k in Custom.INTERACTION_FIELD_NAMES and v != getattr(interaction, k):
            log.error(f"Tried to register and interaction that includes a "
                      f"private/not-allowed argument: {k} echoed inconsistently,"
                      f" {v} vs {getattr(interaction, k)}")
            return False
    return True

Static method that validates action_kwargs before registration. It returns False with an error in the log in two cases: (1) a key is reserved to the framework (max_duration, retry_timeout, delay, action_kwargs, interaction) and (2) a key names a field of the interaction (streams, num_steps, target, timeout, copy_sys, forced_uuid, id, volatile, data_samples, callback, num_samples_to_stream) with a value different from that field. It returns True otherwise.

get_current

get_current() -> Interaction | None
Source code in unaiverse/interaction.py
def get_current(self) -> Interaction | None:
    """Return the currently executing interaction, or None if no interaction is running."""
    return self.current

Returns current (the interaction served by the running action) or None. Agents read it through AgentBasics.get_current_interaction.

get_last_registered

get_last_registered() -> Interaction | None
Source code in unaiverse/interaction.py
def get_last_registered(self) -> Interaction | None:
    """Return the most recently registered interaction, or None if none have been registered."""
    return self.last_registered

Returns last_registered.

set_current_as_paused

set_current_as_paused() -> None
Source code in unaiverse/interaction.py
def set_current_as_paused(self) -> None:
    """Set the current interaction as something that was started but now must be paused because some other
    interactions are handled."""
    if self.current is not None:
        self.current.mark_paused()

Marks the current interaction PAUSED if there is one. The behavior calls it when it leaves a multi-step action to serve something else.

set_current

set_current(interaction: Interaction | None) -> None
Source code in unaiverse/interaction.py
def set_current(self, interaction: Interaction | None) -> None:
    """Set the given interaction as the currently executing one.

    This marks the interaction as running and configures the agent's
    stdin/stdout to point to the correct streams for this interaction.

    Args:
        interaction: The Interaction to set as current.
    """
    self.current = interaction
    first_time = interaction is not None and not interaction.running

    # Default stream bindings (this also automatically switches from private to public and vice versa)
    self.agent.set_default_stream_binding()

    if interaction is not None:
        interaction.mark_running()

        if len(interaction.stream_proxy) > 0:

            # Restart buffered streams and activate them if they were off
            if first_time:
                for stream in interaction.stream_proxy:
                    if isinstance(stream, BufferedStream):
                        stream.restart(interaction.uuid)

            # Every interaction with some-streams-specified forces the interaction-described bindings
            self.agent.stdin.bind(interaction.stdin_streams, uuid=interaction.uuid)
            self.agent.stdtar.bind(interaction.stdtar_streams, uuid=interaction.uuid)
            self.agent.stdext.bind(interaction.stdext_streams, uuid=interaction.uuid)
            self.agent.stdout.bind_uuid_only(interaction.uuid)

Makes interaction the current one. The behavior calls it right before running an action. It first restores the default bindings of the standard streams of the agent on the network where the agent behaves. With an interaction it marks it RUNNING. When the interaction has streams, the method restarts the buffered ones at the first call for that interaction. It binds stdin, stdtar and stdext of the agent to the streams of the interaction and stdout to its uuid. None only clears the current interaction and restores the defaults.

has_data

has_data(interaction: Interaction) -> bool
Source code in unaiverse/interaction.py
def has_data(self, interaction: 'Interaction') -> bool:
    """Return True if any owned stream has data available for the given interaction.

    Args:
        interaction: The interaction to check data availability for.
    """
    for stream_obj in self.agent.owned_streams_by_user_hash.values():
        if stream_obj.has_data(interaction.uuid):
            return True
    return False

Returns True when at least one owned stream of the agent holds data under the uuid of interaction.

get_recipients

get_recipients(interaction: Interaction) -> list[str]
Source code in unaiverse/interaction.py
def get_recipients(self, interaction: 'Interaction') -> list[str]:
    """Return the list of peer IDs that should receive data generated by the interaction.

    For sent interactions the recipients are the interaction targets; for received interactions it
    is the original requester; for lazy interactions it is the interaction targets.  Unknown
    (unregistered) interactions fall back to the interaction's target list.

    Args:
        interaction: The interaction whose recipients should be determined.

    Returns:
        A list of peer ID strings, filtering out any ``None`` entries.
    """
    if self.is_known(interaction):
        if self.is_sent(interaction):
            recipients = interaction.target  # This is always a list, even when with 1 element only
        elif self.is_received(interaction):
            recipients = [interaction.requester]  # This is always 1 element, we make it a list
        elif self.is_lazy(interaction):
            recipients = interaction.target  # This is always a list, even when with 1 element only
        else:
            raise GenException("Unexpected case of a known interaction that is both not sent or received")
    else:

        # This is the case of a not-registered interaction.
        recipients = interaction.target  # This is always a list, even when with 1 element only
    return [x for x in recipients if x is not None]

Returns the peer ids that receive the samples generated for interaction: the targets for a sent or lazy interaction, the requester for a received one and the targets for an interaction that the manager does not know. None entries are dropped. The agent calls it when it sends the samples of its streams.

complete async

complete(interaction: Interaction, reason: CompletionReason, dest_state: str | None = None, target: str | None = None) -> None
Source code in unaiverse/interaction.py
async def complete(self, interaction: 'Interaction', reason: 'CompletionReason',
                   dest_state: str | None = None, target: str | None = None) -> None:
    """Mark an interaction as completed and move it to the recently-completed set, removing it from its action
    (async).

    Args:
        interaction: The interaction to complete.
        reason: The reason for completion.
        dest_state: The destination state reached, if any.
        target: The target agent who completed the interaction (Default: None).
    """
    if interaction is not None and not interaction.completed:
        interaction.mark_completed(reason, dest_state=dest_state, target=target)
        interaction.clear_from_action()  # We do not remove it from streams yet - it might be needed for sending
        if interaction.completed:
            if self.sent.get(interaction.uuid) is interaction:
                self.sent_recently_completed.add(interaction)
                del self.sent[interaction.uuid]
            if self.received.get(interaction.uuid) is interaction:
                self.received_recently_completed.add(interaction)
                del self.received[interaction.uuid]
            if self.lazy.get(interaction.uuid) is interaction:
                self.lazy_recently_completed.add(interaction)
                del self.lazy[interaction.uuid]

            # Running callback method, if any
            if interaction.callback is not None:
                callback_method = getattr(self.agent, interaction.callback)
                self.agent.behav_lone_wolf.enable(False)
                self.agent.behav.enable(False)
                if interaction.requester in self.agent.public_agents:
                    self.agent.behav_lone_wolf.enable(True)
                else:
                    if self.agent.in_world():
                        self.agent.behav.enable(True)

                await callback_method(interaction=interaction)  # "Calling callback!"

                self.agent.behav_lone_wolf.enable(False)
                self.agent.behav.enable(False)

Completes an interaction (async). It does nothing on None or on an interaction already completed.

Argument Type Default Meaning
interaction Interaction required The interaction.
reason CompletionReason required Why it completed.
dest_state str or None None The state reached.
target str or None None Complete only the entry of this target.

It calls Interaction.mark_completed and removes the interaction from its action. When the whole interaction is now completed it moves it from its open group to the matching *_recently_completed set. When the interaction has a callback, the manager disables both behaviors of the agent and enables one of them for the duration of the call. The public behavior is enabled when the requester is in public_agents. Otherwise the world behavior is enabled when the agent is in a world. The manager then awaits getattr(agent, callback)(interaction=interaction) and disables both behaviors again. On an interaction sent by this agent the requester is the agent itself and never belongs to public_agents. Two consequences follow: (1) an agent in a world runs the callback with its world behavior enabled even for a request sent on the public network and (2) an agent outside any world runs it with no behavior enabled. The stream data stays until the drain.

complete_current async

complete_current(dest_state: str, reason: CompletionReason) -> None
Source code in unaiverse/interaction.py
async def complete_current(self, dest_state: str, reason: 'CompletionReason') -> None:
    """Mark the current interaction as completed (async).

    Args:
        dest_state: The destination state reached by completing this action.
        reason: The reason for completion.
    """
    if self.current is not None:
        await self.complete(self.current, dest_state=dest_state, reason=reason)
    self.current = None

Completes the current interaction with reason and dest_state (async) and clears current. The behavior calls it with CompletionReason.OK when an action completes and the machine moves to dest_state.

drain_completed

drain_completed() -> list[Interaction]
Source code in unaiverse/interaction.py
def drain_completed(self) -> list[Interaction]:
    """Return and clear the list of recently completed interactions.

    Used by the agent's ``behave()`` loop to send status notifications.

    Returns:
        List of Interaction objects that were recently completed.
    """
    cur_time = clock.get_time()
    cur_clock_cycle = clock.get_cycle()
    drained = []

    for recently_completed in [self.sent_recently_completed,
                               self.received_recently_completed,
                               self.lazy_recently_completed]:
        to_remove = []
        for i, interaction in enumerate(recently_completed):

            # Wait AT LEAST 1 clock cycle, to allow sending samples generated during the interaction
            # Of course, "disconnected"-agent-related interactions are immediately drained
            if (interaction.completion_reason == CompletionReason.DISCONNECTED or
                    (interaction.cycle_completed < cur_clock_cycle and
                     (cur_time - interaction.timestamp_completed) > Custom.DRAIN_TIMEOUT)):
                log.inter(
                    f"Draining {interaction.to_code_str(True)} "
                    f"(cycle_completed={interaction.cycle_completed})")
                to_remove.append(interaction)
                drained.append(interaction)
        for interaction in to_remove:
            self.sent_recently_completed.discard(interaction)
            self.received_recently_completed.discard(interaction)
            self.lazy_recently_completed.discard(interaction)

            # Clearing from all the owned and not-owned streams (all), that might have been used for output purposes
            # by the current agent or by others.
            # In principle, only the processor streams should be involved, since it is the only one in which we plug
            # this interaction in this class.
            # However, the user might have added the interaction to other owned streams.
            if not self.is_known(interaction):

                # If, meanwhile, another interaction with the same UUID (e.g., None) was received,
                # do not clear it from the streams
                self.clear_from_all_streams(interaction)

    return drained

Returns the completed interactions ready for notification and removes them from the three *_recently_completed sets. An interaction is ready when it completed in an earlier clock cycle or with DISCONNECTED. The wait of at least one tick gives the samples produced by the action time to leave. A drained interaction that the manager no longer knows is detached from every stream. AgentBasics.behave calls it at every tick and sends the status of each drained interaction to its requester.

complete_expired async

complete_expired() -> None
Source code in unaiverse/interaction.py
async def complete_expired(self) -> None:
    """Remove expired (or no-action-based) interactions and return them for notification (async).

    Checks all received and sent interactions against the retry_timeout.
    Expired interactions are marked as COMPLETED with TIMEOUT reason
    and removed from the tracking dicts.
    """
    for interaction in list(self.sent.values()) + list(self.received.values()) + list(self.lazy.values()):
        if interaction.status == InteractionStatus.COMPLETED:
            continue
        elif interaction.is_expired(Custom.DEFAULT_INTER_TIMEOUT) or interaction.action_name is None:
            await self.complete(interaction, reason=CompletionReason.TIMEOUT)
        elif interaction.volatile and self.is_sent(interaction):
            await self.complete(interaction, reason=CompletionReason.TIMEOUT)
        else:
            if self.is_received(interaction) and interaction.requester not in self.agent.all_agents:
                await self.complete(interaction, reason=CompletionReason.DISCONNECTED)
            if self.is_sent(interaction):
                for target in interaction.target:
                    if target not in self.agent.all_agents:
                        await self.complete(interaction, reason=CompletionReason.DISCONNECTED, target=target)

Completes the open interactions that have to end (async). AgentBasics.behave calls it at every tick.

Condition Reason
Older than its timeout (300 seconds at most, see Interaction.is_expired) or without an action name TIMEOUT
Sent and volatile TIMEOUT
Received from a requester that the agent no longer knows DISCONNECTED
Sent to a target that the agent no longer knows DISCONNECTED for that target

clear_expired_stream_data

clear_expired_stream_data() -> None
Source code in unaiverse/interaction.py
def clear_expired_stream_data(self) -> None:
    """Purge stale buffered data from streams whose associated interaction is done or gone."""
    all_interactions = list(self.received.values()) + list(self.sent.values()) + list(self.lazy.values())
    for interaction in all_interactions:
        assert interaction is not None
        for stream in interaction.stream_proxy:

            # In case of data samples or default input values, skip
            if not isinstance(stream, Stream):
                continue

            # We only consider streams whose interactions were either removed, or are already completed, or
            # were just created (artificial interaction, for example the ones created just to send a sample)
            _interaction = stream.get_interaction(interaction.uuid)
            if _interaction is None or _interaction.completed or _interaction.created:

                # This will also clear the associated (completed) interaction, if still there
                stream.clear_expired_data(Custom.DEFAULT_INTER_TIMEOUT)

For each open interaction, it asks every stream of the interaction to drop its data older than Custom.DEFAULT_INTER_TIMEOUT. The method asks only the streams whose interaction under that uuid is gone, completed or still in status CREATED. AgentBasics.behave calls it at every tick.

update_sent_status async

update_sent_status(status_dict: dict) -> None
Source code in unaiverse/interaction.py
async def update_sent_status(self, status_dict: dict) -> None:
    """Update a previously sent interaction's status from a received status message (async).

    Args:
        status_dict: Dict from Interaction.to_status_dict().
    """
    sender = status_dict.get('status_generated_by')
    uuid = status_dict.get('uuid')  # UUID can be None (meaning generic UUID, still valid!), recall this
    if uuid in self.sent:

        # Collecting data
        interaction = self.sent[uuid]
        interaction_status = InteractionStatus(status_dict['status'])
        if status_dict.get('completion_reason'):
            completion_reason = CompletionReason(status_dict['completion_reason'])
        else:
            completion_reason = CompletionReason.OK
        interaction_destination_state = status_dict.get('destination_state')

        # Recording data tags
        data_tags: dict[str, list[int]] | None = status_dict.get('data_tags', None)
        if data_tags is not None:
            interaction.record_data_tags(data_tags,
                                         target=sender)

        #  Mark the completion from the sender
        if interaction_status == InteractionStatus.COMPLETED:
            await self.complete(interaction, dest_state=interaction_destination_state, reason=completion_reason,
                                target=sender)

Applies a status message from a target to the sent interaction with the same uuid (async). It does nothing for an unknown uuid. It records the data tags of the message for that target and, when the status is COMPLETED, completes the entry of that target with the reason of the message (OK when missing) and its destination state. The node calls it for every status message.

is_received

is_received(interaction: Interaction) -> bool
Source code in unaiverse/interaction.py
def is_received(self, interaction: Interaction) -> bool:
    """Return True if the interaction was received from another agent (active or recently completed).

    Args:
        interaction: The interaction to check.
    """
    return interaction.uuid in self.received or interaction in self.received_recently_completed

Returns True when interaction is open in received or is in received_recently_completed.

is_sent

is_sent(interaction: Interaction) -> bool
Source code in unaiverse/interaction.py
def is_sent(self, interaction: Interaction) -> bool:
    """Return True if the interaction was sent by this agent (active or recently completed).

    Args:
        interaction: The interaction to check.
    """
    return interaction.uuid in self.sent or interaction in self.sent_recently_completed

Returns True when interaction is open in sent or is in sent_recently_completed.

is_lazy

is_lazy(interaction: Interaction) -> bool
Source code in unaiverse/interaction.py
def is_lazy(self, interaction: Interaction) -> bool:
    """Return True if the interaction was lazily generated within this agent (active or recently completed).

    Args:
        interaction: The interaction to check.
    """
    return interaction.uuid in self.lazy or interaction in self.lazy_recently_completed

Returns True when interaction is open in lazy or is in lazy_recently_completed.

is_known

is_known(interaction: Interaction) -> bool
Source code in unaiverse/interaction.py
def is_known(self, interaction: Interaction) -> bool:
    """Return True if the interaction is tracked in any of sent, received, or lazy dicts.

    Args:
        interaction: The interaction to check.
    """
    return self.is_received(interaction) or self.is_sent(interaction) or self.is_lazy(interaction)

Returns True when one of is_received, is_sent and is_lazy is True.

get_interaction

get_interaction(uuid: str | None, consider_completed_too: bool = False) -> Interaction | None
Source code in unaiverse/interaction.py
def get_interaction(self, uuid: str | None, consider_completed_too: bool = False) -> Interaction | None:
    """Look up an interaction by UUID across the active tracking dicts.

    Args:
        uuid: The UUID string to look up.
        consider_completed_too: When True, also search the recently-completed sets and return the
            most recently completed match (there may be more than one with the same UUID).

    Returns:
        The matching Interaction, or None if not found.
    """
    if uuid in self.received:
        return self.received[uuid]
    elif uuid in self.sent:
        return self.sent[uuid]
    elif uuid in self.lazy:
        return self.lazy[uuid]
    else:
        if consider_completed_too:
            found_so_far: Interaction | None = None
            for inter in self.received_recently_completed:
                if inter.uuid == uuid:
                    if found_so_far is None or found_so_far.timestamp_completed < inter.timestamp_completed:
                        found_so_far = inter
            for inter in self.sent_recently_completed:
                if inter.uuid == uuid:
                    if found_so_far is None or found_so_far.timestamp_completed < inter.timestamp_completed:
                        found_so_far = inter
            for inter in self.lazy_recently_completed:
                if inter.uuid == uuid:
                    if found_so_far is None or found_so_far.timestamp_completed < inter.timestamp_completed:
                        found_so_far = inter
            return found_so_far  # It returns the last completed, there could be more than one with the same UUID
        else:
            return None

Looks up an interaction by uuid in received, then sent, then lazy. With consider_completed_too=True and no open match it searches the three completed sets and returns the match with the latest completion time. Several completed interactions can share a uuid. It returns None when nothing matches.

add_lazy_stream_to_interaction

add_lazy_stream_to_interaction(stream_hash: str, interaction: Interaction) -> None
Source code in unaiverse/interaction.py
def add_lazy_stream_to_interaction(self, stream_hash: str, interaction: Interaction) -> None:
    """Attach a stream (identified by hash) to an already-registered interaction as a lazy stream.

    Args:
        stream_hash: A user-level or net-level stream hash to resolve and attach.
        interaction: The interaction to attach the stream to.
    """
    user_hashes = self.__normalize_to_user_hashes(stream_hash)
    log.debug(f"[add_lazy_stream_to_interaction] stream_hash={stream_hash}, user_hashes={user_hashes}, "
              f"interaction={interaction}")
    for user_hash in user_hashes:
        stream_obj = self.agent.known_streams_by_user_hash[user_hash]
        stream_obj.add_interaction(interaction)
        interaction.add_lazy_stream(user_hash, stream_obj,
                                    is_owned=user_hash in self.agent.owned_streams_by_user_hash)

Attaches a stream to an interaction already registered. stream_hash can be a user hash or a net hash (all the streams of the group). Each stream records the interaction and the interaction receives the stream through Interaction.add_lazy_stream. The agent uses it to attach the buffered copy of a stream of another agent to the interaction that produced it.

remove_interactions_of_agent async

remove_interactions_of_agent(agent: str) -> None
Source code in unaiverse/interaction.py
async def remove_interactions_of_agent(self, agent: str) -> None:
    """Complete and deregister all interactions that involve the given agent as requester or target (async).

    Args:
        agent: Peer ID of the agent being removed.
    """
    interaction_dicts = [self.sent, self.received, self.lazy]
    for interaction_dict in interaction_dicts:
        for uuid, inter in list(interaction_dict.items()):  # Do not remove list(...)
            if inter.requester == agent:
                await self.complete(inter, reason=CompletionReason.DISCONNECTED)
            if agent in inter.target:
                await self.complete(inter, reason=CompletionReason.DISCONNECTED, target=agent)

Completes with DISCONNECTED every open interaction requested by agent and the entry of agent in every open interaction that targets it (async). AgentBasics.remove_agent calls it when a peer leaves.

InteractionStatus

Bases: Enum

The life cycle of an interaction. Each member has a string value that travels in to_dict and in status messages.

Member Value Meaning
CREATED "created" Built and not registered.
REQUESTED "requested" Registered as sent by the requester.
LAZY "lazy" Registered as lazy.
RECEIVED "received" Registered as received by a target.
RUNNING "running" Served by the running action.
PAUSED "paused" Started and suspended while the behavior serves something else.
COMPLETED "completed" Over for any CompletionReason.

CompletionReason

Bases: Enum

Why an interaction completed. It is stored in completion_reason and per target in target_completion_reason.

Member Value When
OK "ok" The action completed and the behavior of the target moved to the destination state. A status message without a reason also counts as OK.
TIMEOUT "retry_timeout" The interaction outlived its timeout, had no action name or was volatile on the side of the requester.
REJECTED "rejected" The target refused it on arrival because it had no room for it in its manager or among the messages that wait for the end of a running action.
DISCONNECTED "disconnected" The other side left before the end.
ERROR "error" An error occurred while running the action.
DISCARDED "discarded" The agent dropped the interaction on purpose.

The value of TIMEOUT is the string "retry_timeout" and not "timeout". Code that compares values must use that string or the member itself.

InteractionType

Bases: Enum

How the manager registered an interaction. Interaction.type holds it.

Member Value Registered by
SENT "sent" register_sent
RECEIVED "received" register_received
LAZY "lazy" register_lazy