Skip to content

Agents

An agent is what acts on the network. It wraps a processor (the part that turns inputs into outputs) together with the description of what the processor reads and writes, a behavior for the public network, a behavior for the world it may join and the state of its conversations. A node hosts one agent (see Nodes).

import torchvision
from unaiverse.agent import Agent
from unaiverse.streams.dataprops import StreamType

weights = torchvision.models.ResNet50_Weights.IMAGENET1K_V1
labels = weights.meta["categories"]

agent = Agent(proc=torchvision.models.resnet50(weights=weights).eval(),
              proc_inputs=[StreamType(data_type="img", stream_to_proc_transforms=weights.transforms())],
              proc_outputs=[StreamType(data_type="text", proc_to_stream_transforms=lambda p: labels[p.argmax(1)[0]])])

Agent lives in unaiverse.agent and extends AgentBasics from unaiverse.agent_basics (API reference). Agent adds the built-in actions to the machinery of AgentBasics.

Parameters

Parameter Type Default Meaning
proc torch.nn.Module, callable, "human" or None required The processor (see Processors).
proc_inputs list of StreamType or str None One entry per input of the processor. A string such as "img" or "text" is a short form of StreamType(data_type=...). With None the agent guesses the inputs from the processor.
proc_outputs list of StreamType or str None One entry per output of the processor. The rules of proc_inputs apply.
proc_opts dict or None None Options for learning. The key optimizer holds a torch.optim.Optimizer and the key losses holds one loss function per output (None for outputs that do not learn).
merge_flat_stream_labels bool False Merge the labels of all the flat label streams of the agent into one label space.
buffer_generated bool False Keep the samples that the agent generates in buffered streams.
buffer_generated_by_others str "none" Buffer the samples generated by other agents: "one" keeps one buffer per peer and "all" keeps everything. Any other value raises GenException.
world_folder str or None None Worlds only. The folder with the role files of the world (see Worlds).
policy_filter str, callable or None None A function (or the name of a method of the agent) that may override the action chosen by the behavior of the world (see Behaviors).
policy_filter_lone_wolf str, callable or None None The same for the behavior of the public network.

The constructor creates the input and output streams of the processor from proc_inputs and proc_outputs (see Data streams), loads the public behavior and leaves the world behavior empty until the agent joins a world.

Processors

The processor decides what kind of agent you have.

proc The agent is
a torch.nn.Module A model. The agent calls it on the samples of its input streams and writes the results on its output streams. With proc_opts it can also learn (see Learning over time).
any other callable A function, wrapped like a module. Its positional arguments are the inputs and its return value the outputs.
"human" A person. The outputs of the processor are what the person types or sends in the webapp or at a terminal (see People).
None An agent without a processor. It can still own streams (a sensor, a dataset) and run actions (a world master, a coordinator).

The SDK wraps every module and callable in a ModuleWrapper (unaiverse.modules.utils). The wrapper applies the transforms of the streams, checks the shapes and types against proc_inputs and proc_outputs and runs the call. With interactive messages it also checks the answer of a language model against the form that the model has to answer. Ready-made processors (small language models, image classifiers, the clients of hosted language models) are in unaiverse.modules (see Models).

The tick

The node runs behave() of its agent at every cycle. A call of behave() does the following in order:

  1. If the agent is in a world, it binds the processor to the world streams, calls the hook on_tick() and makes one step of the world behavior.
  2. It binds the processor to the public streams and makes one step of the public behavior. An agent in a world therefore keeps answering on the public network.
  3. It closes the interactions that expired, sends the status of the completed ones to their requesters and drops the stream data of closed interactions.

A step of a behavior picks at most one action and runs it (see Behaviors). You can override behave() in a subclass. Because it runs inside the tick, the override must call await super().behave() and must not block.

Offloading

A processor call can take seconds (a large model on a CPU, a request to a hosted model). The wrapper runs the module calls one at a time in a worker thread of its own. The event loop meanwhile keeps the network alive. Preparing interactive messages before the call and checking the answer after it are tasks of the agent and stay on the event loop. The steps of a multi-step action are the exception. They run in the event loop so that each step reads the sample of the tick in which it runs. In these steps a module whose previous call lasted at least NODE_OFFLOAD_SLOW seconds (default 0.5) runs in the worker thread as well.

Calls run inline, in the event loop, in these cases:

  1. The environment holds NODE_OFFLOAD=0.
  2. The code runs in a browser without threads.
  3. The module echoes its input (a person or an identity) or declares UAI_OFFLOAD = False.
  4. A subclass of ModuleWrapper overrides forward().

An async module is awaited either way.

Hooks

You customize an agent by overriding these methods in a subclass of Agent.

Method Called Default
async on_tick() Once per tick while the agent is in a world. It runs before the step of the world behavior. Does nothing.
hook_proc_tweak_inputs(inputs) Right before every processor call. It returns the inputs to use. Stores them in proc_last_inputs and returns them.
hook_proc_tweak_outputs(outputs) Right after every processor call. It returns the outputs to stream. Stores them in proc_last_outputs and returns them.
hook_before_sending_sample(data, data_tag, net_hash, stream_name, recipient) Before a sample leaves the agent. recipient is None for a broadcast. It returns the data to send. Returns data.
async on_send_event(peer_id, event) At the tick boundary for each event of the send queue of a peer (see Networking). Does nothing.
async on_transfer_progress(peer_id, direction, seq, done, total, files, reason) During a transfer larger than one chunk, at most every half second and every 1% (see Networking). Does nothing.
learn_behave(state, last_action, prev_state) Reserved for agents that learn their behavior. Does nothing.

The callback of a request (see Interactions) and your own actions (see Actions) are methods of the same subclass.

Reading the agent

Method or attribute Returns
get_name() The name of the node of the agent.
get_profile() The NodeProfile of the agent with its static and dynamic parts.
get_peer_id(), get_peer_ids() The peer id of the agent on the world network while it behaves in a world and on the public network otherwise. The second method returns the pair (public, world).
in_world() True when the agent is a member of a world.
get_current_role() The role of the agent in its world (None outside a world).
get_role(agent), get_agents_by_role(role) The role of a peer and the peers that hold a role (see Worlds).
resolve_agent_ref(ref) The peer id for a node name, an owner/name reference or a peer id. None when the agent does not know that peer.
public_agents, world_agents, world_masters, all_agents Dictionaries from peer id to profile of the peers known on the public network, in the world, among the world masters and in total.
get_stream(...), get_streams(...), find_streams(peer_id, name_or_group) The streams of the agent and of its peers (see Data streams).
get_last_sent_interaction() The last interaction that the agent sent.
get_current_interaction() The interaction served by the running action (None outside an action).

Saving and loading

agent.save(where="") writes the state of the agent and returns True. It writes nothing and returns False when the processor is not a PyTorch module. With an empty where the files go to <identity dir>/agent_state/. A module that changed since the last save goes to <node name>.pt together with the state of the optimizer of proc_opts. The world profile and the role behaviors received from the world go to <node name>.pkl. The agent writes both files to a temporary name first and then moves them in place. A crash therefore never leaves a half-written file.

agent.load(where="") reads the same files back and returns True on success. It returns False when the processor is not a PyTorch module.

A node saves its agent every save_checkpoint_every seconds when that value is positive and loads it at start with node.run(resume_from_checkpoint=True) (see Nodes).