Skip to content

Interactions

An interaction is a request from one agent to one or more other agents to run an action with given arguments on given data. The agent that asks is the requester and the agents that run the action are the targets. A picture sent to a classifier is an interaction and so is the request of a world master who asks a student to take an exam. Every interaction is created by one call to Agent.send.

ok = await agent.send(action_name="process", target="ResNetAgent",
                      data_samples={"proc_output_0": picture}, callback="on_label")

The Interaction class and the InteractionManager live in unaiverse.interaction (API reference).

The round trip

sequenceDiagram
    participant A as Requester (agent A)
    participant B as Target (agent B)
    A->>B: interaction (action, arguments, samples)
    Note over B: registered and queued on the action
    Note over B: the behavior runs the action
    B-->>A: output samples on its processor stream
    B-->>A: status (completed, reason, destination state)
    Note over A: interaction completed, callback runs
  1. send builds the interaction, registers it among the sent interactions of A and sends it to every target.
  2. B checks that it has room for one more interaction (100 at most) and answers at once with the reason REJECTED when it has none. B then queues the interaction on the action of its current behavior. When the current behavior of B has no such action, B only logs an error and the interaction of A ends at its timeout.
  3. The behavior of B picks the action at one of its next ticks (see Behaviors) and runs it. A process action runs the processor on the samples and streams the output back to A.
  4. When the action is over, B sends A the status of the interaction: completed, the reason and the state that B reached. A volatile interaction gets no status.
  5. A marks its copy as completed and calls its callback when the interaction has one.

send

send is an action of Agent. It is async and returns True when at least one target was reached. You call it from your code (see Where to call send) or from a behavior file.

Argument Type Default Meaning
action_name str None The action that the targets run, for example "process", "learn" or one of your own actions.
target str or list of str None The targets: a peer id, a node name of your account, owner/name or a wildcard such as "<partner>" (see Behaviors). A list sends the same interaction to several agents.
action_kwargs dict None The arguments of the action on the target. They must not contain streams.
streams list or dict None The streams that carry the data. A list names the streams and lets the target place them. A dictionary with the keys stdin, stdtar, stdext and stdunk says which stream becomes an input, a target or an extra stream of the processor of the target (stdunk leaves the choice open). A stream may be named by net hash, by user hash, by name or by group. Any other key raises GenException.
data_samples dict, list or None None The data itself in place of streams (see Data samples).
num_steps int -1 How many steps the target runs (one sample per step). -1 becomes one step when the interaction carries data. An interaction without data keeps -1 and has no data-based steps.
timeout float -1.0 The maximum life of the interaction in seconds. -1 uses the default of 300 seconds and a longer timeout is capped at 300 seconds.
from_state, to_state str or None None The states of the target behavior where the interaction may start and where it should end.
callback str or None None The name of a method of the requester to call when the interaction completes (see Callbacks).
forced_uuid str or None "do_not_force" A uuid to impose on the interaction. Only for very special cases.
id str or None "random" The id of the interaction. "random" draws eight hexadecimal characters. The uuid is the id followed by _ and the peer id of the requester.
copy_sys bool False Start from the last sample that the requester wrote outside any interaction. The default public behavior uses it to forward the last output of the processor.
wait_completion bool False Only inside a behavior: keep the state of the behavior on this action until every target has completed the interaction.
volatile bool False Ask the targets not to send any status back. A volatile interaction ends on the side of the requester at the next tick.
num_samples_to_stream int -1 The maximum number of samples that the requester streams. -1 streams until completion or timeout.

send refuses three combinations: (1) wait_completion=True together with volatile=True, (2) wait_completion=True in a call from your code and (3) a callback together with volatile=True. Inside send each of them raises GenException. The @action wrapper catches the exception, logs it as an error and returns False to the caller. The second case exists because waiting for completion needs the state that only a behavior keeps.

agent.get_last_sent_interaction() returns the Interaction that the last send created. Keep it when you need to follow one request among many.

Data samples

data_samples takes the data directly.

  • A dictionary maps one of the streams of the requester to a sample: {"proc_output_0": picture}. The requester stores the sample on that stream under the uuid of the interaction and sends it. This is the form to use. proc_output_0 is the first output stream of an agent whose proc_outputs have no names.
  • A list of samples is accepted and sent. The target registers the interaction. The samples, however, do not reach the input of its processor and a process request in this form does not complete.

A sample is a PIL.Image.Image, a torch.Tensor, a str or a FileContainer (see Data streams).

Callbacks

A callback is an async method of the requester with one required parameter named interaction. Every other parameter needs a default. send checks the method when it builds the interaction.

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("No answer:", interaction.completion_reason.value)
        else:
            print("Done, the target reached", interaction.destination_state)
        return True

The interaction manager calls await self.on_label(interaction=interaction) exactly once when the interaction completes for any reason. The call happens inside the tick and the callback may therefore call actions and send again.

Completion reasons

interaction.completion_reason is a CompletionReason.

Reason Value When
OK "ok" The target ran the action and its behavior moved on.
TIMEOUT "retry_timeout" The interaction lived longer than its timeout (300 seconds by default). A volatile interaction also ends this way when the requester stops waiting.
REJECTED "rejected" The target had no room left for one more interaction.
DISCONNECTED "disconnected" The target (or, on the other side, the requester) left before the end.
ERROR "error" Reserved. No code of the SDK uses it in this version.
DISCARDED "discarded" The agent dropped one of its own system interactions because its action failed or timed out before the first step.

With several targets, target_completion_reason, target_destination_state and target_timestamp_completed hold one entry per target in the order of interaction.target.

Where the answer lands

The target sends its output on its processor stream and tags each sample with the uuid of the interaction. The status and the samples are separate messages. The requester reads the samples from its local copy of the processor stream of the target with find_streams:

def answer_of(agent, interaction):
    for streams in agent.find_streams(interaction.target[0], "processor").values():
        for stream in streams.values():
            sample = stream.get(uuid=interaction.uuid)
            if sample is not None:
                return sample
    return None

The samples of a completed interaction stay on the stream for up to 300 seconds. Because a sample can arrive in the tick after the status, the callback may still find None and a requester that needs the answer then reads the stream again at a later tick.

The built-in action on_received(processing_fcn=None, data_type=None) does this scan for every interaction that the agent sent and returns each answer only once. It scans only the streams of the world network and returns True when at least one answer arrived. With processing_fcn (the name of a method) it calls method(peer_id, props, data, data_tag) without await for each answer. data_type limits the scan to one type of data.

Where to call send

Because send is async and changes the state of the agent, it must run inside the tick of the node. It belongs in one of three places.

  1. An action of your agent that a behavior runs (see Actions).
  2. A callback that chains a second request to the first one.
  3. An override of behave in a lone wolf that asks something on its own initiative:
class Asker(Agent):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.asked = False

    async def behave(self):
        await super().behave()
        if not self.asked and self.resolve_agent_ref("ResNetAgent") is not None:
            self.asked = await self.send(action_name="process", target="ResNetAgent",
                                         data_samples={"proc_output_0": self.picture},
                                         callback="on_label")

run_hook is synchronous and cannot await send.

The Interaction object

Attribute or method Meaning
uuid, id The unique identifier (<id>_<requester>) and the id that send chose.
requester, target The peer id of the requester and the list of the peer ids of the targets.
action_name, action_kwargs The requested action and its arguments. get_arg(name) reads one argument.
status An InteractionStatus: CREATED, REQUESTED, LAZY, RECEIVED, RUNNING, PAUSED or COMPLETED.
completion_reason, destination_state Why it ended and which state the target reached ("generated" after a successful process).
timeout, timestamp_created, timestamp_started, timestamp_completed Its timeout and the times at which it was created, started and completed.
num_steps, get_step_idx() The number of steps and the index of the last one done (-1 before the first).
callback, volatile The name of the callback and the volatile flag.
is_completed(), is_multi_steps(), is_system() Whether it is over, whether it spans several steps and whether the agent created it for itself.

When a behavior runs an action on its own initiative, the agent serves it with a system interaction that it creates for itself. System interactions have a fixed uuid and never travel on the network.

The interaction manager

Each agent has an InteractionManager in agent.im. It keeps three groups: sent, received and lazy (interactions created on the spot to carry a sample that arrived without a request). At every tick it completes the interactions that expired with TIMEOUT and the ones whose peer left with DISCONNECTED. It also sends the status of the interactions completed in the previous tick and drops the stream data of closed interactions. The action all_sent_completed(action_name=None) returns True when no interaction sent with that action name (or with any name) is still open. A behavior uses it to wait for a group of requests sent without wait_completion.