Skip to content

6 · How interactions travel

When the teacher announces a lecture, the students print a message. When it gives the lecture, each student trains its model on six pictures that arrive one every 7 seconds and the teacher waits until every student is done. Both cases are interactions: one agent asks one or more agents to run an action, possibly over several steps and with data streamed alongside the request. A single method sends all of them: Agent.send. The fourth stage of the classroom (tutorial_steps/step4) uses it for every activity.

One send for everything

await self.send(action_name="learn",
                target=self.get_agents_by_role("student"),
                from_state="in_class",
                forced_uuid=f"lecture{self.current_lecture_num}_uuid",
                streams={"stdin": [f"images@lecture{self.current_lecture_num}"],
                         "stdtar": [f"class_names@lecture{self.current_lecture_num}"]},
                num_steps=self.LECTURE_SAMPLES,
                num_samples_to_stream=self.LECTURE_SAMPLES,
                timeout=self.LECTURE_MAX_DURATION,
                callback="mark_lecture_as_finished")

This is teach, the action that starts a lecture. Its arguments cover almost everything send can do:

Argument Meaning
action_name The action that the targets are asked to run ("learn", "process", "print", any action of their role).
target A peer identifier, a node name, an "owner/node" reference or a list of them.
action_kwargs A dict of arguments for the action of the target.
from_state The state of the behavior of the target in which the request should be served. The request waits until the target is in that state.
to_state Optionally, the state that the target should reach by serving the request.
streams The streams that feed the action of the target (see below).
data_samples Data to attach to the request directly instead of streaming them. Use a dict that maps one of your own stream names to its sample.
num_steps How many times the target runs the action within this one interaction.
num_samples_to_stream How many samples the sender streams at most (-1 for no limit).
timeout The lifetime of the interaction in seconds. An interaction lives at most 300 seconds. Without a timeout it gets exactly that maximum.
callback The name of an action of the sender that runs once the interaction has completed on every target.
forced_uuid A fixed identifier for the interaction in place of a random one.
volatile True asks the targets not to report the completion back.
wait_completion Only when send runs as the action of a transition: the transition completes only when every target completed.
copy_sys Copies the latest sample of the owned streams into the new interaction before sending.

send registers the interaction with the interaction manager of the sender, sends it to each target and returns True when at least one target was reached. self.get_last_sent_interaction() returns the Interaction object just sent. The teacher reads its target attribute to know which students really received an exam.

What happens on the target

The request reaches the behavior of each student as a pending request for the action learn. In the state in_class of the student, learn is a requested transition (ready=False) and the policy picks it as soon as the request is there. The built-in learn reads its inputs from the streams of the interaction, runs the processor and the optimizer and reports the step. With num_steps=6 the student runs learn once for every pair of picture and class name that arrives. Only after the sixth step does it take the transition to done_learning.

sequenceDiagram
    autonumber
    participant T as Teacher
    participant S as Student
    T->>S: interaction "learn" (stdin: images@lecture1, stdtar: class_names@lecture1, 6 steps)
    loop 6 samples, one every 7 s
        T-->>S: picture and class name
        S->>S: learn: processor + loss + optimizer step
    end
    S-->>T: status: completed
    T->>T: callback mark_lecture_as_finished(interaction)

Routing the streams

streams tells each target which streams feed the action and how:

  • stdin streams become the inputs of the processor of the target, in order.
  • stdtar streams become the targets of the losses. The teacher sends the class names here during a lecture. The student turns them into class indices with the stream_to_proc_transforms of its output stream.
  • stdext streams travel along but are neither inputs nor targets. During the exam the teacher puts the class names here. They are the correct answers of the exam and the student must predict them from the pictures alone.

The names follow the pattern name@group (images@lecture1) and send resolves them to the full identifiers of the streams of the sender. A plain list instead of a dict leaves the routing to the interaction manager of the target. The manager then places each stream according to what the processor accepts.

Answers travel back on the processor stream of the target. The teacher finds the answer of a student with self.get_stream("processor", student, data_type="text") and reads the sample that belongs to the interaction with stream.get(..., uuid=interaction.uuid).

Completion and callbacks

An interaction completes on each target separately. Each target sends a status update and the interaction manager of the sender records the outcome of that target. When the last target has completed, the whole interaction is complete and the manager calls the callback named in send. The callback is an action of the sender with a parameter named interaction:

@action
async def mark_lecture_as_finished(self, interaction: Interaction | None = None) -> bool:
    """Runs once every student is done or the lecture has timed out."""
    if interaction is None:
        return False
    if not interaction.is_completed():
        return False
    self.current_lecture_finished = True
    return True

With several targets the callback runs once after the last of them finished and interaction.completion_reason holds the reason of that last target. The list interaction.target_completion_reason keeps the reason of each target in the order of interaction.target. The callback also runs when the interaction fails. Its reason is then one of the values of CompletionReason:

Reason When
OK The target served the request and took its transition.
TIMEOUT The interaction waited longer than its timeout.
REJECTED The target had no room to accept the request and refused it at once.
DISCONNECTED The link with the target ended.
ERROR An error occurred while serving it.
DISCARDED The target dropped it on purpose.

A callback that needs the answer reads it from the processor stream of the target as shown above.

Waiting inside the behavior

Three built-in actions let a behavior wait for interactions without writing a callback:

  • send(..., wait_completion=True) used as the action of a transition completes the transition only when every target completed the interaction. Because the transition holds the state of the wait, this form works only as the action of a transition and not in a direct call from Python code.
  • all_sent_completed(action_name=None) succeeds when every interaction sent with that action name (or any, with None) has completed. It is the natural exit condition of a state that dispatched several sends.
  • on_received(processing_fcn=None, data_type=None) succeeds when at least one target sent back a sample for an interaction of this agent. When processing_fcn names a method of the role, the action calls that method as fn(agent, props, data, data_tag) for every sample.
behav.add_transit("waiting", "waiting", action="on_received",
                  args={"processing_fcn": "collect_answer", "data_type": "text"})
behav.add_transit("waiting", "done", action="all_sent_completed", args={"action_name": "process"})

Notices that need no answer

give_next_lecture sends print with volatile=True. A volatile interaction asks the targets not to report its completion. The teacher has no use for knowing whether every student printed the announcement and no status message travels back. A volatile interaction cannot be combined with wait_completion.

Under the hood: the send queue

Interactions and stream samples travel over the sessions of the node. Each peer has a send queue of 64 messages. A long message is cut into chunks of 5 MB and can be up to 1 GB long (50 MB when the receiver runs an older version of the SDK). When the queue of a peer is full, a new message is refused instead of piling up without limit. A receiver can also ask the sender to stop sending a message that it no longer wants. Networking describes the queue in detail.

Run it

Run tutorial_steps/step4 with two AI students. The teacher announces each lecture, streams its six pictures and waits for both students. After three lectures it runs the exam, scores the students and prints a row of ✓ and ✗ for each of them. The scores improve over the rounds as the students learn.

Where next

Chapter 7 looks at how agents find each other before they interact and how the same interactions reach a person.

7 · Agents talking to each other