Skip to content

3 · Two agents, fully automatic

In episode 2 a person sent the pictures. Here an agent sends each picture to ResNetAgent, waits for the interaction to complete and prints the label. Every collaboration between agents in UNaIVERSE follows this pattern. One agent creates an interaction with send and the other agent runs the requested action.

Keep resnet_agent.py running from episode 1. Put two pictures (cat.jpg and dog.jpg) next to the new script.

The script

asker.py
from PIL import Image
from unaiverse.agent import Agent
from unaiverse.interaction import CompletionReason
from unaiverse.networking.node.node import Node


class Asker(Agent):
    """Sends pictures to the classifier one at a time and prints the labels."""

    def __init__(self, pictures: list[str], *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.pictures = list(pictures)
        self.pending = None   # The interaction waiting for its completion
        self.answered = None  # A completed interaction whose label is on its way

    async def behave(self) -> None:  # (1)!
        await super().behave()
        peer = self.resolve_agent_ref("ResNetAgent")  # (2)!
        if peer is None:
            return

        if self.answered is not None:  # (3)!
            label = self.label_of(self.answered)
            if label is not None:
                print("Label:", label)
                self.answered = None
            return

        if self.pending is None and self.pictures:
            picture = Image.open(self.pictures.pop(0))
            if await self.send(action_name="process", target=peer,  # (4)!
                               data_samples={"proc_output_0": picture},
                               callback="on_answer"):
                self.pending = self.get_last_sent_interaction()

    async def on_answer(self, interaction=None) -> bool:  # (5)!
        self.pending = None
        if interaction.completion_reason == CompletionReason.OK:
            self.answered = interaction
        else:
            print("No answer:", interaction.completion_reason.value)
        return True

    def label_of(self, interaction) -> str | None:  # (6)!
        for streams in self.find_streams(interaction.target[0], "processor", discard_owned=True).values():
            for stream in streams.values():
                label = stream.get(uuid=interaction.uuid)
                if label is not None:
                    return label
        return None


agent = Asker(["cat.jpg", "dog.jpg"],
              proc=lambda img: img,  # (7)!
              proc_inputs=["img"], proc_outputs=["img"])

node = Node(agent, node_name="Asker", hidden=True, clock_delta=1. / 5.)
node.run(get_in_touch="ResNetAgent", max_time=60.0)  # (8)!
  1. The node awaits behave at every tick. The override first runs the default behavior with super().behave() and then adds the work of this agent.
  2. resolve_agent_ref turns the name of a node into the identity of the connected peer. It returns None until the session with ResNetAgent is established.
  3. A label arrives after the interaction completes (see below). Until it is there, the agent sends nothing else.
  4. send creates an interaction that asks ResNetAgent to run process on this picture and calls on_answer when the interaction completes. It returns True when the target was reached.
  5. The callback receives the completed interaction. completion_reason tells a success from a timeout, a rejection or a lost connection.
  6. The label comes back on the processor stream of ResNetAgent tagged with the uuid of the interaction.
  7. The processor of the asker passes its pictures through unchanged. It gives the agent the image output stream proc_output_0 that carries the pictures.
  8. get_in_touch opens the session with the classifier and max_time stops the node after one minute.

Run it in a second terminal:

python asker.py
Label: tabby
Label: golden retriever

How send works

send is the one way in which an agent asks something of other agents. Its main arguments:

Argument In this script Meaning
action_name "process" The action that the target runs. process runs the processor of the target on the data.
target the peer of ResNetAgent One agent or a list of agents. A node name of your account works as well as a peer identity.
data_samples {"proc_output_0": picture} The data of the request, keyed by the name of one of your own streams. The sample is loaded on that stream and travels with the interaction.
callback "on_answer" The name of an async method of your agent that receives the completed interaction.
timeout default How long the interaction may wait. An interaction that nobody completes ends with a timeout after 300 seconds.
wait_completion default False Inside a behavior, True keeps the transition pending until every target has completed the interaction. A direct call from code like this one does not allow it.

The same call covers a broadcast (a list of targets), a request that reads data from streams instead of data_samples and a message that asks for no status in return (volatile=True). Interactions lists every argument.

The life of an interaction

sequenceDiagram
    participant A as Asker
    participant R as ResNetAgent
    A->>R: send(process, cat.jpg)
    Note over R: default behavior: ready to generated
    R->>R: the processor runs
    R-->>A: status: completed (OK)
    Note over A: on_answer(interaction)
    R-->>A: stream processor.proc_output_0: "tabby"
    Note over A: label_of finds the label

Two separate messages come back to the asker: (1) the status with the outcome of the interaction and (2) the stream sample with the output of the processor. Because the target sends the status as soon as its behavior completes the interaction and the output only on its next tick, the callback usually runs before the label is there. For this reason the script records the completed interaction in on_answer and reads the label in the ticks that follow.

CompletionReason has six values:

Value When
OK The target completed the action.
TIMEOUT Nobody completed the interaction in time.
REJECTED The target had no room to accept the request.
DISCONNECTED The target left before completing it.
ERROR The action failed.
DISCARDED The agent dropped the interaction on purpose.

The same pattern in a world

Nothing in this script depends on a person. Put many askers and many classifiers on the network and they work the same way. In a world the same interactions happen inside behaviors. A transition fires send and another one waits with all_sent_completed or collects the answers with on_received. The world gives each agent the behavior of its role. The next episode shows where to go from here: 4 · Where to go next.

What to try

  • Replace the list of pictures with the frames of a camera and send one picture per second.
  • Send the same picture to two classifiers with target=[peer_a, peer_b] and compare the labels.
  • Stop resnet_agent.py while the asker runs and look at the CompletionReason that the callback prints.