Skip to content

unaiverse.agent_basics

AgentBasics holds everything an agent needs except its actions. Two classes extend it: (1) Agent adds the built-in actions and (2) World hosts a world. A developer never instantiates AgentBasics directly. A developer subclasses Agent (or World), overrides the hooks of this class and reads its attributes and helpers inside actions and callbacks. The node that hosts the agent calls most of the other methods at every tick. The narrative guide is Agents.

An instance groups six parts.

  1. The processor: proc, its input and output descriptions proc_inputs and proc_outputs and the learning options proc_opts. The constructor wraps the processor in a ModuleWrapper and creates one owned stream per input (group processor_in) and per output (group processor) once the node binds the agent.
  2. Streams: the streams that the agent owns and the streams of other agents that are compatible with its processor, indexed by net hash and by user hash (see Data streams). A net hash names a group of streams of a peer: <peer_id>::dm:<group> for direct messages and <peer_id>::ps:<group> for broadcast. A user hash names one stream: <peer_id>:<name>.
  3. Peers: the profiles of the agents that this agent knows, split by network (public or world) and by kind (human or artificial).
  4. Behaviors: behav_lone_wolf is the behavior on the public network loaded from unaiverse/utils/public.json and behav is the behavior in the world (empty until the agent joins one). Both are HybridStateMachine objects (see Behaviors).
  5. Interactions: the InteractionManager in im and four standard stream proxies, stdin, stdtar, stdext and stdout, that actions read and write.
  6. Interactive messages: the uai_* methods that render a form for the processor and decide what becomes of its answer (see Interactive messages).

An agent lives on two networks at once. On the public network it has its public peer id and behaves as a lone wolf. In a world it has a second, private peer id and a role. At each tick the node calls behave. This method runs one step of the world behavior (when the agent is in a world) and one step of the public behavior, completes the expired interactions and sends the status of the completed ones. While a behavior acts, behaving_in_world tells which network the code runs for. get_peer_id returns the matching peer id.

from unaiverse.agent import Agent

class Echo(Agent):
    def hook_proc_tweak_outputs(self, outputs):
        outputs = super().hook_proc_tweak_outputs(outputs)
        print("Peer id on this network:", self.get_peer_id())
        print("Known peers:", list(self.all_agents))
        return outputs

agent = Echo(proc=lambda text: text.upper(), proc_inputs=["text"], proc_outputs=["text"])

AgentBasics

AgentBasics(proc: ModuleWrapper | Module | Callable | str | None, proc_inputs: list[StreamType | str] | None = None, proc_outputs: list[StreamType | str] | None = None, proc_opts: dict | None = None, merge_flat_stream_labels: bool = False, buffer_generated: bool = False, buffer_generated_by_others: str = 'none', world_folder: str | None = None, policy_filter: Callable | None = None, policy_filter_lone_wolf: Callable | None = None)
Source code in unaiverse/agent_basics.py
def __init__(self,
             proc: ModuleWrapper | torch.nn.Module | Callable | str | None,
             proc_inputs: list[StreamType | str] | None = None,
             proc_outputs: list[StreamType | str] | None = None,
             proc_opts: dict | None = None,
             merge_flat_stream_labels: bool = False,
             buffer_generated: bool = False,
             buffer_generated_by_others: str = "none",
             world_folder: str | None = None,
             policy_filter: Callable | None = None,
             policy_filter_lone_wolf: Callable | None = None) -> None:
    """Create a new agent.

    Args:
        proc: The processing module (e.g., a neural network) for the agent. Can be None (or string 'human').
        proc_inputs: list of DataProps defining the expected inputs for processor (if None it will be guessed).
        proc_outputs: list of DataProps defining the expected outputs from processor (if None it will be guessed).
        proc_opts: A dictionary of options for the processor.
        merge_flat_stream_labels: If True, merges flat stream labels across all owned streams.
        buffer_generated: If True, generated streams will be buffered.
        buffer_generated_by_others: If set to "one" or "all", streams generated by other agents will be buffered
            ("one" per peer or "all"). If set to "none", no buffering will happen (default).
        world_folder: World only. Folder where the world data is (role files, represented by *.json behavior files).
        policy_filter: The name of a method of the Agent class or a function that implements a
            policy filtering function, overriding what the action-selection-policy decided (when in a world).
        policy_filter_lone_wolf: Same as policy_filter, but for the public network.
    """

    # Agent-related features
    self.behav: HybridStateMachine  # HSM that describes the agent behavior in the private/world net
    self.behav_lone_wolf: HybridStateMachine  # HSM that describes the agent behavior in public net
    self.behav_wildcards = {}
    self.proc = proc
    self.proc_updated_since_last_save = False
    self.proc_inputs = proc_inputs
    self.proc_outputs = proc_outputs
    self.proc_opts = proc_opts
    self.proc_last_inputs = None
    self.proc_last_outputs = None
    self.proc_human_peer_id_to_interaction = {}

    # Last interactive form received from each peer, with the time it arrived, so that what this agent
    # writes next can be encoded as an answer to it. It is conversation memory, not node state: it is
    # never saved nor restored.
    self.uai_inbox = {}
    self.uai_writing_to = None  # Who a person at a keyboard is writing to, when there is one
    self.proc_optional_inputs: list[dict] | None = None  # Must be None to be filled later: do not put an empty list
    self.proc_net_hash: dict[str, None | str] = {'public': None, 'private': None}
    self.proc_in_net_hash: dict[str, None | str] = {'public': None, 'private': None}
    self.merge_flat_stream_labels = merge_flat_stream_labels
    self.buffer_generated = buffer_generated
    self.buffer_generated_by_others = buffer_generated_by_others
    self.world_folder = world_folder
    self.policy_filter = policy_filter
    self.policy_filter_opts = {}
    self.policy_filter_lone_wolf = policy_filter_lone_wolf
    self.policy_filter_lone_wolf_opts = {}
    self.clock = clock  # Backward compatibility

    if self.buffer_generated_by_others not in {"one", "all", "none"}:
        raise GenException("Param buffer_generated_by_others can be set to 'one', 'all', or 'none' only.")

    # Streams
    self.known_streams = {}  # All streams that are known to this agent, organized by net hash
    self.owned_streams = {}  # The streams that are generated/offered by this agent, organized by net hash
    self.env_streams = {}  # The owned streams that come from environmental sources (e.g., a camera), by net hash
    self.proc_streams = {}  # The owned streams that are generated by the agent's processor, organized by net hash
    self.proc_in_streams = {}  # The owned streams that are input to the agent's processor, organized by net hash
    self.known_streams_by_user_hash = {}  # From peer_id:name to stream object
    self.owned_streams_by_user_hash = {}  # From stream name to stream object
    self.env_streams_by_user_hash = {}  # From peer_id:name to stream object
    self.proc_streams_by_user_hash = {}  # From peer_id:name to stream object
    self.proc_in_streams_by_user_hash = {}  # From peer_id:name to stream object
    self.compat_in_streams: list[set] = []  # Streams compatible with the processor input (dynamically set)
    self.compat_out_streams: list[set] = []  # Streams compatible with the processor output (dynamically set)

    # Agents, world masters, expected world masters
    self.all_agents: dict[str, NodeProfile] = {}  # ID -> profile (all types of agent)
    self.public_agents: dict[str, NodeProfile] = {}  # ID -> profile of agents talking in public manner
    self.world_agents: dict[str, NodeProfile] = {}  # ID -> profile of all agents living in this world
    self.world_masters: dict[str, NodeProfile] = {}  # ID -> profile of all master-agents living in this world
    self.human_agents: dict[str, NodeProfile] = {}  # ID -> profile (human agents)
    self.artificial_agents: dict[str, NodeProfile] = {}  # ID -> profile (artificial agent)
    self.world_profile = None
    self.world_role_fsms = None  # Dict role -> FSM (JSON string), delivered by the world's grant bundle
    self.is_world = False  # If this instance is about a world: it will be discovered at creation time
    self.last_sent_interaction = None

    # World specific attributes (they are only used if this agent is actually a world)
    self.packed_agent_files: str = ""
    self.role_to_behav = {}
    self.agent_badges: dict[str, list[dict]] = {}  # Peer_id -> collected badges for other agents
    self.role_changed_by_world: bool = False
    self.received_address_update: bool = False

    # Internal properties about the way streams are used
    self.last_buffered_peer_id_to_info = {}  # If buffering was turned on
    self.last_buffered_id_counter = 0
    self.last_ref_uuid = None
    self.overridden_action_step = None
    self.locked_set_proc_input = False

    # Stats
    self.stats: Stats | None = None

    # Information inherited from the node that hosts this agent
    self.node_name = "unk"
    self.node_conn = None
    self.node_profile = None
    self.node_ask_to_get_in_touch_fcn: Callable | None = None
    self.node_purge_fcn: Callable | None = None
    self.node_identity_dir = ''

    # Utilities (keep the "__" prefix, or they will be cleared on world leaving!)
    self.__proc_in_streams_by_user_hash_pub = {}
    self.__proc_streams_by_user_hash_pub = {}
    self.__env_streams_by_user_hash_pub = {}
    self.__proc_in_streams_by_user_hash_prv = {}
    self.__proc_streams_by_user_hash_prv = {}
    self.__env_streams_by_user_hash_prv = {}

    # Checking and filling (guessing) missing processor-related info (proc_inputs and proc_outputs)
    # and allocating a dummy processor if it was not specified (if None)
    AgentProcessorChecker(self)

    # The stream_hash of compatible streams for each data_props are stored in a set
    self.compat_in_streams = [set() for _ in range(len(self.proc_inputs))] \
        if self.proc_inputs is not None else []
    self.compat_out_streams = [set() for _ in range(len(self.proc_outputs))] \
        if self.proc_outputs is not None else []

    # Interaction Manager, stdin/stdout
    assert isinstance(self.proc_optional_inputs, list)
    self.im = InteractionManager(self, max_interactions=Custom.MAX_INTERACTIONS)

    # What the send queues report about each peer we send to (see on_send_event): peer ID -> {"state": "ok" |
    # "failing" | "dropped", "refused", "dropped", "last_written_seq", "last_error", "last_change"}
    self.send_status: dict[str, dict] = {}

    # The messages larger than a chunk on their way, both directions (see on_transfer_progress): (peer ID, "send" |
    # "receive", seq) -> {"done", "total", "kind", "files", "attempt", "time"}; a message leaves at 100% or dropped
    self.transfers: dict[tuple[str, str, int], dict] = {}
    self.stdin = StreamProxy(replace_none_samples_with=[item["default_value"] if item["has_default"] else None
                                                        for item in self.proc_optional_inputs])
    self.stdtar = StreamProxy()
    self.stdext = StreamProxy()
    self.stdout = StreamProxy()

    # Loading default public HSM
    if hasattr(self, "process"):  # Trick to distinguish if this is an Agent or a World (both sons of this class)
        self.is_world = False

        # Public HSM: safe way to load a file packed in a pip package
        self.behav_lone_wolf = HybridStateMachine(self, policy=self.policy_default)
        utils_path = importlib.resources.files("unaiverse.utils")
        json_file = utils_path.joinpath("public.json")
        file = json_file.open()
        self.behav_lone_wolf.load(file)
        file.close()
        self.set_policy_filter(self.policy_filter_lone_wolf, public=True)

        # PrivatE HSM: Setting an empty HSM as default is not provided (private/world)
        self.behav = HybridStateMachine(self, policy=self.policy_default)
        self.behav.add_state("empty")

    else:
        self.is_world = True
        if self.world_folder is None:
            raise GenException("No world folder was indicated (world_folder argument)")

The base class. Its constructor stores the processor and the options and validates them through AgentProcessorChecker. The checker wraps proc in a ModuleWrapper and guesses proc_inputs and proc_outputs when they are None (see Agents). It then creates the interaction manager and the standard stream proxies. For an Agent (a class with a process method) it loads the public behavior from public.json and creates an empty world behavior with the single state empty. For a World it requires world_folder.

Argument Type Default Meaning
proc ModuleWrapper, torch.nn.Module, callable, "human" or None required The processor. "human" makes the agent the agent of a person and None gives an agent without a processor (a world, a sensor).
proc_inputs list[StreamType or str] or None None One description per input of the processor. A string such as "text" or "img" is short for StreamType(data_type=...). None lets the checker guess.
proc_outputs list[StreamType or str] or None None One description per output. The rules of proc_inputs apply.
proc_opts dict or None None Learning options. optimizer holds a torch.optim.Optimizer and losses holds one loss function per output (None for an output that does not learn).
merge_flat_stream_labels bool False Share one label space among all the owned flat tensor streams with labels (see merge_flat_data_stream_props).
buffer_generated bool False Make the processor output streams BufferedStream objects that keep every sample.
buffer_generated_by_others str "none" Keep a buffered copy of the samples that other processors send to this agent. "one" keeps one buffer per peer and replaces it when a new interaction starts. "all" keeps one buffer per interaction. "none" keeps nothing. Any other value raises GenException. Agent.evaluate needs a value other than "none".
world_folder str or None None Worlds only: the folder with the role files (<role>.json and <role>.py). A World without it raises GenException.
policy_filter callable or None None A function that can override the action chosen by the world behavior (see set_policy_filter).
policy_filter_lone_wolf callable or None None The same for the public behavior. The constructor installs it at once.

The constructor does not contact the network. The node binds the agent later with set_node_info and that call creates the processor streams.

Class constants

ROLE_PUBLIC class-attribute instance-attribute

ROLE_PUBLIC = 0 << 0

The role bits of an agent on the public network: 0. A role is an int whose two lowest bits say where the agent lives. Bit 0 means "in a world" and bit 1 means "master of the world". The bits from 2 upwards encode the custom roles of a world (see build_augmented_roles_dictionaries).

ROLE_WORLD_MASTER class-attribute instance-attribute

ROLE_WORLD_MASTER = 1 << 0 | 1 << 1

The role bits of a master of a world: 3 (0b11).

ROLE_WORLD_AGENT class-attribute instance-attribute

ROLE_WORLD_AGENT = 1 << 0 | 0 << 1

The role bits of an ordinary member of a world: 1 (0b01).

CUSTOM_ROLES class-attribute instance-attribute

CUSTOM_ROLES = []

The list of the custom role names (empty by default). A world fills it in alphabetical order with the names of the JSON files in its folder. A role file may declare it too. The world then checks that the two lists contain the same names.

ROLE_BITS_TO_STR class-attribute instance-attribute

ROLE_BITS_TO_STR = {ROLE_PUBLIC: 'public_agent', ROLE_WORLD_MASTER: 'world_master', ROLE_WORLD_AGENT: 'world_agent'}

A dict from role bits to role name. It starts with 0: "public_agent", 3: "world_master" and 1: "world_agent". augment_roles refills it in place with the custom roles and their combinations (for example "world_master~teacher"). The dictionary is a class attribute shared by every instance in the process.

ROLE_STR_TO_BITS class-attribute instance-attribute

ROLE_STR_TO_BITS = {'public_agent': ROLE_PUBLIC, 'world_master': ROLE_WORLD_MASTER, 'world_agent': ROLE_WORLD_AGENT}

The inverse of ROLE_BITS_TO_STR, a dict from role name to role bits. It is shared by every instance in the process and augment_roles refills it in place.

UAI_MAX_RETRIES class-attribute instance-attribute

UAI_MAX_RETRIES = 2

How many times, within one turn, the agent asks its model again for an answer that does not satisfy the form it was given (2). A world tunes it in its role file for its own models (see uai_answer_fell_short).

UAI_DEADLINE_MARGIN class-attribute instance-attribute

UAI_DEADLINE_MARGIN = 15.0

Seconds kept unspent before the interaction that asked a question expires (15.0). uai_time_left subtracts it from the budget. The margin exists because the requester created its copy of the interaction earlier than this agent and that copy expires first.

BADGE_TYPES class-attribute instance-attribute

BADGE_TYPES = {'completed', 'attended', 'intermediate', 'pro'}

The accepted badge types, the set {"completed", "attended", "intermediate", "pro"}. Agent.suggest_badges_to_world rejects any other type.

HUMAN class-attribute instance-attribute

HUMAN = 'human'

The node type of the agent of a person: the string "human". set_node_info writes it in the static profile of the node when the processor is a HumanModule. is_human reads it.

Attributes

proc instance-attribute

proc = proc

The processor. After the constructor it is a ModuleWrapper around the module or callable given as proc (see unaiverse.modules.utils). Worlds have None.

proc_inputs instance-attribute

proc_inputs = proc_inputs

The list of StreamType objects that describe the inputs of the processor, filled by the checker when the constructor received None. create_proc_input_streams assigns them the group processor_in.

proc_outputs instance-attribute

proc_outputs = proc_outputs

The list of StreamType objects that describe the outputs of the processor. create_proc_output_streams assigns them the group processor.

proc_opts instance-attribute

proc_opts = proc_opts

The learning options (dict). Agent.learn requires optimizer and a non-empty losses.

proc_last_inputs instance-attribute

proc_last_inputs = None

The inputs of the last processor call as stored by the default hook_proc_tweak_inputs. proc_last_outputs holds the outputs stored by hook_proc_tweak_outputs. Both are None before the first call.

behav instance-attribute

The HybridStateMachine of the world. It has the single state empty until accept_new_role loads the behavior of the role.

behav_lone_wolf instance-attribute

behav_lone_wolf: HybridStateMachine

The HybridStateMachine of the public network. The constructor loads it from unaiverse/utils/public.json. That behavior has four states and lets a lone wolf answer requests and speak on its own.

State Transitions
ready (initial, blocking) process requested by a peer goes to generated. process run on the initiative of the agent ("ready": true) goes to self_generated.
generated nop goes back to ready.
self_generated send of a process request to <partner> (streams <agent>:processor, copy_sys=True, callback="show") goes to asked. When the send fails, nop goes back to ready.
asked nop goes back to ready.

A request is therefore answered with the output of the processor. The output that the processor produces on its own (a person who types, a sensor) is forwarded to the partner as a new process request. copy_sys copies that last output onto the new interaction. <partner> is the public peer chosen by set_lone_wolf_partner.

behav_wildcards instance-attribute

behav_wildcards = {}

A dict of extra wildcards that add_behav_wildcard fills. When the agent joins a world the node adds them to the new world behavior.

im instance-attribute

im = InteractionManager(self, max_interactions=Custom.MAX_INTERACTIONS)

The InteractionManager of the agent. It has room for Custom.MAX_INTERACTIONS (100) open interactions.

stdin instance-attribute

stdin = StreamProxy(replace_none_samples_with=[item['default_value'] if item['has_default'] else None for item in self.proc_optional_inputs])

The StreamProxy that the processor reads its inputs from. By default it is bound, under the uuid of system interactions, to the processor input streams of the network where the agent behaves. When the behavior serves an interaction with streams, InteractionManager.set_current binds it to the input streams of that interaction. A missing optional input reads as its default value. Three sibling proxies follow the same rules.

Proxy Bound by default to Used by
stdtar nothing Agent.learn reads the learning targets from it.
stdext the environmental (owned, non-processor) streams Actions that need extra streams.
stdout the processor output streams Agent.process writes the outputs on it.

known_streams instance-attribute

known_streams = {}

Every stream that the agent knows (owned or not) in a dict from net hash to a dict from stream name to Stream. Four more dictionaries with the same shape hold subsets of it.

Attribute Content
owned_streams The streams of this agent.
env_streams The owned streams that are neither processor inputs nor outputs (a camera, a dataset).
proc_streams The processor output streams (group processor).
proc_in_streams The processor input streams (group processor_in).

Each of the five has a twin keyed by user hash (known_streams_by_user_hash, owned_streams_by_user_hash, env_streams_by_user_hash, proc_streams_by_user_hash, proc_in_streams_by_user_hash) that maps <peer_id>:<name> to the Stream.

compat_in_streams instance-attribute

compat_in_streams: list[set] = [set() for _ in range(len(self.proc_inputs))] if self.proc_inputs is not None else []

One set per processor input. Each set holds the pairs (net_hash, stream_name) of the known streams compatible with that input. The own input streams of the agent are included. compat_out_streams does the same for the outputs, whose compatible streams can serve as learning targets. InteractionManager.match_streams assigns the streams of an interaction from these sets.

all_agents instance-attribute

all_agents: dict[str, NodeProfile] = {}

Every peer that the agent knows in a dict from peer id to NodeProfile. A peer enters through add_agent once its handshake is complete. Five dictionaries split it.

Attribute Peers
public_agents On the public network (role bit 0 clear). Insertion order follows the order of arrival.
world_agents Ordinary members of the same world.
world_masters Masters of the same world.
human_agents Agents of a person, on any network.
artificial_agents Every other agent.

world_profile instance-attribute

world_profile = None

The NodeProfile of the world that the agent joined. It is None outside a world. It is saved by save.

world_role_fsms instance-attribute

world_role_fsms = None

The behaviors of the roles of the world as a dict from role name to the JSON of the behavior. The world sends them when it admits the agent and accept_new_role reads them.

is_world instance-attribute

is_world = False

True for a World and False for an Agent. The constructor decides it from the presence of a process method.

last_sent_interaction instance-attribute

last_sent_interaction = None

The interaction created by the last successful send. Read it with get_last_sent_interaction.

last_buffered_peer_id_to_info instance-attribute

last_buffered_peer_id_to_info = {}

When buffer_generated_by_others is not "none", this dict maps each peer id to {"uuid_to_id": ..., "net_hash": ...}. net_hash is the net hash of the group buffered<n> that holds the last buffered copy of the processor output of that peer. Agent.evaluate compares that copy with a reference.

send_status instance-attribute

send_status: dict[str, dict] = {}

A dict from peer id to the state that the send queues report for that peer. Each state is a dict with these keys.

Key Meaning
state "ok", "failing" (a write failed and waits for a retry) or "dropped" (the queue was dropped).
refused How many messages a full queue refused.
dropped How many messages were lost with a dropped queue.
last_written_seq The sequence number of the last message written.
last_error The last error reported (None before the first).
last_change The time of the last event.

The node updates it at the tick boundary before calling on_send_event. It is never updated in the browser.

transfers instance-attribute

transfers: dict[tuple[str, str, int], dict] = {}

A dict keyed by (peer_id, "send" or "receive", seq) with an entry for each message larger than one chunk that is still in transit. Each value holds done and total (bytes), kind, files, attempt and time. An entry is removed when the transfer reaches 100% or the message is dropped. The node updates it before calling on_transfer_progress.

uai_inbox instance-attribute

uai_inbox = {}

The last form received from each peer in a dict from peer id to (spec, time_received, rendered_text). This dictionary is the memory of the conversation. It is never saved or restored and holds at most 32 peers (the oldest peer leaves first). See uai_remember_form.

uai_writing_to instance-attribute

uai_writing_to = None

prepare_stdin_if_human records here the peer that the person behind this agent is writing to. It stays None for an agent that is not a person.

stats instance-attribute

stats: Stats | None = None

The statistics recorder. AgentBasics leaves it None and Agent creates a Stats object.

node_conn instance-attribute

node_conn = None

The connection pool of the hosting node (NodeConn) that set_node_info assigns. The other references from the node are node_profile (NodeProfile), node_name (str), node_identity_dir (the folder of the identity files) and the two callables node_ask_to_get_in_touch_fcn and node_purge_fcn that open and close a connection.

Building and binding

set_node_info

set_node_info(conn: NodeConn, profile: NodeProfile, ask_to_get_in_touch_fcn: Callable, purge_fcn: Callable, node_identity_dir: str) -> bool
Source code in unaiverse/agent_basics.py
def set_node_info(self, conn: NodeConn, profile: NodeProfile,
                  ask_to_get_in_touch_fcn: Callable, purge_fcn: Callable,
                  node_identity_dir: str) -> bool:
    """Set the required information from the node that hosts this agent.

    Args:
        conn: The connection pool manager from the node.
        profile: The profile of the hosting node.
        ask_to_get_in_touch_fcn: The function to call to request getting in touch with another peer.
        purge_fcn: The function to call to purge (kill/disconnect) a connection.
        node_identity_dir: The folder where the node identity files are stored.

    Returns:
        True upon successful setup.
    """

    # Getting basic references
    self.node_conn = conn
    self.node_profile = profile
    self.node_name = profile.get_static_profile()['node_name']
    self.node_ask_to_get_in_touch_fcn = ask_to_get_in_touch_fcn
    self.node_purge_fcn = purge_fcn
    self.node_identity_dir = node_identity_dir

    # Checking if human, marking the node
    assert self.proc is None or isinstance(self.proc, ModuleWrapper)  # It is None in worlds!
    if self.proc is not None and isinstance(self.proc.module, HumanModule):
        self.node_profile.get_static_profile()["node_type"] = self.HUMAN

    # Adding peer_id information into the already existing stream data (if any)
    # (initially marked with generic wildcards like <public_peer_id>, ...)
    net_hashes = list(self.known_streams.keys())
    for net_hash in net_hashes:
        if net_hash.startswith("<public_peer_id>") or net_hash.startswith("<private_peer_id>"):
            stream_dict = self.known_streams[net_hash]
            for stream_obj in stream_dict.values():
                self.add_stream(stream_obj, owned=True)  # This will also re-add streams using the node clock

    # Removing place-holder streams
    for peer_id in ["<public_peer_id>", "<private_peer_id>"]:
        to_remove = []
        for net_hash in self.known_streams.keys():
            if DataProps.peer_id_from_net_hash(net_hash) == peer_id:
                for _name, _stream in self.known_streams[net_hash].items():
                    to_remove.append((net_hash, _name))

        # Removing
        for (net_hash, name) in to_remove:
            user_hash = DataProps.user_hash_from_net_hash(net_hash, name)
            del self.known_streams[net_hash][name]
            if len(self.known_streams[net_hash]) == 0:
                del self.known_streams[net_hash]
            if user_hash in self.known_streams_by_user_hash:
                del self.known_streams_by_user_hash[user_hash]

            # Removing all the owned streams (environment and processor streams are of course "owned")
            if net_hash in self.owned_streams:
                if name in self.owned_streams[net_hash]:
                    del self.owned_streams[net_hash][name]
                    if len(self.owned_streams[net_hash]) == 0:
                        del self.owned_streams[net_hash]
            if user_hash in self.owned_streams_by_user_hash:
                del self.owned_streams_by_user_hash[user_hash]
            if net_hash in self.env_streams:
                if name in self.env_streams[net_hash]:
                    del self.env_streams[net_hash][name]
                    if len(self.env_streams[net_hash]) == 0:
                        del self.env_streams[net_hash]
            if user_hash in self.env_streams_by_user_hash:
                del self.env_streams_by_user_hash[user_hash]
            if net_hash in self.proc_streams:
                if name in self.proc_streams[net_hash]:
                    del self.proc_streams[net_hash][name]
                    if len(self.proc_streams[net_hash]) == 0:
                        del self.proc_streams[net_hash]
            if user_hash in self.proc_streams_by_user_hash:
                del self.proc_streams_by_user_hash[user_hash]
            if net_hash in self.proc_in_streams:
                if name in self.proc_in_streams[net_hash]:
                    del self.proc_in_streams[net_hash][name]
                    if len(self.proc_in_streams[net_hash]) == 0:
                        del self.proc_in_streams[net_hash]
            if user_hash in self.proc_in_streams_by_user_hash:
                del self.proc_in_streams_by_user_hash[user_hash]
            self.__proc_streams_by_user_hash_pub.pop(user_hash, None)
            self.__proc_streams_by_user_hash_prv.pop(user_hash, None)
            self.__proc_in_streams_by_user_hash_pub.pop(user_hash, None)
            self.__proc_in_streams_by_user_hash_prv.pop(user_hash, None)
            self.__env_streams_by_user_hash_pub.pop(user_hash, None)
            self.__env_streams_by_user_hash_prv.pop(user_hash, None)
            log.misc(f"Successfully removed known stream with network hash {net_hash}, stream name: {name}")

    # World only: loading action files and refactoring (or building) JSON files of the different roles.
    # This where the world guesses roles.
    if self.is_world:
        assert self.world_folder is not None

        # Check role-JSON files in the world folder
        role_json_tracker = FileTracker(self.world_folder, ext=".json")

        # This usually does nothing, but if you like to dynamically create JSON files, overload this method
        self.create_behav_files()

        # Loading and refactoring roles and behaviors
        self.load_and_refactor_action_file_and_behav_files(force_save=role_json_tracker.something_changed())

        # Building combination of default roles (considering public, world_agent, world_master default roles), and
        # agent/world specific roles
        self.augment_roles()

    # Creating streams associated to the processor input (right now we assume there is no need to buffer them)
    self.create_proc_input_streams(buffered=False)

    # Creating streams associated to the processor output
    self.create_proc_output_streams(buffered=self.buffer_generated)

    # Updating node profile by indicating the processor-related streams
    self.update_streams_in_profile()

    # Blocking stdin for humans
    if has_human_processor(self):
        self.set_default_stdin_binding(public=True)
        self.stdin.disable()
        self.set_default_stdin_binding(public=False)
        self.stdin.disable()

    return True

Binds the agent to the node that hosts it. The node calls it once at start.

Argument Type Meaning
conn NodeConn The connection pool of the node.
profile NodeProfile The profile of the node.
ask_to_get_in_touch_fcn callable Opens a connection to a peer.
purge_fcn callable Closes a connection to a peer.
node_identity_dir str The folder of the identity files, the default root of save and load.

It stores the references and marks the node type "human" when the processor is a HumanModule. Streams added before binding carry the placeholders <public_peer_id> and <private_peer_id>. The method adds them again under the real peer ids and removes the placeholders. A world then loads its role files (see load_and_refactor_action_file_and_behav_files) and builds its roles. Every agent creates its processor input and output streams and writes them in its profile. The agent of a person also disables its standard input on both networks. It returns True.

get_connection_pool_manager

get_connection_pool_manager() -> NodeConn
Source code in unaiverse/agent_basics.py
def get_connection_pool_manager(self) -> NodeConn:
    """Gets the connection pool manager (the NodeConn coordinator) of the node.

    Returns:
        The NodeConn of the node.
    """
    return self.node_conn

Returns node_conn.

create_proc_input_streams

create_proc_input_streams(buffered: bool = False) -> None
Source code in unaiverse/agent_basics.py
def create_proc_input_streams(self, buffered: bool = False) -> None:
    """Creates the processor input streams based on the `proc_inputs` defined for the agent.

    Args:
        buffered: If True, the created streams will be of type BufferedStream.
    """

    # Adding input streams (grouped together), passing the node clock
    if self.proc_inputs is not None:
        for i, procs in enumerate(self.proc_inputs):
            assert not isinstance(procs, str)
            procs.set_group("processor_in")  # Adding default group info, forced, do not change this!

            # Creating the streams
            for props in procs.props:
                if not buffered:
                    stream = Stream(props=props.clone())
                else:
                    stream = BufferedStream(props=props.clone())

                self.add_stream(stream, owned=True)

                public_peer_id, private_peer_id = self.get_peer_ids()
                peer_id = public_peer_id if stream.is_public() else private_peer_id
                net_hash = stream.net_hash(peer_id)
                if stream.is_public():
                    self.proc_in_net_hash['public'] = net_hash
                else:
                    self.proc_in_net_hash['private'] = net_hash

                # forcing the input stream to be compatible with proc inputs
                self.compat_in_streams[i].add((net_hash, props.get_name()))

Creates one owned stream per property of each proc_inputs entry and forces the group processor_in. With buffered=True the streams are BufferedStream objects. It records the net hash of the group in proc_in_net_hash for the public or the private network and marks each stream compatible with its own input. set_node_info calls it with buffered=False.

create_proc_output_streams

create_proc_output_streams(buffered: bool = False) -> None
Source code in unaiverse/agent_basics.py
def create_proc_output_streams(self, buffered: bool = False) -> None:
    """Creates the processor output streams based on the `proc_outputs` defined for the agent.

    Args:
        buffered: If True, the created streams will be of type BufferedStream.
    """

    # Adding generated streams (grouped together), passing the node clock
    if self.proc_outputs is not None:
        for i, procs in enumerate(self.proc_outputs):
            assert not isinstance(procs, str)
            procs.set_group("processor")  # Adding default group info, forced, do not change this!

            # Creating the streams
            for props in procs.props:
                if not buffered:
                    stream = Stream(props=props.clone())
                else:
                    stream = BufferedStream(props=props.clone())

                self.add_stream(stream, owned=True)

                public_peer_id, private_peer_id = self.get_peer_ids()
                peer_id = public_peer_id if stream.is_public() else private_peer_id
                net_hash = stream.net_hash(peer_id)
                if stream.is_public():
                    self.proc_net_hash['public'] = net_hash
                else:
                    self.proc_net_hash['private'] = net_hash

Creates one owned stream per property of each proc_outputs entry, forces the group processor and records the net hash in proc_net_hash. set_node_info calls it with buffered=buffer_generated.

get_proc_output_net_hash

get_proc_output_net_hash(public: bool = True) -> str | None
Source code in unaiverse/agent_basics.py
def get_proc_output_net_hash(self, public: bool = True) -> str | None:
    """Return the network hash of the processor output streams.

    Args:
        public: If True, returns the public net hash, otherwise the private one.

    Returns:
        The network hash string, or None if not yet set.
    """
    return self.proc_net_hash['public'] if public else self.proc_net_hash['private']

Returns the net hash of the processor output streams on the public network (public=True, the default) or in the world. Before set_node_info it returns None.

get_proc_input_net_hash

get_proc_input_net_hash(public: bool = True) -> str | None
Source code in unaiverse/agent_basics.py
def get_proc_input_net_hash(self, public: bool = True) -> str | None:
    """Return the network hash of the processor input streams.

    Args:
        public: If True, returns the public net hash, otherwise the private one.

    Returns:
        The network hash string, or None if not yet set.
    """
    return self.proc_in_net_hash['public'] if public else self.proc_in_net_hash['private']

Returns the net hash of the processor input streams on the public network (public=True, the default) or in the world. Before set_node_info it returns None.

update_streams_in_profile

update_streams_in_profile() -> None
Source code in unaiverse/agent_basics.py
def update_streams_in_profile(self) -> None:
    """Updates the agent's profile with information about its owned (environmental and processor) streams."""

    # Filling the information about the streams that can be generated and handled
    dynamic_profile = self.node_profile.get_dynamic_profile()
    if (hasattr(self, 'proc_outputs') and hasattr(self, 'proc_inputs') and
            self.proc_outputs is not None and self.proc_inputs is not None):
        dynamic_profile['proc_outputs'] = \
            [dct for d in self.proc_outputs
             if hasattr(d, "to_list_of_dicts") for dct in d.to_list_of_dicts()]  # noqa
        dynamic_profile['proc_inputs'] = \
            [dct for d in self.proc_inputs
             if hasattr(d, "to_list_of_dicts") for dct in d.to_list_of_dicts()]  # noqa

    # Adding the list of locally-created ("environmental") streams to the profile
    list_of_props = []
    public_peer_id, private_peer_id = self.get_peer_ids()
    for net_hash, streams_dict in self.owned_streams.items():
        if net_hash not in self.proc_streams.keys() and net_hash not in self.proc_in_streams.keys():
            if (DataProps.peer_id_from_net_hash(net_hash) == public_peer_id or
                    DataProps.peer_id_from_net_hash(net_hash) == private_peer_id):
                for stream in streams_dict.values():
                    list_of_props.append(stream.get_props().to_dict())  # DataProp
    if len(list_of_props) > 0:
        dynamic_profile['streams'] = list_of_props

Writes the streams of the agent in the dynamic profile of its node: proc_inputs and proc_outputs as lists of property dictionaries and, under streams, the properties of every owned environmental stream. Other agents read these entries to find compatible streams. Call it after adding an owned stream at run time and then send the profile with send_profile_to_all.

send_profile_to_all async

send_profile_to_all() -> None
Source code in unaiverse/agent_basics.py
async def send_profile_to_all(self) -> None:
    """Sends the agent's profile to all known agents (async)."""

    agents = list(self.all_agents.keys())
    for peer_id in agents:
        log.misc(f"Sending profile to {peer_id}")
        if not (await self.node_conn.send(peer_id, channel_trail=None,
                                          content=self.node_profile.get_all_profile(),
                                          content_type=Msg.PROFILE)):
            if self.node_conn.sends_are_queued:

                # A full send queue refused it: the peer is behind, not gone (the Session tells that)
                log.error(f"Profile to {peer_id} refused (send queue full), sent again at the next round")
            else:
                log.error("Failed to send profile, removing (disconnecting) " + peer_id)
                await self.remove_agent(peer_id)

Sends the full profile of the node to every known agent (async). A peer whose queue is full stays among the known agents and receives the profile in a later round. A peer that cannot be reached at all is removed with remove_agent.

subscribe_to_pubsub_owned_streams async

subscribe_to_pubsub_owned_streams() -> bool
Source code in unaiverse/agent_basics.py
async def subscribe_to_pubsub_owned_streams(self) -> bool:
    """Subscribes to all owned streams that are marked as PubSub (async).

    Returns:
        True if all subscriptions were successful, False otherwise.
    """

    # Opening channels for all the (groups of) owned streams (generated and not)
    for net_hash in list(self.owned_streams.keys()):  # A copy: the loop awaits
        is_pubsub = Stream.is_pubsub_from_net_hash(net_hash)

        if is_pubsub:
            log.misc(f"Opening channel for the owned stream {net_hash}")
            peer_id = Stream.peer_id_from_net_hash(net_hash)  # Guessing peer ID from the net hash

            if not (await self.node_conn.subscribe(peer_id, channel=net_hash)):
                log.error(f"Cannot open a channel for owned stream hash {net_hash}")
                return False
    return True

Opens the broadcast channel of every owned broadcast group (async). It returns False at the first failure and True otherwise. The node calls it at start and Agent.record calls it for the streams it records.

generate_id staticmethod

generate_id() -> str
Source code in unaiverse/agent_basics.py
@staticmethod
def generate_id() -> str:
    """Generate a random 8-character hexadecimal ID string.

    Returns:
        An 8-character hexadecimal string.
    """
    return _uuid.uuid4().hex[0:8]

Static method that returns eight random hexadecimal characters, the format of the id of an interaction.

Peers and roles

add_agent async

add_agent(peer_id: str, profile: NodeProfile, add_proc_streams: bool = True, add_env_streams: bool = True, add_pubsub_streams: bool = True) -> bool
Source code in unaiverse/agent_basics.py
async def add_agent(self, peer_id: str, profile: NodeProfile,
                    add_proc_streams: bool = True,
                    add_env_streams: bool = True,
                    add_pubsub_streams: bool = True) -> bool:
    """Add a new known agent (async).

    Args:
        peer_id: The unique identifier of the peer.
        profile: The NodeProfile object containing the peer's/agent's information.
        add_proc_streams: True if the processor's streams of the peer must be added to the list of known streams,
            if compatible.
        add_env_streams: True if the environmental streams of the peer must be added to the list of known streams,
            if compatible.
        add_pubsub_streams: True if pubsub streams must be added/subscribed.

    Returns:
        True if the agent was successfully added, False otherwise.
    """
    must_remove_agent_before_adding_again = False

    # Re-adding an existing agent might happen, for example when the profile of a known agent changed and was
    # sent again (e.g., changes of addresses, ...).
    # If the profile only changed from the point of view of innocent properties (connections, role, addresses, ...)
    # then we can overwrite the existing one with no issues. If streams changed, then we remove the agent and add
    # it again.
    if peer_id in self.all_agents:

        if profile.get_static_profile()["node_type"] != self.all_agents[peer_id].get_static_profile()["node_type"]:
            must_remove_agent_before_adding_again = True

        dynamic_profile = profile.get_dynamic_profile()
        environmental_streams = dynamic_profile['streams']
        proc_streams = dynamic_profile['proc_outputs']

        _dynamic_profile = self.all_agents[peer_id].get_dynamic_profile()
        _environmental_streams = _dynamic_profile['streams']
        _proc_streams = _dynamic_profile['proc_outputs']

        def compare(A: list[dict] | None, B: list[dict] | None):
            set_A = {json.dumps(d, sort_keys=True) for d in (A or [])}
            set_B = {json.dumps(d, sort_keys=True) for d in (B or [])}
            return set_A - set_B, set_B - set_A

        added, lost = compare(environmental_streams, _environmental_streams)
        if (add_env_streams and len(added) > 0) or len(lost) > 0:
            must_remove_agent_before_adding_again = True

        added, lost = compare(proc_streams, _proc_streams)
        if (add_proc_streams and len(added) > 0) or len(lost) > 0:
            must_remove_agent_before_adding_again = True

        if must_remove_agent_before_adding_again:

            # If the agent was already there, we remove it and add will add it again (in case of changes)
            await self.remove_agent(peer_id)  # It has no effects if the agent is not existing
        else:

            # If nothing structural changed, do not try to deal with streams
            if add_env_streams:
                add_env_streams = False
            if add_proc_streams:
                add_proc_streams = False

            # Temporarily remove the agent from these dicts, since they depend on the role, that might have changed
            self.public_agents.pop(peer_id, None)
            self.world_agents.pop(peer_id, None)
            self.world_masters.pop(peer_id, None)

    # Guessing the type of agent to add (accordingly to the default roles shared by every agent)
    role = self.node_conn.get_role(peer_id)
    self.all_agents[peer_id] = profile
    if role & 1 == self.ROLE_PUBLIC:
        self.public_agents[peer_id] = profile
        public = True
    elif role & 3 == self.ROLE_WORLD_AGENT:
        self.world_agents[peer_id] = profile
        public = False
    elif role & 3 == self.ROLE_WORLD_MASTER:
        self.world_masters[peer_id] = profile
        public = False
    else:
        log.error(f"Cannot add agent with peer ID {peer_id} - unknown role: {role}")
        del self.all_agents[peer_id]
        return False

    # Human or artificial?
    if profile.get_static_profile()["node_type"] == AgentBasics.HUMAN:
        self.human_agents[peer_id] = profile
    else:
        self.artificial_agents[peer_id] = profile

    # Check compatibility of the streams owned by the agent we are adding with our-agent's processor
    if self.proc_outputs is not None and self.proc_inputs is not None:

        # Check compatibility of the environmental streams of the agent we are adding with our-agent's processor
        environmental_streams = profile.get_dynamic_profile()['streams']
        if (add_env_streams and environmental_streams is not None and
                not (await self.add_compatible_streams(peer_id, environmental_streams,
                                                       buffered=False,
                                                       public=public,
                                                       skip_pubsub=not add_pubsub_streams))):
            await self.remove_agent(peer_id)  # Clearing
            return False

        # Check compatibility of the generated streams of the agent we are adding with our-agent's processor
        proc_streams = profile.get_dynamic_profile()['proc_outputs']
        if (add_proc_streams and proc_streams is not None and
                not (await self.add_compatible_streams(peer_id, profile.get_dynamic_profile()['proc_outputs'],
                                                       buffered=False,
                                                       public=public,
                                                       skip_pubsub=not add_pubsub_streams))):
            await self.remove_agent(peer_id)  # Clearing
            return False

    log.misc(f"Successfully added agent {profile.get_static_profile()['node_name']} "
             f"with peer ID {peer_id} (public: {public})")

    # A public peer that got in touch (this agent dialed it, or was dialed) is the partner of its own turns
    if public:
        self.set_lone_wolf_partner(peer_id)
    return True

Adds a peer to the known agents (async). The node calls it when the handshake with the peer is complete and again when the peer sends a new profile.

Argument Type Default Meaning
peer_id str required The peer.
profile NodeProfile required Its profile.
add_proc_streams bool True Add the processor output streams of the peer that are compatible with this processor.
add_env_streams bool True Add its compatible environmental streams.
add_pubsub_streams bool True Subscribe to the compatible broadcast streams.

The role that the connection pool records for the peer decides which dictionary receives it: public_agents, world_agents or world_masters. An unknown role returns False. For a peer already known, a change of node type or of its streams removes it and adds it again. Any other change (address, role) only refreshes the profile. A failure while adding the streams removes the peer and returns False. A public peer becomes the partner of the lone-wolf behavior (see set_lone_wolf_partner). It returns True on success.

remove_agent async

remove_agent(peer_id: str) -> None
Source code in unaiverse/agent_basics.py
async def remove_agent(self, peer_id: str) -> None:
    """Remove an agent (async).

    Args:
        peer_id: The unique identifier of the peer to remove.
    """
    if peer_id in self.all_agents:

        # Removing from agent list
        del self.all_agents[peer_id]
        if peer_id in self.world_agents:
            del self.world_agents[peer_id]
        elif peer_id in self.world_masters:
            del self.world_masters[peer_id]
        elif peer_id in self.public_agents:
            del self.public_agents[peer_id]

            # The partner leaving: the public peer that got in touch last among the others, or the placeholder
            # (not for a person, see set_lone_wolf_partner)
            behav = getattr(self, "behav_lone_wolf", None)
            if (behav is not None and not self.is_human() and
                    behav.get_wildcards().get(Custom.PARTNER_WILDCARD) == peer_id):
                self.set_lone_wolf_partner(next(reversed(self.public_agents), None))

        if peer_id in self.artificial_agents:
            del self.artificial_agents[peer_id]
        elif peer_id in self.human_agents:
            del self.human_agents[peer_id]

        if peer_id in self.proc_human_peer_id_to_interaction:
            del self.proc_human_peer_id_to_interaction[peer_id]

        # Clearing from the list of processor-input-compatible-streams
        if self.compat_in_streams is not None:
            for i, _ in enumerate(self.compat_in_streams):
                to_remove = []
                for net_hash_name in self.compat_in_streams[i]:
                    if DataProps.peer_id_from_net_hash(net_hash_name[0]) == peer_id:
                        to_remove.append(net_hash_name)
                for net_hash_name in to_remove:
                    self.compat_in_streams[i].remove(net_hash_name)

        # Clearing from the list of processor-output-compatible-streams
        if self.compat_out_streams is not None:
            for i, _ in enumerate(self.compat_out_streams):
                to_remove = []
                for net_hash_name in self.compat_out_streams[i]:
                    if DataProps.peer_id_from_net_hash(net_hash_name[0]) == peer_id:
                        to_remove.append(net_hash_name)
                for net_hash_name in to_remove:
                    self.compat_out_streams[i].remove(net_hash_name)

        # Clearing streams owned by the removed agent from the list of known streams
        await self.remove_streams(peer_id)

        # Removing from the status variables
        self.remove_peer_from_agent_status_attrs(peer_id)

        # Updating buffered stream index
        if peer_id in self.last_buffered_peer_id_to_info:
            del self.last_buffered_peer_id_to_info[peer_id]  # Only if present

        # Resetting counter, if needed
        if len(self.last_buffered_peer_id_to_info) == 0:
            self.last_buffered_id_counter = 0

        # Clearing pending interactions
        await self.im.remove_interactions_of_agent(peer_id)

        log.misc(f"Successfully removed agent with peer ID {peer_id}")

Forgets a peer (async). It does nothing for an unknown peer. Otherwise it removes the peer from every dictionary of peers, from the compatibility sets and from the status attributes, removes its streams, completes its interactions with DISCONNECTED and drops its buffered copies. When the peer was the partner of the lone-wolf behavior, the public peer that arrived last among the others takes its place.

remove_all_agents

remove_all_agents() -> None
Source code in unaiverse/agent_basics.py
def remove_all_agents(self) -> None:
    """Remove all known agents."""

    # Clearing all agents
    self.all_agents = {}
    self.public_agents = {}
    self.world_masters = {}
    self.world_agents = {}
    self.human_agents = {}
    self.artificial_agents = {}

    # Clearing the list of processor-output-compatible-streams
    if self.compat_in_streams is not None and self.proc_inputs is not None:
        self.compat_in_streams = [set() for _ in range(len(self.proc_inputs))]
    if self.compat_out_streams is not None and self.proc_outputs is not None:
        self.compat_out_streams = [set() for _ in range(len(self.proc_outputs))]

    # Clearing the list of known streams (not our own streams!)
    self.remove_all_streams(owned_too=False)
    log.misc(f"Successfully removed all agents")

Empties every dictionary of peers and the compatibility sets and removes every stream that the agent does not own. No interaction is completed and no connection is closed.

clear_world_related_data(world_peer_id: str) -> None
Source code in unaiverse/agent_basics.py
async def clear_world_related_data(self, world_peer_id: str) -> None:
    """Destroy all the cached information that is about a world (useful when leaving a world) (async)."""

    # Clearing status variables
    self.reset_agent_status_attrs()

    # Clear/reset
    await self.__remove_all_world_private_streams()
    await self.__remove_all_world_related_agents()
    if world_peer_id in self.proc_human_peer_id_to_interaction:
        del self.proc_human_peer_id_to_interaction[world_peer_id]
    self.node_conn.reset_rendezvous_tag()
    await self.node_conn.unsubscribe(world_peer_id, channel=f"{world_peer_id}::ps:rv")  # Special rendezvous (ps:rv)

Forgets the world world_peer_id (async). The node calls it when the agent leaves a world. It resets the status attributes, removes the private streams of other agents and every member and master of the world, drops the pending human request of the world, resets the rendezvous tag and leaves the rendezvous channel of the world.

resolve_agent_ref

resolve_agent_ref(ref: str) -> str | None
Source code in unaiverse/agent_basics.py
def resolve_agent_ref(self, ref: str) -> str | None:
    """Resolve an agent name or peer_id to a peer_id.

    If ``ref`` is already a known peer_id, it is returned as-is.
    Otherwise, the method searches all known agents by node_name.

    Args:
        ref: A peer_id or agent name.

    Returns:
        The peer_id if found, None otherwise.
    """

    # If already a valid peer_id
    if ref in self.all_agents:
        return ref

    # Search by owner/node_name (if only node_name is provided, assumes it is one of your agents)
    if '/' not in ref:
        ref = build_unaid(self.get_profile(), ref)

    for peer_id, profile in self.all_agents.items():
        if build_unaid(profile) == ref:
            return peer_id

    return None

Turns a reference to an agent into a peer id. A known peer id comes back as it is. A string without / is taken as the name of a node of the same account and becomes <account>/<name>. A string with / is compared with the <account>/<name> identifier of every known agent. It returns the peer id of the first match or None. The @action decorator applies it to the arguments named agent, agents, partner, partners, target and targets.

peer_id = self.resolve_agent_ref("ResNetAgent")           # a node of my account
peer_id = self.resolve_agent_ref("alice/ResNetAgent")     # a node of another account

get_name

get_name() -> str
Source code in unaiverse/agent_basics.py
def get_name(self) -> str:
    """Returns the name of the agent or world from the node's profile.

    Args:
        None.

    Returns:
        The name of the agent or world.
    """
    return self.node_name

Returns the name of the node (node_name). Before set_node_info the name is "unk".

get_profile

get_profile() -> NodeProfile
Source code in unaiverse/agent_basics.py
def get_profile(self) -> NodeProfile:
    """Returns the profile of the node hosting this agent/world.

        Returns:
            The NodeProfile of this node.
    """
    return self.node_profile

Returns the NodeProfile of the node. Before set_node_info it returns None.

get_peer_id

get_peer_id() -> str
Source code in unaiverse/agent_basics.py
def get_peer_id(self) -> str:
    """Return the current peer ID of the agent, depending on whether it is behaving in a world or not.

    Returns:
        The private peer ID if the agent is behaving in a world, the public peer ID otherwise.
    """
    public_peer_id, private_peer_id = self.get_peer_ids()
    if self.behaving_in_world():
        return private_peer_id
    else:
        return public_peer_id

Returns the private peer id while the world behavior is enabled and the public peer id otherwise. Code that runs outside a behavior step (for example an override of behave after super().behave()) therefore gets the public peer id.

get_peer_ids

get_peer_ids() -> tuple[str, str]
Source code in unaiverse/agent_basics.py
def get_peer_ids(self) -> tuple[str, str]:
    """Retrieve the public and private peer IDs of the agent, from the underlying node's dynamic profile.

    Returns:
        A tuple containing the public peer ID and the private peer ID.
        If either ID is not available, a placeholder string is returned <public_peer_id>, <private_peer_id>.
    """
    public_peer_id = None
    private_peer_id = None
    if self.node_profile is not None:
        dynamic_profile = self.node_profile.get_dynamic_profile()
        public_peer_id: str = dynamic_profile['peer_id']  # Public
        private_peer_id: str = dynamic_profile['private_peer_id']  # Private
    public_peer_id: str = '<public_peer_id>' if public_peer_id is None else public_peer_id
    private_peer_id: str = '<private_peer_id>' if private_peer_id is None else private_peer_id
    return public_peer_id, private_peer_id

Returns the pair (public_peer_id, private_peer_id) from the dynamic profile of the node. A missing id is replaced by the placeholder "<public_peer_id>" or "<private_peer_id>".

is_human

is_human() -> bool
Source code in unaiverse/agent_basics.py
def is_human(self) -> bool:
    """Check if the agent is marked as human in its node.

    Returns:
        True if the agent is in a human, False otherwise.
    """
    if self.node_profile is not None:
        return self.node_profile.get_static_profile()["node_type"] == self.HUMAN
    else:
        return False

Returns True when the node type in the profile is "human". It returns False before set_node_info.

in_world

in_world() -> bool
Source code in unaiverse/agent_basics.py
def in_world(self) -> bool:
    """Check if the agent is currently operating within a 'world'.

    Returns:
        True if the agent is in a world, False otherwise.
    """
    if self.node_profile is not None:
        return self.ROLE_STR_TO_BITS[self.node_profile.get_dynamic_profile()['connections']['role']] & 1 == 1
    else:
        return False

Returns True when bit 0 of the role in the dynamic profile is 1. This holds for a member and for a master of a world.

behaving_in_world

behaving_in_world() -> bool
Source code in unaiverse/agent_basics.py
def behaving_in_world(self) -> bool:
    """Checks if the agent's world-specific behavior state machine is currently active.

    Returns:
        True if the world behavior is active, False otherwise.
    """
    assert self.behav is not None
    return self.behav.is_enabled()

Returns True while the world behavior is enabled. behave enables it only during the step of the world behavior. The manager also enables it during the callback of an interaction of the world.

get_role

get_role(agent: str) -> str | None
Source code in unaiverse/agent_basics.py
def get_role(self, agent: str) -> str | None:
    """Gets the base role (no world-master/agent bits) of a connected agent.

    Args:
        agent: The peer id of the agent.

    Returns:
        The name of the role, or None when unknown.
    """
    role_int = self.node_conn.get_role(agent)
    base_role_int = (role_int >> 2) << 2
    return self.ROLE_BITS_TO_STR[base_role_int] if base_role_int in self.ROLE_BITS_TO_STR else None

Returns the base role name of the connected peer agent: the custom role without the world bits, such as "teacher". It returns None when the bits match no known role. The public role and the two plain world roles give "public_agent".

get_agents_by_role

get_agents_by_role(role: str | list[str], handshake_completed: bool = True) -> list[str]
Source code in unaiverse/agent_basics.py
def get_agents_by_role(self, role: str | list[str], handshake_completed: bool = True) -> list[str]:
    """Finds the connected agents that have the given role(s).

    Args:
        role: A role or a list of roles (an augmented role, e.g. "world_master~role1", matches exactly).
        handshake_completed: Whether to consider only agents whose handshake completed (default: True).

    Returns:
        The list of the peer ids found.
    """
    role_list = role if isinstance(role, list) else [role]
    searched_roles_int = set()

    for role in role_list:
        is_augmented = "~" in role
        role_int = self.ROLE_STR_TO_BITS[role]
        if not is_augmented:
            for role_prefix_int in {AgentBasics.ROLE_WORLD_AGENT, AgentBasics.ROLE_WORLD_MASTER}:
                searched_roles_int.add(role_prefix_int | role_int)
        else:
            searched_roles_int.add(role_int)

    found_agents = []
    for role_int in searched_roles_int:
        _, _found_connected_peer_ids = self.node_conn.find_addrs_by_role(role_int, return_peer_ids_too=True)
        if handshake_completed:
            for agent in _found_connected_peer_ids:
                if agent in self.all_agents:
                    found_agents.append(agent)
        else:
            found_agents += _found_connected_peer_ids

    return found_agents

Returns the peer ids of the connected peers that hold a role.

Argument Type Default Meaning
role str or list[str] required Role names. A plain custom role such as "teacher" matches both a member and a master with that role. An augmented role such as "world_master~teacher" matches exactly.
handshake_completed bool True Keep only the peers in all_agents. With False every peer that the connection pool lists with that role is returned.

A peer can appear twice when two roles of the list match it. An unknown role name raises KeyError.

get_current_role

get_current_role(return_int: bool = False, ignore_base_role: bool = True) -> str | int | None
Source code in unaiverse/agent_basics.py
def get_current_role(self, return_int: bool = False, ignore_base_role: bool = True) -> str | int | None:
    """Returns the current role of the agent.

    Args:
        return_int: If True, returns the integer representation of the role.
        ignore_base_role: If True, returns only the specific role part, not the base.

    Returns:
        The role as a string or integer, or None if the agent is not living in any worlds.
    """
    if self.in_world():
        role_str = self.node_profile.get_dynamic_profile()['connections']['role']
        if ignore_base_role:
            role_str = role_str.split("~")[-1]
        if not return_int:
            return role_str
        else:
            return self.ROLE_STR_TO_BITS[role_str]
    else:
        return None

Returns the role of this agent in its world. Outside a world it returns None.

Argument Type Default Meaning
return_int bool False Return the role bits instead of the name.
ignore_base_role bool True Drop the prefix world_master~ or world_agent~ and return the custom role alone.

accept_new_role

accept_new_role(role: int) -> None
Source code in unaiverse/agent_basics.py
def accept_new_role(self, role: int) -> None:
    """Set the agent's role and optionally load a default behavior (private/world behavior).

    Args:
        role: The integer role to assign to the agent (e.g., ROLE_PUBLIC, ROLE_WORLD_MASTER).
    """
    base_role_str = self.ROLE_BITS_TO_STR[(role >> 2) << 2]
    full_role_str = self.ROLE_BITS_TO_STR[role]

    self.node_profile.get_dynamic_profile()['connections']['role'] = full_role_str

    # The role FSMs arrive with the grant bundle; profiles of legacy worlds still
    # carry them in the dynamic section, so fall back there when the bundle had none
    base_role_to_behav = self.world_role_fsms or {}
    if not base_role_to_behav and self.world_profile is not None:
        base_role_to_behav = self.world_profile.get_dynamic_profile().get('world_roles_fsm') or {}
    default_behav = base_role_to_behav.get(base_role_str)  # A public role will not be found in the world map

    if default_behav is not None and isinstance(default_behav, str) and len(default_behav) > 0:
        default_behav_hsm = HybridStateMachine(self)
        default_behav_hsm.load(default_behav)
        self.behav = HybridStateMachine(self, policy=self.policy_default)
        self.behav.include(default_behav_hsm, make_a_copy=True)
        self.behav.set_role(base_role_str)
        self.set_policy_filter(self.policy_filter, public=False)

Assigns the role bits role to the agent. The node calls it when a world admits the agent and when the world changes its role. It writes the full role name in the dynamic profile. When the world sent a behavior for the base role (from world_role_fsms or, for older worlds, from the dynamic profile of the world), it builds a new world behavior from a copy of it, tags it with the role and installs policy_filter. A public role finds no behavior and leaves behav as it is.

evaluate_profile

evaluate_profile(role: int, profile: NodeProfile) -> bool
Source code in unaiverse/agent_basics.py
def evaluate_profile(self, role: int, profile: NodeProfile) -> bool:
    """Evaluate if a given profile is valid for this agent based on its role. It helps in identifying and filtering
     out invalid or 'cheating' profiles.

    Args:
        role: The expected integer role (e.g., ROLE_PUBLIC, ROLE_WORLD_MASTER) for the profile.
        profile: The NodeProfile object to be evaluated.

    Returns:
        True if the profile is considered valid for the specified role, False otherwise.
    """

    # If the role in the profile is not the provided role, a profile-cheater was found
    if (profile.get_dynamic_profile()['connections']['role'] in self.ROLE_STR_TO_BITS and
            self.ROLE_STR_TO_BITS[profile.get_dynamic_profile()['connections']['role']] != role):
        log.user(f"Cheater found: "
                 f"{profile.get_dynamic_profile()['connections']['role']} != {self.ROLE_BITS_TO_STR[role]}")
        return False  # Cheater found

    # These are just examples: you are expected to reimplement this method in your custom agent file
    if (role & 1 == self.ROLE_PUBLIC and
            profile.get_dynamic_profile()['guessed_location'] == 'Some Dummy Location, Just An Example Here'):
        return False
    elif (role & 3 == self.ROLE_WORLD_MASTER and
          profile.get_dynamic_profile()['guessed_location'] == 'Some Other Location, Just Another Example Here'):
        return False
    else:
        return True

A template for the check of the profile of a peer. It returns False when the role in the profile differs from role or when the guessed location equals one of the two placeholder strings that the method uses as examples. It returns True otherwise. The node of the current version does not call it.

build_augmented_roles_dictionaries staticmethod

build_augmented_roles_dictionaries(custom_roles: list[str] | set[str]) -> tuple[dict[int, str], dict[str, int]]
Source code in unaiverse/agent_basics.py
@staticmethod
def build_augmented_roles_dictionaries(custom_roles: list[str] | set[str]) -> tuple[dict[int, str], dict[str, int]]:
    """Augment the custom roles (role1, role2, etc.) with the default ones (public, world_master, etc.), generating
    all the mixed roles (world_master~role1, world_master~role2, ...)"""

    role_bits_to_str = {k: v for k, v in AgentBasics.ROLE_BITS_TO_STR.items()}
    role_str_to_bits = {k: v for k, v in AgentBasics.ROLE_STR_TO_BITS.items()}

    # Both Agent and World: Fusing basic roles and custom roles
    if len(custom_roles) > 0:
        if len(custom_roles) > 30:  # Safe value, could be increased
            log.critical("Maximum number of custom role overcame (max is 30)")
        for i, role_str in enumerate(custom_roles):
            role_int = 1 << (i + 2)  # 000000100, then 00001000, etc. (recall that the first two bits are reserved)
            role_str_to_bits[role_str] = role_int
            role_bits_to_str[role_int] = role_str
            AgentBasics.ROLE_STR_TO_BITS[role_str] = role_int

    # Both Agent and World: Augmenting roles
    roles_not_to_be_augmented = {AgentBasics.ROLE_PUBLIC,
                                 AgentBasics.ROLE_WORLD_AGENT,
                                 AgentBasics.ROLE_WORLD_MASTER}
    role_bits_to_str_original = {k: v for k, v in role_bits_to_str.items()}
    for role_int, role_str in role_bits_to_str_original.items():
        if role_int not in roles_not_to_be_augmented and "~" not in role_str:
            for role_base_int in {AgentBasics.ROLE_WORLD_AGENT, AgentBasics.ROLE_WORLD_MASTER}:
                augmented_role_int = role_base_int | role_int
                augmented_role_str = role_bits_to_str[role_base_int] + "~" + role_str
                if augmented_role_str not in role_str_to_bits:
                    role_str_to_bits[augmented_role_str] = augmented_role_int
                    role_bits_to_str[augmented_role_int] = augmented_role_str

    return role_bits_to_str, role_str_to_bits

Static method that builds the role dictionaries of a world from its custom roles. The i-th custom role receives the bits 1 << (i + 2). Each custom role is then combined with the two world roles: world_agent~<role> with bits 1 | role and world_master~<role> with bits 3 | role. It returns (role_bits_to_str, role_str_to_bits). More than 30 custom roles produce a critical log. As a side effect it also writes each custom role in the class dictionary AgentBasics.ROLE_STR_TO_BITS.

bits_to_str, str_to_bits = AgentBasics.build_augmented_roles_dictionaries(["student", "teacher"])
str_to_bits["teacher"]                # 8
str_to_bits["world_master~teacher"]   # 11

augment_roles

augment_roles(role_bits_to_str: dict[int, str] | None = None, role_str_to_bits: dict[str, int] | None = None) -> None
Source code in unaiverse/agent_basics.py
def augment_roles(self,
                  role_bits_to_str: dict[int, str] | None = None,
                  role_str_to_bits: dict[str, int] | None = None) -> None:
    """Augment the custom roles (role1, role2, etc.) with the default ones (public, world_master, etc.), generating
    all the mixed roles (world_master~role1, world_master~role2, ...)"""

    if role_bits_to_str is None or role_str_to_bits is None:
        role_bits_to_str, role_str_to_bits = AgentBasics.build_augmented_roles_dictionaries(self.CUSTOM_ROLES)

    self.ROLE_BITS_TO_STR.clear()
    for k, v in role_bits_to_str.items():
        self.ROLE_BITS_TO_STR[k] = v
    self.ROLE_STR_TO_BITS.clear()
    for k, v in role_str_to_bits.items():
        self.ROLE_STR_TO_BITS[k] = v

Replaces the content of ROLE_BITS_TO_STR and ROLE_STR_TO_BITS with the given dictionaries. With either argument None it builds them from CUSTOM_ROLES with build_augmented_roles_dictionaries. A world calls it in set_node_info and the node calls it with the roles of the world when the agent joins.

load_and_refactor_action_file_and_behav_files

load_and_refactor_action_file_and_behav_files(force_save: bool = False) -> None
Source code in unaiverse/agent_basics.py
def load_and_refactor_action_file_and_behav_files(self, force_save: bool = False) -> None:
    """This method is called when building a world object. It loads the behavior files and refactors them.
    It loads the action file agent.py. It checks consistency between the agent action files agent.py and the roles
    in the behavior files.

        Args:
            force_save: Boolean to force the saving of the JSON and of a "pdf" folder with the PDFs of the state
                machines.
    """

    # World only: the world discovers CUSTOM_ROLES from the JSON files in the world folder
    if self.world_folder is not None and self.is_world:

        # Guessing roles from the list of JSON files
        listdir = os.listdir(self.world_folder)  # Do this only once
        listdir.sort()  # Keep it stable
        self.CUSTOM_ROLES = [os.path.splitext(f)[0] for f in listdir
                             if os.path.isfile(os.path.join(self.world_folder, f))
                             and f.lower().endswith(".json")]
        if len(self.CUSTOM_ROLES) == 0:
            raise GenException(f"No world-role files (*.json) were found in the world folder {self.world_folder}")

        # Default behaviors (getting roles, that are the names of the files with extension "json")
        default_behav_files = [os.path.join(self.world_folder, f) for f in listdir
                               if os.path.isfile(os.path.join(self.world_folder, f)) and
                               f.lower().endswith(".json")]

        # Loading Python files in the "world" folder
        try:
            self.packed_agent_files = pack_py_files(collect_py_files(self.world_folder,
                                                                     exclude_dirs={'pdf', 'stats'}))
        except Exception as e:
            raise GenException(f'Error while reading the agent-related python files in {self.world_folder} [{e}]')

        # Loading and refactoring behaviors
        agent_files = unpack_py_files(self.packed_agent_files)

        # We keep the compatibility with the case of a single agent.py
        if len(self.CUSTOM_ROLES) > 0:
            found = 0
            found_agent_py = False
            for role in self.CUSTOM_ROLES:
                for file_name in agent_files.keys():
                    if file_name == "agent.py":
                        found_agent_py = True
                    if file_name == f"{role}.py":
                        found += 1
                        break
            if found != len(self.CUSTOM_ROLES):
                if found_agent_py:
                    code_content = agent_files["agent.py"]
                    stats_source = agent_files.get('stats.py')

                    # All roles go to the content of agent.py; stats.py (when present)
                    # must survive the rewrite, since it now travels inside the bundle
                    agent_files = {f"{k}.py": code_content for k in self.CUSTOM_ROLES}
                    if stats_source is not None:
                        agent_files['stats.py'] = stats_source
                else:
                    raise GenException(f'Mismatching JSON-file roles and .py files in {self.world_folder}')

        for role, default_behav_file in zip(self.CUSTOM_ROLES, default_behav_files):
            dummy_agent_memory_finder = None

            try:

                # Creating a dummy agent which supports the actions of the following state machines
                try:
                    dummy_agent, dummy_agent_memory_finder = load_agent_in_memory(agent_files, role, proc=None)
                    loaded_roles = dummy_agent.CUSTOM_ROLES
                    dummy_agent.CUSTOM_ROLES = self.CUSTOM_ROLES
                except Exception as e:
                    raise GenException(f'Unable to create a valid dummy agent object for agent with role {role} '
                                       f'[{e}]')

                # Checking if the roles you wrote in agent.py are coherent with the JSON files in this folder;
                # most agents declare no roles at all (they inherit the world's ones by the injection above),
                # so the check only applies when the agent code takes a stance, and order does not matter
                if loaded_roles and set(loaded_roles) != set(self.CUSTOM_ROLES):
                    raise GenException(f"Mismatching roles. "
                                       f"Roles in JSON files: {self.CUSTOM_ROLES}. "
                                       f"Roles specified in the agent.py file: {loaded_roles}")

                try:
                    behav = HybridStateMachine(dummy_agent)
                    behav.load(default_behav_file)
                    self.role_to_behav[role] = str(behav)
                except Exception as e:
                    raise GenException(f'Error while loading or handling '
                                       f'behav file {default_behav_file} for role {role} [{e}]')

                # Refactoring and saving PDF
                try:
                    if (force_save or
                            behav.save(os.path.join(self.world_folder, f'{role}.json'),
                                       only_if_changed=dummy_agent)):
                        os.makedirs(os.path.join(self.world_folder, 'pdf'), exist_ok=True)
                        behav.save_pdf(os.path.join(self.world_folder, 'pdf', f'{role}.pdf'))
                except Exception as e:
                    raise GenException(f'Error while saving the behav file {default_behav_file} for role {role} '
                                       f'[{e}]')

            finally:

                # Clearing memory — runs on success AND on every GenException above
                if dummy_agent_memory_finder is not None:
                    dummy_agent_memory_finder.cleanup()

        # Ship only what joiners can execute: the role files plus the closure of
        # their relative imports, with stats.py forced in (it is executed in a bare
        # module on the joiner, so its own imports are world-side only and are not
        # followed). World-side code and non-imported files stay private.
        entry_files = [f"{role}.py" for role in self.CUSTOM_ROLES]
        pruned_files = prune_to_import_closure(agent_files, entry_files, forced=('stats.py',))
        kept_private = sorted(set(agent_files) - set(pruned_files))
        self.packed_agent_files = pack_py_files(pruned_files)
        log.misc(f"World code bundle: shipping {sorted(pruned_files)}" +
                 (f", keeping private {kept_private}" if kept_private else ""))

Prepares the role files of a world. set_node_info calls it on worlds only.

  1. It reads the role names from the *.json files of world_folder in alphabetical order. A folder without JSON files raises GenException.
  2. It reads every Python file of the folder (except the folders pdf and stats). Each role needs <role>.py. When one of these files is missing, a single agent.py serves every role. A folder without agent.py in that case raises GenException.
  3. For each role it loads the agent class of the role file and checks that the roles it declares match the JSON files. It then loads the behavior and keeps its text in role_to_behav. When the behavior changed or force_save is True, it saves the normalized JSON and a PDF drawing in <world_folder>/pdf/.
  4. The package of code that joining agents receive holds only the role files, the files they import and stats.py. Every other file of the folder stays on the world.

create_behav_files

create_behav_files() -> None
Source code in unaiverse/agent_basics.py
def create_behav_files(self) -> None:
    """This method is called when building a world object. In your custom world-class, you can overload this method
    and create the JSON files with the role-related behaviors, if you like. Recall that acting like this is not
    mandatory at all: you can just manually create the JSON  files, and this method will simply do nothing."""
    pass

A hook for worlds that generate their role behaviors in code. set_node_info calls it before loading the role files. The default does nothing.

set_lone_wolf_partner

set_lone_wolf_partner(peer_id: str | None) -> None
Source code in unaiverse/agent_basics.py
def set_lone_wolf_partner(self, peer_id: str | None) -> None:
    """Points the <partner> wildcard of the lone-wolf behavior at a public peer (agents that are not a person).

    The partner is where the turns this agent takes on its own are sent (the default public behavior sends them to
    <partner>); the answers to requests go to whoever asked, whatever the partner. It is the public peer that got
    in touch last (dialing or dialed), then the one whose request was accepted last; when it leaves, the public
    peer that got in touch last among the others.

    A person decides whom they write to, so the partner of a person's agent is left to whoever drives it: the
    browser sets it to the peer the person writes to at every message (the Forward command of Node.js), with many
    chats open; the interactive mode of node.py sets it to the peer of the console. Nothing is changed here then.

    Args:
        peer_id: A public peer, or None to put the placeholder back (a send to it then fails cleanly).
    """
    behav = getattr(self, "behav_lone_wolf", None)
    if behav is None or self.is_human():
        return
    value = peer_id if peer_id is not None else Custom.PARTNER_WILDCARD
    wildcards = behav.get_wildcards()
    if Custom.PARTNER_WILDCARD not in wildcards or wildcards[Custom.PARTNER_WILDCARD] == value:
        return
    behav.update_wildcard(Custom.PARTNER_WILDCARD, value)
    behav.apply_wildcards()

Points the wildcard <partner> of the public behavior at peer_id and applies it. None puts the literal <partner> back and a later send to <partner> fails without effect. The partner receives the turns that the agent takes on its own. Answers to requests always go to the requester. The agent calls this method after adding a public peer and after accepting a public request. When the partner leaves, the agent calls it with the public peer that arrived last among the others. The method does nothing for the agent of a person because whoever drives that agent (the web application or the console) chooses the partner at every message.

add_behav_wildcard

add_behav_wildcard(wildcard_from: str, wildcard_to: object) -> None
Source code in unaiverse/agent_basics.py
def add_behav_wildcard(self, wildcard_from: str, wildcard_to: object) -> None:
    """Adds a wildcard mapping for the agent's behavior state machine, use when joining worlds.

    Args:
        wildcard_from: The string to be used as a wildcard.
        wildcard_to: The object to replace the wildcard.
    """
    self.behav_wildcards[wildcard_from] = wildcard_to

Records the wildcard wildcard_from with the value wildcard_to in behav_wildcards. The node adds these wildcards to the world behavior when the agent joins a world.

Behaving

behave async

behave() -> None
Source code in unaiverse/agent_basics.py
async def behave(self) -> None:
    """Behave in the current environment, calling the state-machines of the public and private networks (async)."""

    assert isinstance(self.behav_lone_wolf, HybridStateMachine)
    assert isinstance(self.behav, HybridStateMachine)

    if self.in_world():
        log.set_sub("prv")
        log.misc("Behaving (world)...")
        if self.behav is None:
            log.error("No behaviour specified")
        else:
            if self.behav_lone_wolf is not None:
                self.behav_lone_wolf.enable(False)
            self.behav.enable(True)
            self.stdin.bind(self.__proc_in_streams_by_user_hash_prv, uuid=Custom.SYSTEM_INTERACTION_UUID)
            self.stdout.bind(self.__proc_streams_by_user_hash_prv, uuid=Custom.SYSTEM_INTERACTION_UUID)
            self.stdext.bind(self.__env_streams_by_user_hash_prv, uuid=Custom.SYSTEM_INTERACTION_UUID)
            await self.on_tick()
            await self.behav.act()
            self.behav.enable(False)

    log.set_sub("pub")
    log.misc("Behaving (public)...")
    if self.behav_lone_wolf is None:
        log.error("No behaviour specified")
    else:
        if self.behav is not None:
            self.behav.enable(False)
        self.behav_lone_wolf.enable(True)
        self.stdin.bind(self.__proc_in_streams_by_user_hash_pub, uuid=Custom.SYSTEM_INTERACTION_UUID)
        self.stdout.bind(self.__proc_streams_by_user_hash_pub, uuid=Custom.SYSTEM_INTERACTION_UUID)
        self.stdext.bind(self.__env_streams_by_user_hash_pub, uuid=Custom.SYSTEM_INTERACTION_UUID)
        await self.behav_lone_wolf.act()
        self.behav_lone_wolf.enable(False)

    log.set_sub("gen")

    # Clear expired interactions at every clock cycle and notify originators
    await self.im.complete_expired()

    # Also drain recently completed interactions for status notification
    completed = self.im.drain_completed()

    # Clear stream-expired data
    self.im.clear_expired_stream_data()

    for interaction in completed:
        if (interaction.requester is not None and not interaction.volatile and
                interaction.requester in self.all_agents):
            log.inter(f"Communicating completion of interaction {interaction.to_code_str(True)}")
            my_public_peer_id, my_private_peer_id = self.get_peer_ids()
            if interaction.requester in self.public_agents:
                my_peer_id: str = my_public_peer_id
            else:
                my_peer_id: str = my_private_peer_id
            ret = await self.node_conn.send(interaction.requester, channel_trail=None,
                                            content=interaction.to_status_dict(status_generated_by=my_peer_id),
                                            content_type=Msg.INTERACTION_STATUS)
            if not ret and self.node_conn.sends_are_queued:

                # A full send queue refused it: the requester is behind, not gone (the Session tells that); its
                # interaction will end by its own timeout
                log.error(f"Interaction status to {interaction.requester} refused (send queue full)")
            elif not ret:
                log.error(
                    f"Failed to send interaction status to peer {interaction.requester}, disconnecting it")

                assert self.node_purge_fcn is not None

                # Send-failure teardown: LOCAL_ERROR (best-effort GOAWAY on a possibly dead link).
                await self.node_purge_fcn(interaction.requester, reason=LOCAL_ERROR)

Runs one tick of the agent (async). The node calls it at every cycle.

  1. In a world: it enables only the world behavior, binds stdin, stdout and stdext to the private streams, awaits on_tick() and makes one step of the world behavior.
  2. It enables only the public behavior, binds the proxies to the public streams and makes one step of it. An agent in a world keeps answering on the public network.
  3. It completes the expired interactions, drains the completed ones and drops the stream data of closed interactions.
  4. For each drained interaction with a known requester that is not volatile, it sends the status to the requester. A refused send (full queue) is logged. Any other failed send disconnects the requester.

An override must await super().behave() and must not block.

on_tick async

on_tick() -> None
Source code in unaiverse/agent_basics.py
async def on_tick(self) -> None:
    """Hook called once per tick, before the world behavior acts; override it in agents (async)."""
    pass

A hook awaited once per tick before the step of the world behavior while the agent is in a world. The world behavior is enabled during the call. The default does nothing.

learn_behave

learn_behave(state: int, last_action: int, prev_state: int) -> None
Source code in unaiverse/agent_basics.py
def learn_behave(self, state: int, last_action: int, prev_state: int) -> None:
    """A placeholder method for behavioral learning, intended to be implemented by child classes.
    It receives state and action information to update a behavioral model.

    Args:
        state: The current state of the agent.
        last_action: The last action taken.
        prev_state: The previous state of the agent.

    Returns:
        None in the base implementation; subclasses are expected to return state-related feedback.
    """
    pass

A placeholder for agents that learn their behavior. It receives the current state, the last action and the previous state. The default does nothing and nothing in the SDK calls it.

set_policy async

set_policy(policy_method_name_or_policy_fcn: str | Callable[[list[Action]], [int, Interaction | None]], public: bool = False) -> bool
Source code in unaiverse/agent_basics.py
async def set_policy(self,
                     policy_method_name_or_policy_fcn: str | Callable[[list[Action]], [int, Interaction | None]],
                     public: bool = False) -> bool:
    """Sets the policy to be used in selecting what action to perform in the current state (async).

    Args:
        policy_method_name_or_policy_fcn: The name of a method of the Agent class that implements a policy function.
            It is a function that takes a list of `Action` objects that are candidates for execution, and returns
            the index of the selected action and an ActionRequest object with the action-requester details
            (requester, arguments, time, and UUID), or -1 and None if no action is selected.
            By design, every agent implements a basic policy function named "policy_default".
        public: If True, the policy will be applied to the public HSM, otherwise to the private/world one.

    Returns:
        True if the policy was successfully set, False otherwise.
    """
    if isinstance(policy_method_name_or_policy_fcn, str):
        policy_fcn = getattr(self, policy_method_name_or_policy_fcn, None)
        if not callable(policy_fcn):
            return False
        behav = self.behav if not public else self.behav_lone_wolf
        assert isinstance(behav, HybridStateMachine)
        policy_fcn: Callable[[int, Interaction | None, list[Action], dict], tuple[int, Interaction | None]] | None
        behav.set_policy(policy_fcn)
        return True
    elif callable(policy_method_name_or_policy_fcn):
        policy_fcn = policy_method_name_or_policy_fcn
        behav = self.behav if not public else self.behav_lone_wolf
        assert isinstance(behav, HybridStateMachine)
        policy_fcn: Callable[[int, Interaction | None, list[Action], dict], tuple[int, Interaction | None]] | None
        behav.set_policy(policy_fcn)
        return True
    return False

Replaces the policy of a behavior (async). The policy chooses which feasible action of the current state runs.

Argument Type Default Meaning
policy_method_name_or_policy_fcn str or callable required A method name of the agent or a function. It receives the list of the candidate Action objects and returns the index of the chosen one and the Interaction to serve. Without a choice it returns (-1, None).
public bool False True selects the public behavior and False the world one.

It returns True when it installed the policy and False when the name is not a callable method.

set_policy_filter

set_policy_filter(filter_method_name_or_policy_fcn: str | Callable[[int, Interaction | None, list[Action], dict], [int, Interaction | None]] | None, public: bool = False) -> bool
Source code in unaiverse/agent_basics.py
def set_policy_filter(self,
                      filter_method_name_or_policy_fcn: str | Callable[
                          [int, Interaction | None, list[Action], dict], [int, Interaction | None]] | None,
                      public: bool = False) -> bool:
    """Sets the policy filter function, which overrides the action selected by the policy in the current state.

    Args:
        filter_method_name_or_policy_fcn: The name of a method of the Agent class or a function that implements a
            policy filtering function, overriding what the policy decided.
            It is a function that takes what the policy decided, a list of `Action` objects that are candidates
            for execution, and a dictionary with customizable field (always including the "agent" key, with a ref
            to the current agent) and returns the index of the selected action and an ActionRequest object with the
            action-requester details (requester, arguments, time, and UUID), or -1 and None
            if no action is selected.
            By design, every agent comes with no filtering active.
        public: If True, the filter will be applied to the public HSM, otherwise to the private/world one.

    Returns:
        True if the filter was successfully set, False otherwise.
    """
    if isinstance(filter_method_name_or_policy_fcn, str):
        filter_fcn: Callable | None = getattr(self, filter_method_name_or_policy_fcn, None)
        if not callable(filter_fcn):
            return False
        if public:
            self.policy_filter_lone_wolf = filter_fcn
            assert isinstance(self.behav_lone_wolf, HybridStateMachine)
            self.behav_lone_wolf.set_policy_filter(self.policy_filter_lone_wolf, self.policy_filter_lone_wolf_opts)
            self.policy_filter_lone_wolf_opts['agent'] = self  # Forced (do it *after* set_policy_filter)
            self.policy_filter_lone_wolf_opts['public'] = True
        else:
            self.policy_filter = filter_fcn
            assert isinstance(self.behav, HybridStateMachine)
            self.behav.set_policy_filter(self.policy_filter, self.policy_filter_opts)
            self.policy_filter_opts['agent'] = self  # Forced (do it *after* set_policy_filter)
            self.policy_filter_opts['public'] = False
        return True
    elif callable(filter_method_name_or_policy_fcn):
        if public:
            self.policy_filter_lone_wolf = filter_method_name_or_policy_fcn
            assert isinstance(self.behav_lone_wolf, HybridStateMachine)
            self.behav_lone_wolf.set_policy_filter(self.policy_filter_lone_wolf, self.policy_filter_lone_wolf_opts)
            self.policy_filter_lone_wolf_opts['agent'] = self  # Forced (do it *after* set_policy_filter)
            self.policy_filter_lone_wolf_opts['public'] = True
        else:
            self.policy_filter = filter_method_name_or_policy_fcn
            assert isinstance(self.behav, HybridStateMachine)
            self.behav.set_policy_filter(self.policy_filter, self.policy_filter_opts)
            self.policy_filter_opts['agent'] = self  # Forced (do it *after* set_policy_filter)
            self.policy_filter_opts['public'] = False
        return True
    return False

Installs a filter that can override the choice of the policy of a behavior.

Argument Type Default Meaning
filter_method_name_or_policy_fcn str, callable or None required A method name of the agent or a function. The behavior calls it with the choice of the policy, the candidate actions and an options dict. It returns the index of the action and the interaction. The pair (-1, None) chooses nothing.
public bool False True selects the public behavior and False the world one.

The options dictionary (policy_filter_opts or policy_filter_lone_wolf_opts) always holds agent (this agent) and public (the flag). It returns True when it installed the filter and False for None or for a name that is not a callable method. See Behaviors.

policy_default

policy_default(actions_list: list[Action]) -> tuple[int, Interaction | None]
Source code in unaiverse/agent_basics.py
def policy_default(self, actions_list: list[Action]) -> tuple[int, Interaction | None]:
    """This is the default policy for selecting which action to execute from a list of feasible actions.
    It prioritizes actions that have been explicitly requested (i.e., have pending requests) on a first-come,
    first-served basis. If no requested actions are found, it then selects the first action in the list that is
    marked as `ready`.

    Args:
        actions_list: A list of `Action` objects that are candidates for execution.

    Returns:
        The index of the selected action and an ActionRequest object with the requester details (requester,
            arguments, time, and UUID), or -1 and None if no action is selected.
    """
    for i, action in enumerate(actions_list):
        if action.is_high_priority:
            _list_of_requests = action.get_list_of_interactions()
            _selected_action_idx = i
            _selected_interaction = _list_of_requests.get_oldest_interaction() \
                if len(_list_of_requests) > 0 else None
            return _selected_action_idx, _selected_interaction
    for i, action in enumerate(actions_list):
        _list_of_requests = action.get_list_of_interactions()
        if len(_list_of_requests) > 0:  # The process action has more priority
            _selected_action_idx = i
            _selected_interaction = _list_of_requests.get_oldest_interaction()
            return _selected_action_idx, _selected_interaction
    for i, action in enumerate(actions_list):
        if action.is_ready(consider_interactions=False):
            _selected_action_idx = i
            _selected_interaction = None
            return _selected_action_idx, _selected_interaction
    _selected_action_idx = -1
    _selected_interaction = None
    return _selected_action_idx, _selected_interaction

The default policy of both behaviors. Given the candidate actions of the current state, it picks the first one of these three rules that applies.

  1. The first high-priority action together with its oldest pending interaction (or None).
  2. The first action with a pending request together with its oldest interaction.
  3. The first action ready to run on its own initiative together with None.

It returns (index, interaction). When no action applies it returns (-1, None).

inject_received_interaction

inject_received_interaction(sender: str, interaction_dict: dict) -> None
Source code in unaiverse/agent_basics.py
def inject_received_interaction(self, sender: str, interaction_dict: dict) -> None:
    """Registers an interaction received from a peer, linking it to its action in the behavior.

    Args:
        sender: The peer that sent the interaction.
        interaction_dict: The interaction, as received (a dictionary).
    """

    # Creating the interaction object
    interaction = Interaction.from_dict(interaction_dict)

    # Marking
    public = sender in self.public_agents

    # Also register with the HSM for action selection
    behav = self.behav_lone_wolf if public else self.behav
    assert isinstance(behav, HybridStateMachine)

    if (interaction.action_name is not None and len(interaction.action_name) > 0 and
            not behav.request_action(interaction)):  # Here the interaction links to action (IM does not do this!)
        log.error(f"Cannot enqueue a received interaction!")
    else:

        # Register with the InteractionManager
        log.misc(f"Registering received interaction for action "
                 f"{interaction.action_name}")

        # The partner follows the conversation: the turns this agent takes on its own go to the public peer whose
        # request it accepted last
        if self.im.register_received(interaction, public) and public:
            self.set_lone_wolf_partner(sender)

Accepts an interaction that arrived from sender. The node calls it for every incoming request. It rebuilds the Interaction from interaction_dict and asks the behavior of the network of the sender to queue it on the requested action. When the behavior refuses (no such action in the current state machine) it logs an error and registers nothing. Otherwise it registers the interaction in the manager. When a public request is registered, its sender becomes the partner of the lone-wolf behavior.

reject_received_interaction async

reject_received_interaction(sender: str, interaction_dict: dict) -> None
Source code in unaiverse/agent_basics.py
async def reject_received_interaction(self, sender: str, interaction_dict: dict) -> None:
    """Tells the sender of an interaction that it was not accepted, instead of dropping it silently (async).

    The sender's interaction completes at once with reason REJECTED, so the action waiting for it goes on instead
    of waiting for its timeout. Used when there is no room for it (in the interaction manager, or among the
    messages waiting for the end of a running action).

    Args:
        sender: The peer that sent the interaction.
        interaction_dict: The interaction, as received (a dictionary).
    """
    my_public_peer_id, my_private_peer_id = self.get_peer_ids()
    status = {'status_generated_by': my_public_peer_id if sender in self.public_agents else my_private_peer_id,
              'uuid': interaction_dict.get('uuid') if isinstance(interaction_dict, dict) else None,
              'status': InteractionStatus.COMPLETED.value,
              'completion_reason': CompletionReason.REJECTED.value,
              'destination_state': None,
              'data_tags': None}
    if not (await self.node_conn.send(sender, channel_trail=None, content=status,
                                      content_type=Msg.INTERACTION_STATUS)):
        log.error(f"Could not tell {sender} that its interaction was rejected")

Tells sender that its interaction was not accepted (async). It sends a status message with COMPLETED and REJECTED. The action that waits for it on the sender then ends at once. The node calls it when the manager has no room or when too many messages wait for the end of the running action.

Streams

add_stream

add_stream(stream: Stream, owned: bool = True, net_hash: str | None = None) -> dict[str, Stream]
Source code in unaiverse/agent_basics.py
def add_stream(self, stream: Stream, owned: bool = True, net_hash: str | None = None) -> dict[str, Stream]:
    """Add a new stream to the set of known streams.

    Args:
        stream: The Stream object to add.
        owned: If True, the streams are considered owned by this agent.
        net_hash: Optional network hash for the streams. If None, it will be generated.

    Returns:
        A dictionary containing the added stream and the possibly already present streams belonging to the same
        group (stream name -> stream object).
    """

    # Stream net hash
    assert stream.props is not None
    if net_hash is None:
        public_peer_id, private_peer_id = self.get_peer_ids()
        peer_id = public_peer_id if stream.is_public() else private_peer_id
        net_hash = stream.net_hash(peer_id)
    user_hash = stream.user_hash(stream.peer_id_from_net_hash(net_hash))

    # It is fine to overwrite an existing stream, but the net hash cannot change
    if net_hash not in self.known_streams and user_hash in self.known_streams_by_user_hash:
        raise GenException(f"Naming clash in streams. "
                           f"Net hash {net_hash} is not known (stream name: {stream.props.get_name()}), "
                           f"but user hash {user_hash} is already existing. "
                           f"Are you using the same name for two different streams? (not allowed)")

    # Adding the new stream
    if net_hash not in self.known_streams:
        self.known_streams[net_hash] = {}
    else:
        for _stream in self.known_streams[net_hash].values():
            public = _stream.get_props().is_public()
            pubsub = _stream.get_props().is_pubsub()
            if public and not stream.get_props().is_public():
                log.error(f"Cannot add a stream to a group with different properties (public): "
                          f"hash: {net_hash}, name: {stream.get_props().get_name()}, "
                          f"public: {stream.get_props().is_public()}")
                return {}
            if pubsub and not stream.get_props().is_pubsub():
                log.error(f"Cannot add a stream to a group with different properties (pubsub): "
                          f"hash: {net_hash}, name: {stream.get_props().get_name()}, "
                          f"public: {stream.get_props().is_public()}")
                return {}
            break
    self.known_streams[net_hash][stream.get_props().get_name()] = stream  # Overwrite if existing
    self.known_streams_by_user_hash[user_hash] = stream  # Overwrite if existing

    if owned:
        is_proc_outputs_stream = False
        is_proc_inputs_stream = False

        # Adding an 'owned' processor output stream (i.e., the stream coming from OUR OWN processor)
        if self.proc_outputs is not None:
            proc_outputs_name_and_group = set()
            for props in self.proc_outputs:
                assert not isinstance(props, str)
                proc_outputs_name_and_group.add((props.get_name(), props.get_group()))
            if (stream.get_props().get_name(), stream.get_props().get_group()) in proc_outputs_name_and_group:
                if net_hash not in self.proc_streams:
                    self.proc_streams[net_hash] = {}
                self.proc_streams[net_hash][stream.get_props().get_name()] = stream
                self.proc_streams_by_user_hash[user_hash] = stream
                if stream.is_public():
                    self.__proc_streams_by_user_hash_pub[user_hash] = stream
                else:
                    self.__proc_streams_by_user_hash_prv[user_hash] = stream
                is_proc_outputs_stream = True

        # Adding an 'owned' processor input stream (i.e., the stream entering OUR OWN processor)
        if self.proc_inputs is not None and not is_proc_outputs_stream:
            proc_inputs_name_and_group = set()
            for props in self.proc_inputs:
                assert not isinstance(props, str)
                proc_inputs_name_and_group.add((props.get_name(), props.get_group()))
            if (stream.get_props().get_name(), stream.get_props().get_group()) in proc_inputs_name_and_group:
                if net_hash not in self.proc_in_streams:
                    self.proc_in_streams[net_hash] = {}
                self.proc_in_streams[net_hash][stream.get_props().get_name()] = stream
                self.proc_in_streams_by_user_hash[user_hash] = stream
                if stream.is_public():
                    self.__proc_in_streams_by_user_hash_pub[user_hash] = stream
                else:
                    self.__proc_in_streams_by_user_hash_prv[user_hash] = stream
                is_proc_inputs_stream = True

        if net_hash not in self.owned_streams:
            self.owned_streams[net_hash] = {}
        self.owned_streams[net_hash][stream.get_props().get_name()] = stream
        self.owned_streams_by_user_hash[user_hash] = stream

        if not is_proc_outputs_stream and not is_proc_inputs_stream:
            if net_hash not in self.env_streams:
                self.env_streams[net_hash] = {}
            self.env_streams[net_hash][stream.get_props().get_name()] = stream
            self.env_streams_by_user_hash[user_hash] = stream
            if stream.is_public():
                self.__env_streams_by_user_hash_pub[user_hash] = stream
            else:
                self.__env_streams_by_user_hash_prv[user_hash] = stream
    else:

        # If a stream is not owned (i.e., it is from somebody else), the delta property >= 0 must be cleared,
        # since it is expected to limit the speed to the "set" operation on the owner-side. If we keep it here too
        # then it will also limit the speed of our "set" operation, that in principle is fine (we are getting
        # data at the speed the owner is setting it): however, a small network latency might end-up in making us
        # discard a sample that was sent with the right timing.
        if stream.props.delta >= 0.:
            stream.props.delta = -1.  # Forcing

    # If needed, merging descriptor labels (attribute labels) and sharing them with all streams
    if self.merge_flat_stream_labels:
        self.merge_flat_data_stream_props()

    return self.known_streams[net_hash]

Adds a stream to the known streams and returns the dict (name to Stream) of its group.

Argument Type Default Meaning
stream Stream required The stream.
owned bool True True for a stream of this agent.
net_hash str or None None The net hash of the group. None builds it from the public or the private peer id of the agent, depending on the publicity of the stream.

An owned stream is classified as processor output, processor input or environmental stream by its name and group. The agent clears the delta (the minimum interval between samples) of a stream of another agent. The pace belongs to the owner and a local delta would drop samples that arrive late. A stream added again under the same net hash replaces the old one. Adding a public stream to a private group or a direct stream to a broadcast group logs an error and returns {}. A user hash already used by another net hash raises GenException. With merge_flat_stream_labels the labels are merged again.

from unaiverse.streams.streams import BufferedStream

self.add_stream(BufferedStream(props=props), owned=True)
self.update_streams_in_profile()
await self.send_profile_to_all()

add_streams

add_streams(streams: list[Stream], owned: bool = True, net_hash: str | None = None) -> list[dict[str, Stream]]
Source code in unaiverse/agent_basics.py
def add_streams(self, streams: list[Stream], owned: bool = True, net_hash: str | None = None) \
        -> list[dict[str, Stream]]:
    """Add a list of new streams to this environment.

    Args:
        streams: A list of Stream objects to add.
        owned: If True, the streams are considered owned by this agent.
        net_hash: Optional network hash for the streams. If None, it will be generated for each.

    Returns:
        A list of dictionaries (it could be empty in case of issues), where each dictionary is what
        is returned by add_stream().
    """

    # Adding the new stream
    ret = []
    for stream in streams:
        stream_dict = self.add_stream(stream, owned, net_hash)
        if len(stream_dict) == 0:
            return []
        ret.append(stream_dict)
    return ret

Calls add_stream on each stream of the list and returns the list of the results. It stops at the first failure and returns []. The streams added before the failure stay.

remove_streams async

remove_streams(peer_id: str, name: str | None = None, owned_too: bool = False) -> None
Source code in unaiverse/agent_basics.py
async def remove_streams(self, peer_id: str, name: str | None = None, owned_too: bool = False) -> None:
    """Remove a known stream (async).

    Args:
        peer_id: The hash of each stream included the peer ID of the owner, so this is the peer ID associated with
            the stream(s) to remove.
        name: The optional name of the stream to remove. If None, all streams with this peer_id are removed.
        owned_too: If True, also removes streams from the owned stream dict (so also environmental and processor).
    """

    # Identifying what to remove
    to_remove = []
    for net_hash in self.known_streams.keys():
        if DataProps.peer_id_from_net_hash(net_hash) == peer_id:
            for _name, _stream in self.known_streams[net_hash].items():
                if name is None or name == _name:
                    to_remove.append((net_hash, _name))

    # Removing
    for (net_hash, name) in to_remove:
        if not owned_too and net_hash in self.owned_streams:
            continue

        group = DataProps.name_or_group_from_net_hash(net_hash)
        user_hash = DataProps.user_hash_from_net_hash(net_hash, name if name is not None else group)

        del self.known_streams[net_hash][name]
        if len(self.known_streams[net_hash]) == 0:
            del self.known_streams[net_hash]
        if user_hash in self.known_streams_by_user_hash:
            del self.known_streams_by_user_hash[user_hash]

        # Unsubscribing to pubsub
        if DataProps.is_pubsub_from_net_hash(net_hash):
            if peer_id != "<private_peer_id>" and peer_id != "<public_peer_id>":
                if not (await self.node_conn.unsubscribe(peer_id, channel=net_hash)):

                    # log.error(f"Failed in unsubscribing from pubsub, peer_id: {peer_id}, channel: {net_hash}")
                    pass
                else:
                    log.misc(f"Successfully unsubscribed from pubsub, peer_id: {peer_id}, channel: {net_hash}")

        # Removing all the owned streams (environment and processor streams are of course "owned")
        if net_hash in self.owned_streams:
            if name in self.owned_streams[net_hash]:
                del self.owned_streams[net_hash][name]
                if len(self.owned_streams[net_hash]) == 0:
                    del self.owned_streams[net_hash]
        if user_hash in self.owned_streams_by_user_hash:
            del self.owned_streams_by_user_hash[user_hash]
        if net_hash in self.env_streams:
            if name in self.env_streams[net_hash]:
                del self.env_streams[net_hash][name]
                if len(self.env_streams[net_hash]) == 0:
                    del self.env_streams[net_hash]
        if user_hash in self.env_streams_by_user_hash:
            del self.env_streams_by_user_hash[user_hash]
        if net_hash in self.proc_streams:
            if name in self.proc_streams[net_hash]:
                del self.proc_streams[net_hash][name]
                if len(self.proc_streams[net_hash]) == 0:
                    del self.proc_streams[net_hash]
        if user_hash in self.proc_streams_by_user_hash:
            del self.proc_streams_by_user_hash[user_hash]
        log.misc(f"Successfully removed known stream with network hash {net_hash}, stream name: {name}")

Removes the known streams of the peer peer_id (async). It returns None.

Argument Type Default Meaning
peer_id str required The owner of the streams.
name str or None None Only the stream with this name. None removes them all.
owned_too bool False Also remove streams that this agent owns.

It unsubscribes from the broadcast groups it removes and deletes the streams from the owned, environmental and processor output indexes.

remove_all_streams

remove_all_streams(owned_too: bool = False) -> None
Source code in unaiverse/agent_basics.py
def remove_all_streams(self, owned_too: bool = False) -> None:
    """Remove all not-owned streams.

    Args:
        owned_too: If True, also removes the owned streams of this agent (so also environmental and processor ones).
    """
    if not owned_too:
        self.known_streams = {k: v for k, v in self.owned_streams.items()}
        self.known_streams_by_user_hash = {k: v for k, v in self.owned_streams_by_user_hash.items()}
    else:
        self.known_streams = {}
        self.owned_streams = {}
        self.env_streams = {}
        self.proc_streams = {}
        self.proc_in_streams = {}
        self.known_streams_by_user_hash = {}
        self.owned_streams_by_user_hash = {}
        self.env_streams_by_user_hash = {}
        self.proc_streams_by_user_hash = {}
        self.proc_in_streams_by_user_hash = {}
    log.misc(f"Successfully removed all streams!")

Keeps only the owned streams. With owned_too=True it empties every index of streams. No channel is closed.

get_stream

get_stream(name_or_group: str, peer_id: str | None = None, data_type: str | None = None) -> Stream | None
Source code in unaiverse/agent_basics.py
def get_stream(self, name_or_group: str, peer_id: str | None = None, data_type: str | None = None) -> Stream | None:
    """Gets a known stream of a peer by name (or group).

    Args:
        name_or_group: The name or the group of the stream.
        peer_id: The owner of the stream (default: None, meaning this agent).
        data_type: The data type to look for, when a group has streams of several types (default: None).

    Returns:
        The stream, or None when not found.
    """
    if peer_id is None:
        peer_id = self.get_peer_id()
    user_hash = DataProps.build_user_hash(peer_id, name_or_group)
    if user_hash in self.known_streams_by_user_hash:
        return self.known_streams_by_user_hash[user_hash]
    else:
        streams = self.get_streams(group_name=name_or_group, peer_id=peer_id)
        if streams is not None and len(streams) > 0:
            if data_type is not None:
                for stream in streams:
                    assert stream.props is not None
                    if stream.props.data_type == data_type:
                        return stream
                return None
            elif len(streams) == 1:
                return streams[0]
            else:
                return None  # Ambiguous case
        else:
            return None

Returns one known stream or None.

Argument Type Default Meaning
name_or_group str required A stream name (tried first) or a group name.
peer_id str or None None The owner. None means this agent under the peer id of the network where it behaves.
data_type str or None None With a group, the data type of the stream to return ("text", "img", "tensor", "file").

A group with a single stream returns it. A group with several streams returns None unless data_type selects one.

camera = self.get_stream("camera")                       # my own stream
answer = self.get_stream("processor", peer_id=peer, data_type="text")

get_streams

get_streams(group_name: str, peer_id: str | None = None) -> list[Stream] | None
Source code in unaiverse/agent_basics.py
def get_streams(self, group_name: str, peer_id: str | None = None) -> list[Stream] | None:
    """Gets the known streams of a group of a peer.

    Args:
        group_name: The name of the group.
        peer_id: The owner of the streams (default: None, meaning this agent).

    Returns:
        The list of the streams, or None when not found.
    """
    if peer_id is None:
        peer_id = self.get_peer_id()
    net_hash_ps = DataProps.build_net_hash(peer_id, pubsub=True, name_or_group=group_name)
    if net_hash_ps in self.known_streams:
        return list(self.known_streams[net_hash_ps].values())
    else:
        net_hash_dm = DataProps.build_net_hash(peer_id, pubsub=False, name_or_group=group_name)
        if net_hash_dm in self.known_streams:
            return list(self.known_streams[net_hash_dm].values())
        else:
            return None

Returns the list of the streams of the group group_name of peer_id (this agent when None). The method tries the broadcast group first and then the direct one. It returns None when neither exists.

find_streams

find_streams(peer_id: str, name_or_group: str | None = None, discard_owned: bool = False) -> dict[str, dict[str, Stream]]
Source code in unaiverse/agent_basics.py
def find_streams(self, peer_id: str, name_or_group: str | None = None, discard_owned: bool = False) \
        -> dict[str, dict[str, Stream]]:
    """Find streams associated with a given peer ID and optionally by name or group.

    Args:
        peer_id: The peer ID of the (owner of the) streams to find.
        name_or_group: Optional name or group of the streams to find.
        discard_owned: If True, the owned streams are not searched (default False).

    Returns:
        A dictionary where keys are network hashes and values are dictionaries of streams
        (stream name to Stream object) matching the criteria.
    """
    ret = {}
    for net_hash, streams_dict in self.known_streams.items():
        if discard_owned and net_hash in self.owned_streams:
            continue
        _peer_id = Stream.peer_id_from_net_hash(net_hash)
        _name_or_group = Stream.name_or_group_from_net_hash(net_hash)
        if peer_id == _peer_id:
            if name_or_group is None or name_or_group == _name_or_group:
                ret[net_hash] = streams_dict
            else:
                for _name, _stream in streams_dict.items():
                    if name_or_group == _name:
                        if net_hash not in ret:
                            ret[net_hash] = {}
                        ret[net_hash][name_or_group] = _stream
    return ret

Returns the known streams of peer_id as a dict from net hash to a dict from name to Stream.

Argument Type Default Meaning
peer_id str required The owner.
name_or_group str or None None A group (all its streams) or a stream name (that stream alone). None returns every stream of the peer.
discard_owned bool False Skip the groups that this agent owns.

A requester reads the answer to a request from the processor streams of the target:

for streams in self.find_streams(peer_id, "processor").values():
    for stream in streams.values():
        sample = stream.get(uuid=interaction.uuid)

get_last_streamed_data

get_last_streamed_data(agent_name: str) -> list
Source code in unaiverse/agent_basics.py
def get_last_streamed_data(self, agent_name: str) -> list:
    """Get the last data samples from the processor streams of a given agent.

    Args:
        agent_name: The name of the agent.

    Returns:
        A list of data samples taken from all the known streams associated to the provided agent.
    """
    data_list = []
    for peer_id, profile in self.all_agents.items():
        if profile.get_static_profile()['node_name'] == agent_name:
            net_hash_to_stream_dict = self.find_streams(peer_id, name_or_group="processor")
            for net_hash, streams_dict in net_hash_to_stream_dict.items():
                for stream_name, stream_obj in streams_dict.items():
                    data_list.append(stream_obj.get())
    return data_list

Returns the latest sample of every processor stream of the known agents whose node name is agent_name. The method predates the streams per interaction. It compares only the node name (two accounts can use the same name) and reads the latest sample whatever its interaction. To read the answer to a request, read the processor stream under the uuid of the interaction (see find_streams) or use Agent.on_received.

resolve_stream_ref

resolve_stream_ref(ref: str, public: bool) -> str | None
Source code in unaiverse/agent_basics.py
def resolve_stream_ref(self, ref: str, public: bool) -> str | None:
    """Resolve a stream name to a stream user or net hash (heuristic, gives priority to owned streams).

    Args:
        ref: A stream name, without peer IDs, just the name.
        public: A boolean to inform the resolve procedure whether it must look for streams among public agents
            (True) or world-related agents (False).

    Returns:
        The stream user hash or net hash if found, None otherwise.
    """

    # If already a valid user hash
    if ref in self.known_streams_by_user_hash:
        return ref

    # If already a valid net hash
    if ref in self.known_streams:
        return ref

    # If it is formatted as a net hash, but was not found, then nothing to do
    if Stream.is_net_hash(ref):
        return None

    # By default, we will try to resolve by looking at owned (first) and other (then) streams
    search_owned_streams = True
    search_other_streams = True
    owner = None

    # If it looks like a user hash but was not found in the code above, then it could be a stream group
    # represented as a user hash, so we clear it, and we keep the group name only. Moreover, since it will also
    # contain a peer ID, we immediately know where to look
    if Stream.is_user_hash(ref):
        peer_id = DataProps.peer_id_from_user_hash(ref)
        ref = DataProps.name_from_user_hash(ref)
        search_owned_streams = peer_id == self.get_peer_id()
        search_other_streams = not search_owned_streams
        owner = peer_id  # Only the streams of this peer: another peer's stream with the same name is not it

    # Search your own streams first (priority)
    if search_owned_streams:
        for user_hash, stream_obj in self.owned_streams_by_user_hash.items():
            if public and not stream_obj.is_public():
                continue
            if ref == Stream.name_from_user_hash(user_hash):
                return user_hash
        for net_hash, stream_dict in self.owned_streams.items():
            if len(stream_dict) == 0:
                continue
            if public and not next(iter(stream_dict.values())).is_public():
                continue
            if ref == Stream.name_or_group_from_net_hash(net_hash):
                return net_hash

    # Search all streams then
    if search_other_streams:
        for user_hash, stream_obj in self.known_streams_by_user_hash.items():
            if public and not stream_obj.is_public():
                continue
            if owner is not None and DataProps.peer_id_from_user_hash(user_hash) != owner:
                continue
            if ref == Stream.name_from_user_hash(user_hash):
                return user_hash
        for net_hash, stream_dict in self.known_streams.items():
            if len(stream_dict) == 0:
                continue
            if public and not next(iter(stream_dict.values())).is_public():
                continue
            if owner is not None and DataProps.peer_id_from_net_hash(net_hash) != owner:
                continue
            if ref == Stream.name_or_group_from_net_hash(net_hash):
                return net_hash

    return None

Turns a reference to a stream into a user hash or a net hash. The @action decorator applies it to the arguments stream and streams and the interaction manager applies it to the streams of an interaction.

Argument Type Meaning
ref str A user hash, a net hash, a stream name or a group name.
public bool True to consider only public streams.

A known user hash or net hash comes back as it is. An unknown net hash gives None. A user hash that is not known is read as <peer_id>:<name or group> and searched among the streams of that peer only. A bare name is searched first among the owned streams (stream names, then group names) and then among all the known streams. It returns the first match or None. Agent.resolve_stream_ref adds the reference <playlist>.

user_stream_hash_to_net_hash

user_stream_hash_to_net_hash(user_stream_hash: str) -> str | None
Source code in unaiverse/agent_basics.py
def user_stream_hash_to_net_hash(self, user_stream_hash: str) -> str | None:
    """Converts a user-defined stream hash (peer_id:name_or_group) to a network hash
    (peer_id::dm:... or peer_id::ps:name_or_group) by searching the known hashes in the known streams.

    Args:
        user_stream_hash: The user-defined stream hash string (peer_id:name).

    Returns:
        The corresponding network hash string (peer_id::dm:... or peer_id::ps:name_or_group), or None if not found.
    """
    if user_stream_hash is None:
        return None
    if "::" in user_stream_hash:
        return user_stream_hash  # It was already fine
    components = user_stream_hash.split(":")
    peer_id = components[0]
    name = components[-1]
    for net_hash, stream_dict in self.known_streams.items():
        _peer_id = Stream.peer_id_from_net_hash(net_hash)
        _name_or_group = Stream.name_or_group_from_net_hash(net_hash)
        if _peer_id == peer_id and _name_or_group == name:
            return net_hash
        for _name in stream_dict.keys():
            if _peer_id == peer_id and _name == name:
                return net_hash
    return None

Converts <peer_id>:<name or group> into the net hash of the known group that has that group name or contains a stream with that name. A string that contains :: is already a net hash and comes back as it is. It returns None when the argument is None or nothing matches.

add_compatible_streams async

add_compatible_streams(peer_id: str, streams_in_profile: list[dict], buffered: bool = False, add_all: bool = False, public: bool = True, skip_pubsub: bool = False) -> bool
Source code in unaiverse/agent_basics.py
async def add_compatible_streams(self, peer_id: str,
                                 streams_in_profile: list[dict], buffered: bool = False,
                                 add_all: bool = False, public: bool = True, skip_pubsub: bool = False) -> bool:
    """Add to the list of processor-compatible-streams those streams provided as arguments that are actually
    found to be compatible with the processor (if they are pubsub, it also subscribes to them) (async).

    Args:
        peer_id: The peer ID of the agent providing the streams.
        streams_in_profile: A list of dictionaries (DataProps to dict) representing the streams in peer's profile.
        buffered: If True, the added streams will be of type BufferedStream.
        add_all: If True, all streams from the profile are added, regardless of processor compatibility.
        public: Consider public streams only (or private streams only).
        skip_pubsub: Skip pubsub streams.

    Returns:
        True if compatible streams were successfully added and subscribed to, False otherwise.
    """
    added_streams = []

    if add_all:

        # This is the case in which we add all streams, storing all pairs (DataProps, net_hash)
        for j in streams_in_profile:
            jj = DataProps.from_dict(j)
            if (public == jj.is_public()
                    and (not jj.is_pubsub() or not skip_pubsub)):
                net_hash = jj.net_hash(peer_id)
                added_streams.append((jj, net_hash))
    else:

        # This is the case in which a processor is present, hence storing pairs (DataProps, net_hash)
        # of the found compatible streams
        added_net_hash_to_prop_name = {}

        # Find streams that are compatible with our 'proc_inputs'
        assert self.proc_inputs is not None
        for i, in_proc in enumerate(self.proc_inputs):
            assert not isinstance(in_proc, str)
            for j in streams_in_profile:
                jj = DataProps.from_dict(j)
                if (public == jj.is_public() and in_proc.is_compatible(jj)
                        and (not jj.is_pubsub() or not skip_pubsub)):
                    net_hash = jj.net_hash(peer_id)

                    if net_hash not in added_net_hash_to_prop_name:
                        added_net_hash_to_prop_name[net_hash] = set()
                    if jj.name not in added_net_hash_to_prop_name[net_hash]:
                        added_net_hash_to_prop_name[net_hash].add(jj.name)
                        added_streams.append((jj, net_hash))

                    # Saving the position in the proc_input list
                    self.compat_in_streams[i].add((net_hash, jj.get_name()))

        # Find streams that are compatible with our 'proc_outputs'
        has_cross_entropy = []
        assert self.proc_outputs is not None
        assert self.proc_opts is not None
        if 'losses' in self.proc_opts:
            for i in range(0, len(self.proc_outputs)):
                if self.proc_opts['losses'][i] is not None and \
                        (self.proc_opts['losses'][i] == torch.nn.functional.cross_entropy or
                         isinstance(self.proc_opts['losses'][i], torch.nn.CrossEntropyLoss) or
                         "cross_entropy" in self.proc_opts['losses'][i].__name__):
                    has_cross_entropy.append(True)
                else:
                    has_cross_entropy.append(False)

        for i, out_proc in enumerate(self.proc_outputs):
            out_proc: StreamType
            for j in streams_in_profile:
                jj = DataProps.from_dict(j)
                if ((public == jj.is_public() and
                        (out_proc.is_compatible(jj) or (jj.is_tensor_target_id() and has_cross_entropy[i])))
                        and (not jj.is_pubsub() or not skip_pubsub)):
                    net_hash = jj.net_hash(peer_id)

                    if net_hash not in added_net_hash_to_prop_name:
                        added_net_hash_to_prop_name[net_hash] = set()
                    if jj.name not in added_net_hash_to_prop_name[net_hash]:
                        added_net_hash_to_prop_name[net_hash].add(jj.name)
                        added_streams.append((jj, net_hash))

                    # Saving the position in the proc_output list
                    self.compat_out_streams[i].add((net_hash, jj.get_name()))

    net_hashes_to_subscribe = set()

    # For each compatible stream found...
    for (props, net_hash) in added_streams:

        # Check if it is a new stream or a data stream to add to an already known stream
        already_known_stream = net_hash in self.known_streams

        # A stream already known with the same properties and of the same kind is kept: a new object would detach
        # the interactions registered on the old one, which would then never see the samples arriving on the new
        # one (an interaction naming the stream, registered just before a subscribe that adds the stream again);
        # the delta is not compared, since it is cleared on the streams of the others (see add_stream)
        known = self.known_streams.get(net_hash, {}).get(props.get_name())
        if known is not None and isinstance(known, BufferedStream) == buffered:
            known_props, new_props = known.get_props().to_dict(), props.to_dict()
            known_props.pop('delta')
            new_props.pop('delta')
            if known_props == new_props:
                continue

        # Creating the stream object
        if not buffered:
            stream = Stream(props=props.clone())
        else:
            stream = BufferedStream(props=props.clone())

        # Add the data stream to the list of known streams
        # if the stream already exists it will be overwritten (which is fine in case of changes)
        self.add_stream(stream, owned=False, net_hash=net_hash)

        # If the stream is over PubSub, and we are not already subscribed, we will subscribe
        if props.is_pubsub() and not already_known_stream:
            net_hashes_to_subscribe.add(net_hash)

    # Opening PubSubs
    for net_hash in net_hashes_to_subscribe:
        log.misc(f"Opening channel for the not-owned but processor-compatible stream {net_hash}")
        if not (await self.node_conn.subscribe(peer_id, channel=net_hash)):
            log.error(f"Error subscribing to {net_hash}")
            return False

    return True

Adds the streams of a peer that fit this processor (async). add_agent calls it with the stream lists of the profile of the peer.

Argument Type Default Meaning
peer_id str required The owner of the streams.
streams_in_profile list[dict] required Stream properties as dictionaries.
buffered bool False Create BufferedStream objects.
add_all bool False Add every stream, compatible or not.
public bool True Consider only public streams (True) or only private ones.
skip_pubsub bool False Ignore broadcast streams.

A stream is compatible with an input when its properties match that input. It is compatible with an output when they match that output. A stream of class indices is also compatible with an output whose loss is a cross-entropy. Each compatible stream enters compat_in_streams or compat_out_streams. A stream already known with the same properties keeps its object. The interactions already attached to it thus keep receiving samples. The method subscribes to every new broadcast group. It returns False when a subscription fails and True otherwise.

merge_flat_data_stream_props

merge_flat_data_stream_props() -> None
Source code in unaiverse/agent_basics.py
def merge_flat_data_stream_props(self) -> None:
    """Merge the labels of the descriptor components, across all streams, sharing them."""

    # Set of pivot labels
    superset_labels = []

    # Checking the whole list of streams, but considering only the ones with generic data, flat, and labels
    considered_streams = []

    for stream_dict in self.owned_streams.values():
        for stream in stream_dict.values():

            # Skipping not flat, or not generic, or unlabeled streams
            if not stream.props.is_flat_tensor_with_labels():
                continue

            # Saving list of considered streams
            considered_streams.append(stream)

            # Adding the current stream-labels to the pivot labels
            for label in stream.props.tensor_labels:
                if label not in superset_labels:
                    superset_labels.append(label)

    # Telling each stream in which positions their labels fall, given the pivot labels
    for stream in considered_streams:

        # In the case of BufferedStream, we have to update the data buffer by clearing previously applied
        # adaptation first (I know it looks similar to what is done below, but we must clear first!)
        if isinstance(stream, BufferedStream):
            assert stream.props is not None
            for uuid in stream.data_buffer_by_uuid.keys():
                for data in stream.data_buffer_by_uuid[uuid]:
                    data.data = stream.props.clear_label_adaptation(data.data)

        # Updating labels
        assert stream.props is not None and isinstance(stream.props.tensor_labels, TensorLabels)
        stream.props.tensor_labels.interleave_with(superset_labels)

        # In the case of BufferedStream, we have to update the data buffer with the new labels
        if isinstance(stream, BufferedStream):
            assert stream.props is not None

            for uuid in stream.data_buffer_by_uuid.keys():
                for data in stream.data_buffer_by_uuid[uuid]:
                    data.data = stream.props.adapt_tensor_to_tensor_labels(data.data)

Builds the union of the labels of all the owned flat tensor streams with labels and makes each of those streams place its components in that common space. The samples already in a BufferedStream are adapted to the new layout. add_stream calls it when merge_flat_stream_labels is True.

get_stream_sample

get_stream_sample(net_hash: str, sample_dict: dict[str, dict[str, Tensor | None | int | str]]) -> list[tuple[str, str]]
Source code in unaiverse/agent_basics.py
def get_stream_sample(self, net_hash: str,
                      sample_dict: dict[str, dict[str, torch.Tensor | None | int | str]]) \
        -> list[tuple[str, str]]:
    """Receive and process stream samples that were provided by another agent.

    Args:
        net_hash: The network hash identifying the source of the stream samples.
        sample_dict: A dictionary where keys are stream names and values are dictionaries
                     containing 'data', 'data_tag', and 'data_uuid' for each sample.

    Returns:
        The list of tuples (stream user hash, data UUID) for each added data sample.
    """

    # Let's be sure that the net hash is converted from the user's perspective to the one of the code here
    net_hash = DataProps.normalize_net_hash(net_hash)
    added_data = []

    log.misc(f"Got a stream sample from {net_hash}...")
    if sample_dict is None:
        log.error(f"Invalid sample (expected a dictionary, got None)")
        return added_data

    if net_hash in self.known_streams:
        for name, data_and_tag_and_uuid in sample_dict.items():
            if ('data' not in data_and_tag_and_uuid or
                    'data_tag' not in data_and_tag_and_uuid or
                    'data_uuid' not in data_and_tag_and_uuid):
                log.error(f"Invalid sample in data stream named {name} (missing one or more keys)")
                continue

            data, data_tag, data_uuid = (data_and_tag_and_uuid['data'],
                                         data_and_tag_and_uuid['data_tag'],
                                         data_and_tag_and_uuid['data_uuid'])

            # - data must be not None
            # - the stream name must be known
            # - if the UUID associated to our local stream is the same of the data, then we check tag order
            # - if the UUID associated to our local stream is the expected one, we don't check tag order
            skip = False
            reason = None
            has_data = False
            if not skip:
                if data is None:
                    skip = True
                    reason = "Data is None"
            if not skip:
                if net_hash not in self.known_streams:
                    skip = True
                    reason = f"The net hash {net_hash} is not a known stream hash"
            if not skip:
                if name not in self.known_streams[net_hash]:
                    skip = True
                    reason = (f"The data stream named {name} is not present for net hash {net_hash} "
                              f"(names: {list(self.known_streams[net_hash].keys())})")
            if not skip:
                has_data = self.known_streams[net_hash][name].has_data(data_uuid)
                has_this_data_tag = self.known_streams[net_hash][name].get_tag(data_uuid)
                if has_data:
                    assert data_tag is not None
                    assert has_this_data_tag is not None
                    if data_tag <= has_this_data_tag:
                        skip = True
                        reason = (f"The data tag {data_tag} is less or equal to the already present one "
                                  f"for UUID {data_uuid} "
                                  f"({self.known_streams[net_hash][name].get_tag(data_uuid)})")

            # If we sample can be accepted...
            if not skip:
                log.misc(f"Accepted sample named {name}: tag={data_tag}, uuid={data_uuid}" +
                         (": it is a new UUID" if not has_data else ""))

                # Saving the data sample on the known stream objects (its owner already paced it: no delta check)
                self.known_streams[net_hash][name].set(data, data_tag, uuid=data_uuid, check_delta=False)

                # Data to return
                added_data.append((DataProps.user_hash_from_net_hash(net_hash, name), data_uuid))

                # A form somebody sent us is remembered here, because this is the only point every
                # message goes through: what a person is shown never reaches their processor, and their
                # answer would otherwise have nothing to be matched against
                if isinstance(data, str) and has_fence(data):
                    self.uai_remember_form(DataProps.peer_id_from_net_hash(net_hash), data)

                # Buffering data, if it was requested and if this sample comes from somebody's processor
                if (self.buffer_generated_by_others != "none" and
                        DataProps.name_or_group_from_net_hash(net_hash) == "processor"):
                    log.debug(f"[get_stream_sample] Buffering others' processor generated data...")

                    # Getting the streams of the processor of the source agent
                    _processor_stream_dict = self.known_streams[net_hash]
                    _peer_id = DataProps.peer_id_from_net_hash(net_hash)

                    # Setting buffered stream counter
                    clear = False
                    if _peer_id in self.last_buffered_peer_id_to_info:
                        if self.buffer_generated_by_others == "one":
                            _buffered_uuid_to_id = self.last_buffered_peer_id_to_info[_peer_id]["uuid_to_id"]
                            if data_uuid not in _buffered_uuid_to_id:
                                _id = next(iter(_buffered_uuid_to_id.values()))
                                _buffered_uuid_to_id.clear()
                                _buffered_uuid_to_id[data_uuid] = _id
                                clear = True
                    else:
                        self.last_buffered_peer_id_to_info[_peer_id] = {"uuid_to_id": {}, "net_hash": None}
                    _buffered_uuid_to_id = self.last_buffered_peer_id_to_info[_peer_id]["uuid_to_id"]
                    if data_uuid not in _buffered_uuid_to_id:
                        self.last_buffered_id_counter += 1
                        _buffered_uuid_to_id[data_uuid] = self.last_buffered_id_counter
                    _buffered_id = _buffered_uuid_to_id[data_uuid]

                    # Building net hash to retrieve the buffered stream
                    _group = "buffered" + str(_buffered_id)
                    _name = name + "@" + _group
                    _net_hash = DataProps.build_net_hash(
                        _peer_id,
                        pubsub=False,
                        name_or_group=_group)

                    # If the buffered stream was not created before
                    if _net_hash not in self.known_streams:
                        log.debug(f"[get_stream_sample] Adding a new buffered stream to the list of known "
                                  f"streams, hash: {_net_hash}")
                        for stream_obj in _processor_stream_dict.values():

                            # Same properties of the stream of the processor of the source agent
                            props = stream_obj.get_props().clone()
                            props.set_group("buffered" + str(_buffered_id))
                            props.set_name(props.get_name() + "@" + props.get_group())

                            # Adding the newly created stream
                            self.add_stream(BufferedStream(props=props),
                                            owned=False,
                                            net_hash=_net_hash)

                        # Saving hash of the new buffered stream
                        self.last_buffered_peer_id_to_info[_peer_id]["net_hash"] = _net_hash
                    else:
                        if clear:
                            for stream_obj in self.known_streams[_net_hash].values():
                                stream_obj.clear_buffer()

                    # Saving sample
                    self.known_streams[_net_hash][_name].set(data, data_tag, uuid=data_uuid)
                    if self.known_streams[_net_hash][_name].get_interaction(data_uuid) is None:
                        interaction = self.known_streams[net_hash][name].get_interaction(data_uuid)
                        if interaction is not None:
                            self.im.add_lazy_stream_to_interaction(
                                DataProps.user_hash_from_net_hash(_net_hash, _name), interaction)

            # If we decided to skip this sample...
            else:
                log.misc(f"Skipping sample named {name} received in net hash {net_hash}, "
                         f"tag={data_tag}, uuid={data_uuid}: {reason}")

                if net_hash not in self.known_streams:
                    log.debug(f"[get_stream_sample] "
                              f"The net hash {net_hash} was not found in the set of known streams")
                else:
                    if name not in self.known_streams[net_hash]:
                        log.debug(f"[get_stream_sample] The net hash was known, but the data stream "
                                  f"named {name} is not known")
                    else:
                        log.debug(f"[get_stream_sample] "
                                  f"data={self.known_streams[net_hash][name].props.to_text(data)}")
        return added_data

    # If this stream is not known at all...
    else:
        log.misc(f"Skipping sample from {net_hash} (data stream is unknown)")  # Misc
        return added_data

Stores the samples that a peer sent on the group net_hash. The node calls it for every incoming stream message.

Argument Type Meaning
net_hash str The group of the sender. It is normalized first.
sample_dict dict Stream name to {"data": ..., "data_tag": int, "data_uuid": str or None}.

A sample is skipped in three cases: (1) its data is None, (2) its group or stream is unknown and (3) its tag is not greater than the tag already stored under the same uuid. An accepted sample is written on the stream under its uuid with no pace check. A text sample that carries an interactive block is remembered as a form of the sender (see uai_remember_form). With buffer_generated_by_others other than "none" a sample of a processor stream is also copied into the buffered group buffered<n> of the sender. The method returns the list of (user_hash, data_uuid) of the accepted samples.

send_stream_samples async

send_stream_samples() -> None
Source code in unaiverse/agent_basics.py
async def send_stream_samples(self) -> None:
    """Collect and send stream samples from all owned streams to appropriate recipients (async)."""

    # For each owned net hash...
    for net_hash, streams_dict in list(self.owned_streams.items()):  # A copy: the loop awaits

        # Skipping our processor input
        if DataProps.name_or_group_from_net_hash(net_hash) == "processor_in":
            continue

        # Get samples from all the owned streams: taking notes about the recipient and of what to send (contents)
        interactions_by_uuid = {}
        recipients_by_uuid = {}
        contents_by_uuid = {}
        contents_data_by_uuid = {}

        # Preparing content to send
        valid_samples_count = {}

        # For each stream within this net hash...
        for name, stream in streams_dict.items():
            uuids = stream.get_interaction_uuids()  # We send direct messages only if there is an interaction

            # We do not consider UUID not-paired with interaction in the case of BufferedStream's
            if stream.is_pubsub() and not isinstance(stream, BufferedStream):
                uuids = list(uuids) + [u for u in stream.get_data_uuids() if u is not None and u not in uuids]

            # Set None as last UUID (it is present in pre-built BufferedStreams)
            # since it is sometimes replaced by the last set reference,
            # and we prefer to give priority to the not-None cases
            if stream.is_pubsub() and stream.has_data(None):
                uuids = list(uuids) + [None]  # We send by PubSub whenever there is some data with None UUID

            # For each agent who triggered the interaction that generated this data (recipient)
            for uuid in uuids:
                interaction = stream.get_interaction(uuid)
                recipient = None

                # Invalid agent? Skip!
                if not stream.is_pubsub():
                    assert interaction is not None
                    recipient = self.im.get_recipients(interaction)
                    if len(recipient) == 0:
                        continue

                # Skipping system-triggered interactions
                if recipient == [Custom.SYSTEM_INTERACTION_LABEL]:
                    continue

                # Skipping interactions that already provided all the required data
                if interaction is not None:
                    if interaction.all_samples_streamed():
                        continue

                # Get data
                data = stream.get(requested_by="send_stream_samples", uuid=uuid)
                data_tag = stream.get_tag(uuid=uuid)

                assert stream.props is not None
                log.debug(f"[send_stream_sample] data from stream {stream.props.get_name()} = {data}")

                if data is not None:
                    count_recipients = len(recipient) if recipient is not None else 1

                    # Force the lazy decode now to avoid race condition afterward (PIL loads only when needed)
                    if isinstance(data, Image):
                        data.load()  # Forcing load here, for safety

                    log.debug(f"[send_stream_samples] Found something in stream {stream.props.get_name()} "
                              f"uuid={uuid}, data_tag={data_tag}, recipient={recipient}")

                    # Prepare data structures the first time we meet a new recipient
                    if uuid not in contents_by_uuid:
                        interactions_by_uuid[uuid] = interaction
                        recipients_by_uuid[uuid] = recipient
                        contents_by_uuid[uuid] = [{name: {'data': None, 'data_tag': None, 'data_uuid': None}
                                                   for name in streams_dict.keys()}
                                                  for _ in range(0, count_recipients)]
                        contents_data_by_uuid[uuid] = {name: None for name in streams_dict.keys()}
                        valid_samples_count[uuid] = 0

                    # Pack into the prepared data structures
                    for i in range(0, count_recipients):
                        contents_by_uuid[uuid][i][name] = {'data': data,
                                                           'data_tag': data_tag,
                                                           'data_uuid': uuid}
                    contents_data_by_uuid[uuid][name] = data
                    valid_samples_count[uuid] += 1
                else:
                    log.debug(f"[send_stream_samples] None data in stream {stream.props.get_name()} uuid={uuid}")

        # Remove recipients of not-net-hash-full-of-contents messages
        uuid_to_remove = []
        for uuid, count in valid_samples_count.items():
            if count == 0:
                uuid_to_remove.append(uuid)
                log.debug(f"[send_stream_samples] Cannot send data for {net_hash}, uuid {uuid}, "
                          f"since it is incomplete ({valid_samples_count[uuid]} vs {len(streams_dict)})")
        for uuid in uuid_to_remove:
            del interactions_by_uuid[uuid]
            del recipients_by_uuid[uuid]
            del contents_by_uuid[uuid]
            del contents_data_by_uuid[uuid]
            del valid_samples_count[uuid]

        # If direct message...
        if not Stream.is_pubsub_from_net_hash(net_hash):
            name_or_group = DataProps.name_or_group_from_net_hash(net_hash)

            for uuid, recipients in recipients_by_uuid.items():
                contents = contents_by_uuid[uuid]
                content_data = contents_data_by_uuid[uuid]
                interaction = interactions_by_uuid[uuid]

                for i, recipient in enumerate(recipients):
                    log.debug(f"[send_stream_samples] " 
                              f"Sending samples of {net_hash} by direct message to {recipient}...")
                    content = contents[i]
                    for name in content.keys():
                        content[name]['data'] = self.hook_before_sending_sample(content_data[name],
                                                                                content[name]['data_tag'],
                                                                                net_hash, name, recipient)
                        log.debug(f"[send_stream_samples] "
                                  f"(data_tag={content[name]['data_tag']}, data_uuid={uuid}, "
                                  f"data is None?={content[name]['data'] is None})")

                # One send per recipient, concurrently (one failure does not cancel the others)
                results = await asyncio.gather(
                    *(self.node_conn.send(recipient, channel_trail=name_or_group,
                                          content_type=Msg.STREAM_SAMPLE, content=contents[i])
                      for i, recipient in enumerate(recipients)),
                    return_exceptions=True)

                # Checking result of sending
                for r in results:
                    if isinstance(r, Exception):
                        log.debug(f"[send_stream_samples] Sending failed: {r}")
                    else:
                        log.debug(f"[send_stream_samples] Sending success")

                # Increase sent-samples-count on the interaction object
                if interaction is not None:
                    if any(r is True for r in results):
                        interaction.inc_streamed_samples()

        # If pubsub...
        if Stream.is_pubsub_from_net_hash(net_hash):
            for uuid, recipients in recipients_by_uuid.items():
                log.debug(f"[send_stream_samples] Sending stream samples of the whole {net_hash} by pubsub...")

                content = contents_by_uuid[uuid][0]
                content_data = contents_data_by_uuid[uuid]
                interaction = interactions_by_uuid[uuid]

                for name in content.keys():
                    content[name]['data'] = self.hook_before_sending_sample(content_data[name],
                                                                            content[name]['data_tag'],
                                                                            net_hash, name, None)
                    log.debug(
                        f"[send_stream_samples] (data_tag={content[name]['data_tag']}, data_uuid={uuid}, "
                        f"data is None?={content[name]['data'] is None}")

                peer_id = Stream.peer_id_from_net_hash(net_hash)  # Guessing agent peer ID from the net hash
                result = await self.node_conn.publish(peer_id, channel=net_hash,
                                                      content_type=Msg.STREAM_SAMPLE,
                                                      content=content)
                log.debug(f"[send_stream_samples] PubSub sending returned " + str(result))

                if interaction is not None and result:
                    interaction.inc_streamed_samples()

Sends the samples of the owned streams to their recipients (async). The node calls it at every tick. The processor input group is skipped.

  1. For a direct group, the method sends the sample stored under the uuid of each interaction attached to the stream. The recipients are those given by InteractionManager.get_recipients. System interactions and interactions that already streamed num_samples_to_stream samples are skipped.
  2. A broadcast group also publishes the data stored under uuids without an interaction (the uuid None included).

Each sample passes through hook_before_sending_sample. Direct sends to several recipients run concurrently and a failure does not cancel the others. Each send that reaches at least one recipient increases the streamed count of the interaction.

streams_to_str

streams_to_str() -> str
Source code in unaiverse/agent_basics.py
def streams_to_str(self) -> str:
    """Return a formatted string listing all known streams, marking owned ones with an asterisk.

    Returns:
        A multi-line string representation of the known streams.
    """
    return "Streams:\n" + "\n".join([(("   @" if user_hash in self.owned_streams_by_user_hash else "   ") +
                                      DataProps.peer_id_from_user_hash(user_hash) + " => " +
                                      str(stream).replace("\n", "\n   "))
                                     for user_hash, stream in self.known_streams_by_user_hash.items()])

Returns a multi-line description of every known stream with one line per user hash and @ before the owned ones. The node prints it in the stream log.

Standard streams and the processor input

set_default_stdin_binding

set_default_stdin_binding(public: bool | None = None) -> None
Source code in unaiverse/agent_basics.py
def set_default_stdin_binding(self, public: bool | None = None) -> None:
    """Set default bindings for the stdin."""

    if (public is not None and not public) or (public is None and self.behaving_in_world()):
        self.stdin.bind(self.__proc_in_streams_by_user_hash_prv, uuid=Custom.SYSTEM_INTERACTION_UUID)

    if (public is not None and public) or (public is None and not self.behaving_in_world()):
        self.stdin.bind(self.__proc_in_streams_by_user_hash_pub, uuid=Custom.SYSTEM_INTERACTION_UUID)

Binds stdin to the processor input streams under the system uuid. public=True binds the public streams, public=False the private ones and None the streams of the network where the agent behaves.

set_default_stream_binding

set_default_stream_binding(public: bool | None = None) -> None
Source code in unaiverse/agent_basics.py
def set_default_stream_binding(self, public: bool | None = None) -> None:
    """Set default bindings for the stdin, stdtar, stdext, stdout stream proxies."""

    if (public is not None and not public) or (public is None and self.behaving_in_world()):
        self.stdin.bind(self.__proc_in_streams_by_user_hash_prv, uuid=Custom.SYSTEM_INTERACTION_UUID)
        self.stdtar.bind({}, uuid=Custom.SYSTEM_INTERACTION_UUID)
        self.stdext.bind(self.__env_streams_by_user_hash_prv, uuid=Custom.SYSTEM_INTERACTION_UUID)
        self.stdout.bind(self.__proc_streams_by_user_hash_prv, uuid=Custom.SYSTEM_INTERACTION_UUID)

    if (public is not None and public) or (public is None and not self.behaving_in_world()):
        self.stdin.bind(self.__proc_in_streams_by_user_hash_pub, uuid=Custom.SYSTEM_INTERACTION_UUID)
        self.stdtar.bind({}, uuid=Custom.SYSTEM_INTERACTION_UUID)
        self.stdext.bind(self.__env_streams_by_user_hash_pub, uuid=Custom.SYSTEM_INTERACTION_UUID)
        self.stdout.bind(self.__proc_streams_by_user_hash_pub, uuid=Custom.SYSTEM_INTERACTION_UUID)

Binds the four proxies to their defaults under the system uuid: stdin to the processor inputs, stdtar to nothing, stdext to the environmental streams and stdout to the processor outputs. public works as in set_default_stdin_binding. InteractionManager.set_current calls it before every action.

get_default_stdin_bindings

get_default_stdin_bindings(public: bool | None = None) -> dict
Source code in unaiverse/agent_basics.py
def get_default_stdin_bindings(self, public: bool | None = None) -> dict:
    """Returns the streams that are bind by default on the stdin."""
    if (public is not None and not public) or (public is None and self.behaving_in_world()):
        return self.__proc_in_streams_by_user_hash_prv

    if (public is not None and public) or (public is None and not self.behaving_in_world()):
        return self.__proc_in_streams_by_user_hash_pub
    return {}

Returns the dict (user hash to Stream) that set_default_stdin_binding would bind for public.

get_default_stream_bindings

get_default_stream_bindings(public: bool | None = None) -> tuple[dict, dict, dict, dict]
Source code in unaiverse/agent_basics.py
def get_default_stream_bindings(self, public: bool | None = None) -> tuple[dict, dict, dict, dict]:
    """Returns the streams that are bind by default on the standard streams (stdin, stdtar, stdext, stdout)."""
    if (public is not None and not public) or (public is None and self.behaving_in_world()):
        return (self.__proc_in_streams_by_user_hash_prv, {},
                self.__env_streams_by_user_hash_prv, self.__proc_streams_by_user_hash_prv)

    if (public is not None and public) or (public is None and not self.behaving_in_world()):
        return (self.__proc_in_streams_by_user_hash_pub, {},
                self.__env_streams_by_user_hash_pub, self.__proc_streams_by_user_hash_pub)
    return {}, {}, {}, {}

Returns the four dictionaries that set_default_stream_binding would bind for public, in the order stdin, stdtar, stdext, stdout.

prepare_stdin_if_human

prepare_stdin_if_human(public: bool, peer_id: str) -> tuple[str, int]
Source code in unaiverse/agent_basics.py
def prepare_stdin_if_human(self, public: bool, peer_id: str) -> tuple[str, int]:
    """Prepares the stdin of a human agent to receive what the person writes to a peer.

    Args:
        public: True when writing on the public network, False in the world.
        peer_id: The peer the person is writing to.

    Returns:
        The pair (uuid, data_tag) to use when setting the data into the stdin.
    """
    self.set_default_stdin_binding(public)

    # Who this person is writing to, taken before the world swap below: it is what tells an answer to a
    # form apart from a message meant for somebody else
    self.uai_writing_to = peer_id

    # Zero-step: if we are in a world, the peer ID used for indexing the interaction cache is the world peer ID
    peer_id = peer_id if public else self.node_conn.get_world_node_peer_id()

    # First of all, clearing residuals of interactions that were completed in the past
    to_remove = []
    for _peer_id, _interaction in self.proc_human_peer_id_to_interaction.items():
        if _interaction.is_completed():
            to_remove.append(_peer_id)
    for _peer_id in to_remove:
        del self.proc_human_peer_id_to_interaction[_peer_id]

    # Getting existing interaction or defaulting to the system one
    if peer_id in self.proc_human_peer_id_to_interaction:
        interaction = self.proc_human_peer_id_to_interaction[peer_id]
        uuid = interaction.uuid
    else:
        interaction = None
        uuid = Custom.SYSTEM_INTERACTION_UUID

    # Getting data tag
    if interaction is not None and interaction.stdin_streams is not None and len(interaction.stdin_streams) > 0:
        self.stdin.bind(interaction.stdin_streams, uuid=interaction.uuid)
        tag = self.stdin.get_tag()
        self.set_default_stdin_binding(public)
    else:
        tag = self.stdin.get_tag()

    return uuid, tag

Prepares the standard input of the agent of a person before the person's message is written on it. The node calls it with public (True on the public network) and the peer_id that the person writes to. It records peer_id in uai_writing_to and drops the stored requests of completed interactions. When a request of that peer is pending (in a world, a request of the world), the message answers it. The method then returns the uuid of that interaction and the current tag of its input streams. Otherwise it returns the system uuid and the current tag of the default input. The node then writes the message with that (uuid, data_tag).

disable_proc_input

disable_proc_input(public: bool) -> None
Source code in unaiverse/agent_basics.py
def disable_proc_input(self, public: bool) -> None:
    """Disable the processor input stream of this agent.

    Args:
        public: If True, disables the public input stream, otherwise the private one.
    """
    stream_dict = self.owned_streams[self.get_proc_input_net_hash(public=public)]
    for stream_obj in stream_dict.values():
        if stream_obj.is_public() == public:
            stream_obj.disable()

Disables the processor input streams of the public (public=True) or the private network. A disabled stream ignores new samples.

enable_proc_input

enable_proc_input(public: bool) -> None
Source code in unaiverse/agent_basics.py
def enable_proc_input(self, public: bool) -> None:
    """Enable the processor input stream of this agent.

    Args:
        public: If True, enables the public input stream, otherwise the private one.
    """
    stream_dict = self.owned_streams[self.get_proc_input_net_hash(public=public)]
    for stream_obj in stream_dict.values():
        if stream_obj.is_public() == public:
            stream_obj.enable()

Enables again the processor input streams of the public (public=True) or the private network.

set_proc_input

set_proc_input(data: str | Image | Tensor | None, public: bool = False, uuid: str | None = None, data_type: str = 'auto', data_tag: int = -1) -> bool
Source code in unaiverse/agent_basics.py
def set_proc_input(self, data: str | Image | torch.Tensor | None, public: bool = False,
                   uuid: str | None = None, data_type: str = "auto", data_tag: int = -1) -> bool:
    """Set the data in the processor input stream.

    Args:
        data: The data to set in the stream (text, image, or tensor).
        public: If True, targets the public input stream, otherwise the private one.
        uuid: Optional UUID to associate with the data sample.
        data_type: The type of data ("text", "img", "tensor", or "auto" to infer from the data).
        data_tag: The tag associated with the sample (default -1).

    Returns:
        True if the data was successfully set, False otherwise.
    """
    peer_id = self.get_peer_ids()[0] if public else self.get_peer_ids()[1]
    proc_in = self.find_streams(peer_id, "processor_in")
    if proc_in is None or len(proc_in) == 0:
        return False
    for net_hash, stream_dict in proc_in.items():
        if not DataProps.is_pubsub_from_net_hash(net_hash):
            for stream_name, stream_obj in stream_dict.items():
                assert stream_obj.props is not None
                if stream_obj.props.is_public() == public:
                    if (data is None or
                            ((data_type == "text" or isinstance(data, str)) and stream_obj.props.is_text()) or
                            ((data_type == "img" or isinstance(data, Image)) and stream_obj.props.is_img()) or
                            ((data_type == "tensor" or isinstance(data, torch.Tensor))
                             and stream_obj.props.is_tensor())):
                        stream_obj.set(data, uuid=uuid)  # This might fail if the stream is disabled
                        stream_obj.set_tag(data_tag, uuid=uuid)
                        return True
    return False

Writes one sample on a direct processor input stream of this agent. Use it to feed the processor from code (for example from a sensor loop).

Argument Type Default Meaning
data str, PIL.Image.Image, torch.Tensor or None required The sample.
public bool False The public input (True) or the world input.
uuid str or None None The uuid to store the sample under.
data_type str "auto" "text", "img" or "tensor" to choose the stream, "auto" to infer it from the type of data.
data_tag int -1 The tag of the sample.

The method writes the sample on the first input stream of the right type and returns True. It returns False when no stream fits. A None sample goes to the first stream. The write does nothing when the stream is disabled.

get_tag

get_tag(net_hash: str, uuid: str | None = None) -> int
Source code in unaiverse/agent_basics.py
def get_tag(self, net_hash: str, uuid: str | None = None) -> int:
    """Get the maximum data tag across all streams associated with the given network hash.

    Args:
        net_hash: The network hash identifying the stream group.
        uuid: Optional UUID of the data sample. If None, the latest tag is returned.

    Returns:
        The maximum data tag found, or -1 if the stream is unknown.
    """
    if net_hash in self.known_streams:
        data_tag = -1
        stream_dict = self.known_streams[net_hash]
        for stream_obj in stream_dict.values():
            t = stream_obj.get_tag(uuid)
            if t is not None:
                data_tag = max(data_tag, t)
        return data_tag
    return -1

Returns the largest data tag among the streams of the group net_hash under uuid (None reads the latest data). An unknown group or a group without tags gives -1.

set_tag

set_tag(net_hash: str, data_tag: int, uuid: str | None = None) -> None
Source code in unaiverse/agent_basics.py
def set_tag(self, net_hash: str, data_tag: int, uuid: str | None = None) -> None:
    """Set the data tag on all streams associated with the given network hash.

    Args:
        net_hash: The network hash identifying the stream group.
        data_tag: The tag value to set.
        uuid: Optional UUID of the data sample to tag. If None, the latest sample is tagged.
    """
    if net_hash in self.known_streams:
        stream_dict = self.known_streams[net_hash]
        for stream_obj in stream_dict.values():
            stream_obj.set_tag(data_tag, uuid=uuid)

Writes the tag data_tag on every stream of the group net_hash under uuid. An unknown group is ignored.

Interactions and steps

get_current_interaction

get_current_interaction() -> Interaction | None
Source code in unaiverse/agent_basics.py
def get_current_interaction(self) -> Interaction | None:
    """Gets the interaction currently being executed.

    Returns:
        The current interaction, or None.
    """
    return self.im.get_current()

Returns the interaction served by the running action. Outside an action it returns None.

get_last_sent_interaction

get_last_sent_interaction() -> Interaction
Source code in unaiverse/agent_basics.py
def get_last_sent_interaction(self) -> Interaction:
    """Gets the last interaction this agent sent.

    Returns:
        The last sent interaction.
    """
    return self.last_sent_interaction

Returns the interaction created by the last call of Agent.send. Use it to follow one request among many. Every send first clears it. A send that reached no target leaves it None.

if await self.send(action_name="process", target="ResNetAgent",
                   data_samples={"proc_output_0": picture}):
    self.pending = self.get_last_sent_interaction()

get_action_step

get_action_step() -> int | None
Source code in unaiverse/agent_basics.py
def get_action_step(self) -> int | None:
    """Retrieve the current action step from the agent's private/world behavior.

    Returns:
        The current action step object from the HybridStateMachine's active action, or None if no action.
    """
    assert isinstance(self.behav, HybridStateMachine)
    assert isinstance(self.behav_lone_wolf, HybridStateMachine)
    behav = self.behav if self.behav.is_enabled() else self.behav_lone_wolf
    return behav.get_action_step_idx() if self.overridden_action_step is None else self.overridden_action_step

Returns the index of the current step of the running action as counted by the enabled behavior (the first step is 0). A step forced with force_action_step takes precedence. It returns None when no action runs.

force_action_step

force_action_step(step: int) -> None
Source code in unaiverse/agent_basics.py
def force_action_step(self, step: int) -> None:
    """Override the current action step index used in the active behavior.

    Args:
        step: The action step index to force. If negative, the override is cleared.
    """
    self.overridden_action_step = step if step >= 0 else None

Makes get_action_step return step. A negative value removes the override. The behavior keeps its own step count.

is_last_action_step

is_last_action_step() -> bool | None
Source code in unaiverse/agent_basics.py
def is_last_action_step(self) -> bool | None:
    """Check if the agent's current action (private/world behavior) is on its last step.

    Returns:
        True if the current action was its last step, False otherwise. Returns None if there is no active action.
    """
    if self.im.current is not None:
        return self.im.current.was_last_step_done()
    else:
        return None

Returns True when the current interaction has done its last step (see Interaction.was_last_step_done) and None without a current interaction.

is_multi_steps_action

is_multi_steps_action() -> bool
Source code in unaiverse/agent_basics.py
def is_multi_steps_action(self) -> bool:
    """Determines if the current action is a multistep action.

    Returns:
        True if the action is multistep, False otherwise.
    """
    if self.im.current is not None:
        return self.im.current.is_multi_steps()
    else:
        return False

Returns True when the current interaction spans more than one step and False without a current interaction.

stepwise

stepwise(interaction: Interaction | None, make_gen: Callable[..., Generator], /, *args: Any, retry_timeout: float = _STEPWISE_RETRY_TIMEOUT_S, **kwargs: Any) -> tuple[bool, Any]
Source code in unaiverse/agent_basics.py
def stepwise(self, interaction: Interaction | None, make_gen: Callable[..., Generator], /, *args: Any,
             retry_timeout: float = _STEPWISE_RETRY_TIMEOUT_S, **kwargs: Any) -> tuple[bool, Any]:
    """Run a generator-based computation one chunk per tick across HSM retries.

    Usage inside an @action body:
        done, result = self.stepwise(interaction, core_gen_factory, arg1, kw=...)
        if not done:
            return False          # pedantic retry: the node loop keeps pumping
        ... apply result on the main task ...

    make_gen(*args, **kwargs) must build a fresh generator whose return value is the
    result of the computation; every yield marks a chunk boundary. The first call
    builds the generator, makes the action pedantic so that returning False means
    "retry next tick", and advances ONE chunk; each later call advances one more
    chunk, returning (False, None) until the generator returns, then (True, result).
    Everything runs on the main task: no threads, no concurrency, just cooperative
    slicing, so the pump latency is bounded by the longest single chunk.

    The retry budget travels in the mark as a deadline: past it, the poll cleans up
    and raises, which the @action wrapper turns into a single discard. A chunk that
    raises is cleaned up and re-raised the same way.

    Contract for the generator: self-contained compute in short chunks (each chunk
    inflates the tick it runs in); never yield while holding a thread-global mode
    (e.g. inside torch.no_grad(): enter and exit it within the chunk); re-runnable
    from scratch (a discarded interaction abandons the generator, and a later
    trigger calls make_gen again); any state flipped on shared objects (e.g. the
    model train/eval mode) must be restored in a finally block, which also runs when
    an abandoned generator is garbage-collected. Only viable on single-step actions
    or from step >= 1 of a multi-step interaction (a False at step 0 of a multi-step
    is discarded regardless of pedantic).

    With interaction=None (direct call from code) the generator is drained inline,
    blocking, like the plain synchronous function it wraps.
    """
    if interaction is None:
        gen = make_gen(*args, **kwargs)
        while True:
            try:
                next(gen)
            except StopIteration as stop:
                return True, stop.value
    if retry_timeout <= 0.:
        raise GenException("stepwise retry_timeout must be > 0")

    run = interaction.get_mark()
    if run is None:
        action_ref = interaction.action_ref
        assert isinstance(action_ref, Action)
        if not action_ref.is_pedantic():
            action_ref.set_timeout(retry_timeout)  # So that returning False means retry
        now = time.perf_counter()
        run = _StepwiseRun(make_gen(*args, **kwargs), now + retry_timeout, now)
        interaction.set_mark(run)
    assert isinstance(run, _StepwiseRun)

    if time.perf_counter() >= run.deadline:

        # Budget exhausted: give up in a single discard. The abandoned generator is
        # collected once the mark is gone, running its finally cleanup.
        self._finish_stepwise(interaction, healthy=False)
        raise GenException(f"Stepwise computation exceeded its retry budget "
                           f"({run.deadline - run.started_at:.0f} s, "
                           f"{run.chunks} chunks done)")

    try:
        next(run.gen)
    except StopIteration as stop:
        self._finish_stepwise(interaction, healthy=True)
        log.misc(f"Stepwise computation completed: {run.chunks} chunks in "
                 f"{time.perf_counter() - run.started_at:.2f} s")
        return True, stop.value
    except Exception:
        self._finish_stepwise(interaction, healthy=False)
        raise  # -> @action wrapper -> False -> non-pedantic -> discarded in one shot

    run.chunks += 1
    return False, None

Splits a long computation inside an action into chunks and runs one chunk per tick. The node keeps running between chunks. Everything runs on the event loop without threads.

Argument Type Default Meaning
interaction Interaction or None required (positional) The interaction that the action serves. None runs the whole computation at once.
make_gen callable required (positional) Builds a fresh generator. Each yield ends a chunk and the return value is the result.
*args, **kwargs Passed to make_gen.
retry_timeout float 60.0 The budget of the whole computation in seconds. A non-positive value raises GenException.

The first call builds the generator, stores it in the mark of the interaction and gives the action a retry timeout of retry_timeout (unless it has one). The action then returns False and the behavior calls it again at the next tick. Every call advances one chunk and returns (False, None) until the generator returns. The call that ends it returns (True, result). When the budget runs out the call raises GenException. An exception raised by the generator propagates as well. The @action decorator turns both into a single False that discards the interaction.

The generator must keep its chunks short, must not yield inside a thread-global mode such as torch.no_grad() and must restore any shared state in a finally block. Because a discarded interaction abandons the generator, it must also tolerate being restarted from scratch. In a multi-step interaction a False at step 0 discards the attempt in any case. A multi-step action therefore calls stepwise only from step 1 on.

from unaiverse.agent import Agent, action

class Indexer(Agent):
    def index_in_chunks(self, docs):
        for i in range(0, len(docs), 100):
            self.index.add(docs[i:i + 100])
            yield
        return len(docs)

    @action
    async def index_documents(self, interaction=None) -> bool:
        done, n = self.stepwise(interaction, self.index_in_chunks, self.documents, retry_timeout=120.0)
        if not done:
            return False
        print(f"Indexed {n} documents")
        return True

Processor hooks

hook_proc_tweak_inputs

hook_proc_tweak_inputs(inputs: Any) -> Any
Source code in unaiverse/agent_basics.py
def hook_proc_tweak_inputs(self, inputs: Any) -> Any:
    """A callback method that saves the inputs to the processor right before execution.

    Args:
        inputs: The data inputs for the processor.

    Returns:
        The same inputs passed to the function.
    """
    self.proc_last_inputs = inputs
    return inputs

Agent.process calls it right before every processor call with the tuple of inputs read from stdin. It returns the inputs to use. Returning None makes the step fail. The default stores the inputs in proc_last_inputs and returns them unchanged. An override should call super() to keep proc_last_inputs.

hook_proc_tweak_outputs

hook_proc_tweak_outputs(outputs: Any) -> Any
Source code in unaiverse/agent_basics.py
def hook_proc_tweak_outputs(self, outputs: Any) -> Any:
    """A callback method that saves the outputs from the processor right after execution.

    Args:
        outputs: The data outputs from the processor.

    Returns:
        The same outputs passed to the function.
    """
    self.proc_last_outputs = outputs
    return outputs

Agent.process calls it right after every processor call with the tuple of outputs. It returns the outputs that go to stdout. The default stores them in proc_last_outputs and returns them unchanged.

hook_before_sending_sample

hook_before_sending_sample(data: Any, data_tag: int, net_hash: str, stream_name: str, recipient: str | None) -> Any
Source code in unaiverse/agent_basics.py
def hook_before_sending_sample(self, data: Any, data_tag: int,
                               net_hash: str, stream_name: str, recipient: str | None) -> Any:
    """A callback method that handles the steam data right before sending it through the network.

    Args:
        data: The stream data sample.
        data_tag: The tag of the sample.
        stream_name: The name of the data stream.
        net_hash: The net hash of the whole stream.
        recipient: The (planned) recipient of this sample (or None in case of pubsub).

    Returns:
        The same data passed to the function.
    """
    return data

send_stream_samples calls it for each sample before the sample leaves the agent. It returns the data to send.

Argument Type Meaning
data any The sample.
data_tag int Its tag.
net_hash str The group of the stream.
stream_name str The name of the stream.
recipient str or None The peer that receives it (None for a broadcast).

The default returns data. An override can redact a sample for one recipient or compress it.

Interactive messages

An interactive message carries fenced blocks such as media, charts and forms. A form is a question with fields that the receiver must fill (see Interactive messages). A model must not read the raw blocks. Its free-text answer must become a reply block that the asker can read. The ModuleWrapper of the processor runs the following loop on every call and the methods below define its policy. A world overrides them in its role file to change how its agents read and answer forms. Every agent that joins inherits the override.

  1. On the way in, every text input that carries blocks goes through uai_preprocess and the module reads the alternative text of each block in place of the block. The stream keeps the original message.
  2. On the way out, the first text output is checked against the form of this call or, when the call had none, against the form remembered from the peer of the turn (see uai_pending_form).
  3. uai_postprocess returns an AnswerOutcome that holds one of three results. text replaces the output with a reply block, retry is a corrective prompt that the wrapper feeds to the module again and withhold stops the output. The wrapper loops while the outcome asks to retry.
  4. A withheld output raises AnswerWithheld and Agent.process returns False without logging an error. The interaction that asked stays open.

The message that a person reads never goes through the processor of the agent of that person. On the other hand the answer of the person does go through it. To check that answer against its form, get_stream_sample remembers every form that arrives through uai_remember_form.

uai_preprocess

uai_preprocess(text: str) -> tuple[str, dict | None]
Source code in unaiverse/agent_basics.py
def uai_preprocess(self, text: str) -> tuple[str, dict | None]:
    """A callback method that renders an interactive message for the processor, right before execution.

    It is called by ModuleWrapper.forward on every text input that carries protocol blocks, and only when
    the module is a real processor: a passthrough echoes wire text and is skipped. The stream keeps the
    message as it arrived; what is rewritten here is only what the module is handed.

    Args:
        text: The raw text of the message, blocks included.

    Returns:
        A tuple with the text the module should read (every block replaced by its alternative text) and the
        spec of the form it is being asked, if any, which is what the answer will be matched against.
    """
    parts = parse_message(text)
    return parts_to_model_text(parts), newest_form(parts)

Renders a message for the module. It parses text, replaces every block with its alternative text and returns (rendered_text, spec). spec is the newest form of the message or None. The wrapper calls it only for a module that does not echo its input.

uai_postprocess

uai_postprocess(text: str, spec: dict, attempt: int = 0, asked_now: bool = True, model_view: str | None = None, attempts: list | None = None) -> AnswerOutcome
Source code in unaiverse/agent_basics.py
def uai_postprocess(self, text: str, spec: dict, attempt: int = 0, asked_now: bool = True,
                         model_view: str | None = None, attempts: list | None = None) -> AnswerOutcome:
    """A callback method that decides what becomes of the processor's answer to a form, after execution.

    A block is a message with a contract on its format, and an answer that does not honour it is not
    sent as it is: a model is asked again within the same turn, with a corrective prompt, until it
    satisfies the form, the retries are spent, or the interaction is about to expire; a person at a
    keyboard is told what is wrong and nothing travels until they answer again. A world that wants its
    own reading of what its agents write (a domain-specific vocabulary, a legacy format) overrides this
    method, or the ones it delegates to, in its role file: the override is inherited by every agent that
    joins.

    Args:
        text: What the processor produced.
        spec: The spec of the form being answered, as returned by uai_preprocess or remembered from
            an earlier message.
        attempt: How many times the processor has already been asked again in this turn.
        asked_now: True when the form was handed to the processor in this very call, False when it was
            remembered from an earlier message (then a free text is ordinary chat, not a refusal).
        model_view: What the processor read the first time, for the corrective prompt.
        attempts: Every text the processor produced this turn, oldest first (the current one last):
            an answer can be completed across the corrective rounds, and the block's raw lists the
            texts its values were read from.

    Returns:
        The outcome: what should travel (a single block carrying its own readable projection, contract
        section 3.6, or None for the words as written), the prompt to ask again with, or a withhold.
    """
    values, event = read_answer(text, spec)
    raw_texts = [text]

    # From the second round on, the attempts are read together: later ones override earlier ones on
    # conflict, so a processor asked only for what was missing does not have to repeat the rest. A
    # block the processor wrote on its own is never merged over: it is theirs, and is handled below
    attempts = [t for t in (attempts or []) if isinstance(t, str) and t.strip()]
    if len(attempts) > 1 and (event is None or event.via != VIA_BLOCK):
        values, event, raw_texts = self.uai_merge_reads(spec, attempts)

    if values is not None:

        # The words the answer was read from travel inside the block, verbatim: transparent for every
        # receiver, there for whoever asks (an audit, a stat, a study of how the answer was phrased)
        answer = encode_reply(spec, values, raw=raw_texts)

        # Whatever leaves here is wire text, and a world may still cut it to its own size limit: an answer
        # that would push the message past what such limits usually are is not worth breaking
        if len(answer.encode("utf-8")) > MAX_OUTPUT_BYTES:
            return AnswerOutcome()
        self.uai_forget_form(spec)
        return AnswerOutcome(text=answer)

    # A block the processor wrote on its own (a widget, a model writing JSON) is theirs and travels as it
    # is; if it answers the form remembered here, that form is over, and what is typed next is not bound
    # to it any more
    if event is not None and event.via == VIA_BLOCK:
        if event.to == spec.get("id"):
            self.uai_forget_form(spec)
        return AnswerOutcome()

    # Nothing to read, or a text that was never an answer while a form was merely pending from before:
    # the words travel as they are. Once the processor has been asked again, though, a free text is a
    # refusal like any other; and so is silence, when the form was handed over in this very turn: an
    # empty answer to a question just asked is a refusal to answer it, not a message (an empty answer
    # to an unrelated turn, with a form merely pending from before, is ordinary silence and travels).
    # A person at a terminal is the exception to the free pass: a form is the last thing they were
    # shown, their next line IS the answer to it, and one that cannot be read is told and withheld
    # rather than delivered as if it were the reply (their form is always "merely pending", since what
    # they are shown never goes through their processor, so without this they would never be held)
    if event is None or (event.via == VIA_FREETEXT and not asked_now and attempt == 0
                         and not self.uai_can_reprompt_person()):
        if not text.strip() and (asked_now or attempt > 0):
            return self.uai_answer_fell_short(text, spec, None, attempt, model_view)
        return AnswerOutcome()
    return self.uai_answer_fell_short(text, spec, event, attempt, model_view, attempts=raw_texts)

Decides what becomes of the answer text of the processor to the form spec. It returns an AnswerOutcome.

Argument Type Default Meaning
text str required The output of the processor.
spec dict required The form being answered.
attempt int 0 How many times the processor was already asked again in this turn.
asked_now bool True True when the form came with this call, False when it was remembered from an earlier message.
model_view str or None None What the processor read the first time. The corrective prompt restates it.
attempts list[str] or None None Every non-empty text of the turn from the oldest.

The decision follows these rules in order.

  1. With more than one attempt and no block written by the processor, the attempts are read together with uai_merge_reads.
  2. When the reading satisfies the form, the answer becomes a reply block that carries the values and the texts they were read from. The form is then forgotten and the reply travels. A reply larger than 16384 bytes is dropped in favor of the text as written and the form stays remembered.
  3. A block that the processor wrote itself travels as it is. When it answers this form, the form is forgotten.
  4. A text with nothing to read travels as it is. So does a free text when three conditions hold: the form was only remembered, this is the first attempt and the agent cannot ask a person again. In both cases an empty text goes to uai_answer_fell_short as a refusal when the form was asked now or the processor was already asked again.
  5. Every other case goes to uai_answer_fell_short.

uai_merge_reads

uai_merge_reads(spec: dict, attempts: list) -> tuple
Source code in unaiverse/agent_basics.py
def uai_merge_reads(self, spec: dict, attempts: list) -> tuple:
    """Reads every attempt of the turn against the form and merges what they gave.

    Later attempts override earlier ones on conflict, so an answer can be built across the corrective
    rounds of one turn: what was already read stays good, and the processor is asked only for what is
    still missing. An attempt whose reading is addressed to a different form contributes nothing.

    Args:
        spec: The form being answered.
        attempts: The texts the processor produced this turn, oldest first.

    Returns:
        A tuple: the merged values when they satisfy the form, meaning nothing required is missing
        AND the latest attempt raised no complaint (else None); the event describing the merged
        reading; and the texts, oldest first, that anything was read from, which is what the raw of
        the encoded block lists (the last attempt alone, when nothing was ever readable).
    """
    merged, contributors, issues, last_via = {}, [], {}, VIA_FREETEXT
    for t in attempts:
        _, e = read_answer(t, spec)
        if e is None or (e.to is not None and e.to != spec.get("id")):
            continue
        if e.values:
            contributors.append(t)
            merged.update(e.values)
        issues = dict(e.issues) if e.issues else {}  # Only the LATEST attempt's complaints stand
        last_via = e.via

    # A field the latest attempt complained about is not "missing" (it was addressed, badly): the
    # correction words the complaint, never a self-contradictory "you said nothing about it"
    missing = [f["name"] for f in interactive_fields(spec)
               if f.get("required") and f["name"] not in merged and f["name"] not in issues]
    event = ReplyEvent(to=spec.get("id"), name=spec.get("name"), values=merged, missing=missing,
                       issues=issues, raw=attempts[-1] if attempts else "", via=last_via,
                       duplicate=False)

    # Complete only when nothing required is missing AND the latest attempt raised no complaint: a
    # fresh out-of-range value is a retraction being corrected, never something to ship over
    return (merged if not missing and not issues else None), event, (contributors or attempts[-1:])

Reads each text of attempts against spec and merges the values. Later attempts override earlier ones. An attempt addressed to another form contributes nothing. Only the complaints of the latest readable attempt count. It returns a tuple of three items.

  1. The merged values when no required field is missing and the latest attempt raised no complaint. In every other case None.
  2. The ReplyEvent of the merged reading with its missing fields and complaints.
  3. The texts that contributed values in order from the oldest. When none did, the last attempt alone.

uai_answer_fell_short

uai_answer_fell_short(text: str, spec: dict, event: Any, attempt: int, model_view: str | None = None, attempts: list | None = None) -> AnswerOutcome
Source code in unaiverse/agent_basics.py
def uai_answer_fell_short(self, text: str, spec: dict, event: Any, attempt: int,
                               model_view: str | None = None, attempts: list | None = None) -> AnswerOutcome:
    """A callback method for an answer that was meant for a form and does not satisfy it.

    Args:
        text: What was written.
        spec: The form it was meant to answer.
        event: How the text was read, carrying "missing" and "issues" (or nothing at all, for free
            text); after a corrective round it describes the MERGED reading of every attempt.
        attempt: How many times the processor has already been asked again in this turn.
        model_view: What the processor read the first time, if known.
        attempts: The texts, oldest first, the event's values were read from: what the raw of an
            encoded partial lists (the current text alone, when not given).

    Returns:
        The outcome, see uai_postprocess.
    """

    # A person at a terminal is told what is wrong, through the same sink every message to them goes
    # through, and asked to write again: nothing travels, the form stays pending, their next line is read
    # against it. A person in the web application cannot be told (what this node prints never reaches
    # their chat, and their bubble is already on their screen): their words travel as written, and the
    # widget is their way to answer a form.
    if has_human_processor(self):
        if not self.uai_can_reprompt_person():
            return AnswerOutcome()

        # rep=True: two failed attempts in a row often word the SAME complaint, and the screen sink
        # suppresses consecutive identical lines; the person must see the reprompt every single time
        log.user(f"⚠️ {reprompt_person(spec, event)}", rep=True)
        return AnswerOutcome(withhold=True)

    # A module that gives back what it was given is a relay, not the author: there is nobody to ask
    if self.uai_module_echoes():
        return AnswerOutcome()

    # The exchange is about to expire: asking once more would produce an answer nobody is waiting for,
    # and an answer that never honoured the form is discarded rather than sent
    if self.uai_time_left() <= 0.:
        log.misc(f"The answer to '{spec.get('name', spec.get('id'))}' never satisfied it and the "
                 f"interaction is expiring: nothing is sent ({describe_answer(spec, event)})")
        return AnswerOutcome(withhold=True)

    if attempt < self.UAI_MAX_RETRIES:
        return AnswerOutcome(retry=retry_prompt(spec, text, event, model_view))

    # The retries are spent and nothing was ever said: silence has no words to send, and an empty
    # string must not reach whoever asked as if it were an answer, so it is withheld like an
    # expiring one (the form stays pending, the asker times out instead of reading an empty ballot)
    if not text.strip():
        log.misc(f"The answer to '{spec.get('name', spec.get('id'))}' was never given after "
                 f"{attempt} more attempts: nothing is sent")
        return AnswerOutcome(withhold=True)

    # The retries are spent: what travels is one reply block carrying whatever could be read and the
    # words themselves as its raw, so that whoever asked gets the values there are, learns what is
    # missing, and can still read how the answer was phrased. The form is over either way
    log.misc(f"The answer to '{spec.get('name', spec.get('id'))}' still does not satisfy it after "
             f"{attempt} more attempts, it travels as a reply carrying its words: "
             f"{describe_answer(spec, event)}")
    partial = encode_partial(spec, attempts if attempts else text, event)
    if partial is not None:
        self.uai_forget_form(spec)
    return AnswerOutcome(text=partial)

Handles an answer that was meant for the form spec and does not satisfy it. The arguments are those of uai_postprocess plus event (the reading, None for free text). It returns an AnswerOutcome chosen by the first rule that applies.

  1. The agent of a person in the browser: the words travel as written. Nothing printed by the node reaches the chat of that person.
  2. The agent of a person at a terminal: the node prints what is wrong and withholds the answer. The form stays pending and the next line is read against it.
  3. A module that echoes its input: the words travel as written.
  4. No time left (see uai_time_left): withheld.
  5. Fewer than UAI_MAX_RETRIES attempts: a corrective prompt to ask the module again.
  6. An empty text after the retries: withheld.
  7. Otherwise a partial reply block with the values that could be read and the words of the attempts. The form is forgotten.

uai_time_left

uai_time_left() -> float
Source code in unaiverse/agent_basics.py
def uai_time_left(self) -> float:
    """Seconds still worth spending on the current turn before the interaction that asked expires.

    An interaction lives at most Custom.DEFAULT_INTER_TIMEOUT seconds, less when it carries its own
    timeout; a margin is kept, since whoever asked created their copy earlier than this agent did.
    A self-driven turn has no asker waiting, and gets the default budget.
    """
    budget = Custom.DEFAULT_INTER_TIMEOUT
    interaction = self.get_current_interaction()
    if interaction is not None and not interaction.is_system():
        if interaction.timeout is not None and interaction.timeout > 0.:
            budget = min(budget, interaction.timeout)
        budget -= self.clock.get_time() - interaction.timestamp_created
    return budget - self.UAI_DEADLINE_MARGIN

Returns the seconds still worth spending on the current turn. The budget starts from Custom.DEFAULT_INTER_TIMEOUT (300 seconds). A positive timeout of the current interaction lowers it to that value and the age of the interaction is subtracted from it. A system turn has the full budget. UAI_DEADLINE_MARGIN is subtracted in every case. A non-positive result stops the retries.

uai_can_reprompt_person

uai_can_reprompt_person() -> bool
Source code in unaiverse/agent_basics.py
def uai_can_reprompt_person(self) -> bool:
    """Tells whether the person behind this agent can read what this node prints and write again.

    True at a terminal. In the browser the agent runs under Pyodide and what it prints does not reach
    the person's chat, so there is nobody to ask.
    """
    return has_human_processor(self) and sys.platform != "emscripten"

Returns True when the agent is the agent of a person and does not run in the browser. Only in that case can the person read what the node prints and write again.

uai_module_echoes

uai_module_echoes() -> bool
Source code in unaiverse/agent_basics.py
def uai_module_echoes(self) -> bool:
    """Tells whether the processor gives back what it is handed (a person, a relay), in which case what
    it produces is never rewritten on the way in and is never asked again on the way out."""
    return self.proc is not None and bool(getattr(self.proc.module, "UAI_ECHOES_INPUT", False))

Returns True when the module of the processor declares UAI_ECHOES_INPUT = True (a person, a relay). Such a module never receives a rendered input and is never asked again for its output.

uai_peer

uai_peer() -> str | None
Source code in unaiverse/agent_basics.py
def uai_peer(self) -> str | None:
    """The peer this processor turn is talking to.

    It is whoever asked, when the turn was requested by somebody. When an agent writes on its own
    initiative, which is what a person at a keyboard does, the turn is a system one: then it is whoever
    that person is writing to, and failing that the partner the behavior is pointing at.
    """
    interaction = self.get_current_interaction()
    if interaction is not None and not interaction.is_system() and interaction.requester is not None:
        return interaction.requester
    if self.uai_writing_to is not None:
        return self.uai_writing_to
    behav = self.behav if self.behaving_in_world() else self.behav_lone_wolf
    wildcards = behav.get_wildcards() if behav is not None else {}
    return wildcards.get(Custom.PARTNER_WILDCARD)

Returns the peer of the current turn: the requester of the current interaction when it is not a system one. Without such a requester it returns uai_writing_to. When that is None too it returns the value of <partner> in the enabled behavior.

uai_remember_form

uai_remember_form(peer_id: str | None, text: str) -> None
Source code in unaiverse/agent_basics.py
def uai_remember_form(self, peer_id: str | None, text: str) -> None:
    """A callback method that remembers the last form a peer sent, to match a future answer against it.

    This exists because the two halves of an exchange travel apart: what a person is shown never goes
    through their processor, while their answer does, so without this the answer would have nothing to
    be matched against. A form is remembered for as long as the interaction that asked it can live; a
    world that needs more than the last form per peer (several open at a time, a duplicate flag)
    overrides this together with uai_pending_form, uai_pending_view and uai_forget_form.

    Args:
        peer_id: Who sent the message.
        text: The message, as it arrived.
    """
    if peer_id is None or not isinstance(text, str):
        return
    parts = parse_message(text)
    spec = newest_form(parts)
    if spec is None:
        return
    self.uai_inbox.pop(peer_id, None)  # Re-inserted below, so that the oldest entry stays first

    # The rendered message is kept beside the spec: a corrective prompt built long after the message
    # arrived can then restate the whole question, not only the form's own instruction
    self.uai_inbox[peer_id] = (spec, self.clock.get_time(), parts_to_model_text(parts))
    while len(self.uai_inbox) > MAX_INBOX_PEERS:
        self.uai_inbox.pop(next(iter(self.uai_inbox)))

Remembers the newest form of the message text sent by peer_id. It ignores a None peer, a non-string message and a message without forms. The entry (spec, time, rendered_text) replaces the previous one of that peer and moves it to the end of uai_inbox. Past 32 peers the oldest entry is dropped. A world that needs more than one form per peer overrides it together with uai_pending_form, uai_pending_view and uai_forget_form.

uai_pending_form

uai_pending_form() -> dict | None
Source code in unaiverse/agent_basics.py
def uai_pending_form(self) -> dict | None:
    """A callback method that returns the form this agent is expected to be answering, if any."""
    peer_id = self.uai_peer()
    entry = self.uai_inbox.get(peer_id) if peer_id is not None else None
    if entry is None:
        return None
    spec, remembered_at = entry[0], entry[1]

    # Older than any interaction can be, so nobody is waiting for an answer any more
    if self.clock.get_time() - remembered_at > Custom.DEFAULT_INTER_TIMEOUT:
        del self.uai_inbox[peer_id]
        return None
    return spec

Returns the form remembered from uai_peer() or None. An entry older than Custom.DEFAULT_INTER_TIMEOUT (300 seconds) is deleted and gives None because no interaction can still wait for it.

uai_pending_view

uai_pending_view() -> str | None
Source code in unaiverse/agent_basics.py
def uai_pending_view(self) -> str | None:
    """A callback method that returns the message that carried the pending form, as a processor reads
    it (every block replaced by its alternative text), when it is still known. A corrective prompt for
    a form remembered from an earlier message uses it to restate the question that was actually asked,
    instead of repeating the form's instruction alone."""
    if self.uai_pending_form() is None:
        return None
    peer_id = self.uai_peer()
    entry = self.uai_inbox.get(peer_id) if peer_id is not None else None
    return entry[2] if entry is not None else None

Returns the rendered text of the message that carried the pending form or None. A corrective prompt for a remembered form uses it to restate the question that was asked.

uai_forget_form

uai_forget_form(spec: dict) -> None
Source code in unaiverse/agent_basics.py
def uai_forget_form(self, spec: dict) -> None:
    """A callback method that forgets a remembered form once an answer to it has travelled.

    A form is answered once: forgetting it keeps a later message, which might well read as another
    answer, from being delivered as a second one to something that is over.
    """
    peer_id = self.uai_peer()
    entry = self.uai_inbox.get(peer_id) if peer_id is not None else None
    if entry is not None and entry[0].get("id") == spec.get("id"):
        del self.uai_inbox[peer_id]

Deletes the form remembered from uai_peer() when its id is the id of spec. A form is answered only once. After the deletion a later message of the same peer is not delivered as a second answer.

Status attributes

The built-in actions keep their state in attributes whose name starts with a single _ (for example _engaged_agents and _found_agents in Agent). The two methods below treat every such attribute of type list, set, dict, int, float or bool as status.

remove_peer_from_agent_status_attrs

remove_peer_from_agent_status_attrs(peer_id: str) -> None
Source code in unaiverse/agent_basics.py
def remove_peer_from_agent_status_attrs(self, peer_id: str) -> None:
    """Remove a peer ID from the status of the agent, assuming it to be the represented by attributes that start
    with '_'."""
    for attr_name in dir(self):
        if attr_name.startswith("_") and (not attr_name.startswith("__") and not attr_name.startswith("_Agent")
                                          and not attr_name.startswith("_WAgent")):
            try:
                value = getattr(self, attr_name)
                if isinstance(value, list):
                    setattr(self, attr_name, [v for v in value if v != peer_id])
                elif isinstance(value, set):
                    value.discard(peer_id)
                elif isinstance(value, dict):
                    if peer_id in value:
                        del value[peer_id]
            except AttributeError:
                continue  # Skip read-only attributes

Removes peer_id from every status attribute: from lists and sets and as a key of dictionaries. remove_agent calls it. A custom status attribute that holds peer ids is therefore cleaned when the peer leaves.

reset_agent_status_attrs

reset_agent_status_attrs() -> None
Source code in unaiverse/agent_basics.py
def reset_agent_status_attrs(self) -> None:
    """Resets attributes that represent the status of the agent, assuming to be the ones that start with '_'."""
    for attr_name in dir(self):
        if (attr_name.startswith("_") and not attr_name.startswith("__") and not attr_name.startswith("_Agent")
                and not attr_name.startswith("_WAgent") and not attr_name.startswith("_AgentBasics")):
            try:
                value = getattr(self, attr_name)
                if isinstance(value, list):
                    setattr(self, attr_name, [])
                elif isinstance(value, set):
                    setattr(self, attr_name, set())
                elif isinstance(value, dict):
                    setattr(self, attr_name, {})
                elif isinstance(value, int):
                    setattr(self, attr_name, 0)
                elif isinstance(value, float):
                    setattr(self, attr_name, 0.)
                elif isinstance(value, bool):
                    setattr(self, attr_name, False)
            except AttributeError:
                continue  # Skip read-only attributes

Resets every status attribute to the empty value of its type ([], set(), {}, 0, 0.0). Because bool is a subclass of int, a bool resets to 0. clear_world_related_data calls it when the agent leaves a world.

Saving and loading

agent_state_dict

agent_state_dict() -> dict
Source code in unaiverse/agent_basics.py
def agent_state_dict(self) -> dict:
    """Returns a dictionary containing an instance of the agent's state that can be saved."""
    save_in_state = ['world_profile', 'world_role_fsms']
    return {k: getattr(self, k) for k in save_in_state}

Returns the part of the state that save pickles: {"world_profile": ..., "world_role_fsms": ...}. Override it to save more attributes. load restores every key as an attribute.

save

save(where: str = '') -> bool
Source code in unaiverse/agent_basics.py
def save(self, where: str = "") -> bool:
    """Save the agent's state, including its processor and other attributes, to a specified location.

    Args:
        where: The directory path where the agent's state should be saved. Defaults to "".

    Returns:
        True upon successful saving.

    Raises:
        IOError: If there is an issue with file operations (e.g., directory creation, writing files).
        TypeError, ValueError, RuntimeError: For other potential issues during serialization or saving.
    """
    if not (isinstance(self.proc, ModuleWrapper) and isinstance(self.proc.module, torch.nn.Module)):
        return False

    if where == '':
        if self.node_identity_dir is None or len(self.node_identity_dir) == 0:
            return False
        where = os.path.join(self.node_identity_dir, "agent_state")  # Default save path

    os.makedirs(where, exist_ok=True)

    # Saving the processor
    if self.proc is not None and self.proc_updated_since_last_save:
        assert isinstance(self.proc, ModuleWrapper)
        proc: ModuleWrapper = self.proc
        assert isinstance(proc.module, torch.nn.Module)

        pt_final = os.path.join(where, f"{self.node_name}.pt")
        pt_tmp = pt_final + ".tmp"
        try:
            checkpoint = {
                'model_state_dict': proc.module.state_dict(),
            }

            # If your agent has an optimizer, save its state too
            assert self.proc_opts is not None
            if self.proc_opts.get('optimizer', None) is not None:
                checkpoint['optimizer_state_dict'] = self.proc_opts['optimizer'].state_dict()

            torch.save(checkpoint, pt_tmp)
            os.replace(pt_tmp, pt_final)  # Atomic move
            self.proc_updated_since_last_save = False
        except Exception as e:
            if os.path.exists(pt_tmp):
                os.remove(pt_tmp)
            log.error(f"Error saving processor: {e}")
            raise e

    # Save Agent State
    pkl_final = os.path.join(where, f"{self.node_name}.pkl")
    pkl_tmp = pkl_final + ".tmp"
    try:
        state = self.agent_state_dict()
        with open(pkl_tmp, "wb") as f:
            pickle.dump(state, f)
        os.replace(pkl_tmp, pkl_final)
    except Exception as e:
        log.error(f"Could not save " + ("agent" if not self.is_world else "world") + f": {e}")
        if os.path.exists(pkl_tmp):
            os.remove(pkl_tmp)
        raise e

    return True

Saves the agent into the folder where and returns True. The node calls it every save_checkpoint_every seconds when that value is positive.

  1. It returns False at once when the processor is not a PyTorch module. It does the same when where is empty and the node has no identity folder. An empty where means <identity dir>/agent_state.
  2. When the processor learned since the last save, it writes {"model_state_dict": ..., "optimizer_state_dict": ...} to <node name>.pt.
  3. It pickles agent_state_dict() to <node name>.pkl.

Each file is written under a temporary name and then renamed to its final name. An error removes the temporary file and is raised again.

load

load(where: str = '') -> bool
Source code in unaiverse/agent_basics.py
def load(self, where: str = "") -> bool:
    """Load the agent's state from a specified location.

    Args:
        where: The directory path from which the agent's state should be loaded. Defaults to "".

    Returns:
        True if loading succeeded.
    """
    if not (isinstance(self.proc, ModuleWrapper) and isinstance(self.proc.module, torch.nn.Module)):
        return False

    if where == '':
        if self.node_identity_dir is None or len(self.node_identity_dir) == 0:
            return False
        where = os.path.join(self.node_identity_dir, "agent_state")  # Default save path

    # Check if directory exists
    if not os.path.exists(where):
        log.error("No state folder found for " + ("agent" if not self.is_world else "world") +
                  f" {self.node_name}.")
        return False

    # Check if the specific pickle file exists
    pkl_path = os.path.join(where, f"{self.node_name}.pkl")
    if not os.path.exists(pkl_path):
        log.error("No saved state found for " + ("agent" if not self.is_world else "world") +
                  f" {self.node_name}.")
        return False

    # Loading the agent state dictionary
    try:
        with open(pkl_path, "rb") as f:
            agent_state_dict = pickle.load(f)
    except Exception as e:
        raise Exception(f"Error loading pickle file at {pkl_path}: {e}")

    # Update self's attributes with the loaded object's attributes
    self.__dict__.update(agent_state_dict)

    # Check if we also need to load the processor state
    pt_path = os.path.join(where, f"{self.node_name}.pt")
    load_proc = self.proc is not None and os.path.exists(pt_path)
    if load_proc:
        try:
            assert self.proc is not None
            assert self.proc_opts is not None
            proc: ModuleWrapper = self.proc
            assert isinstance(proc.module, torch.nn.Module)
            checkpoint = torch.load(pt_path)
            if isinstance(checkpoint, dict) and 'model_state_dict' in checkpoint:
                proc.module.load_state_dict(checkpoint['model_state_dict'])

                # Restore Optimizer to proc_opts
                if 'optimizer_state_dict' in checkpoint and self.proc_opts.get('optimizer') is not None:
                    self.proc_opts['optimizer'].load_state_dict(checkpoint['optimizer_state_dict'])
            else:
                proc.module.load_state_dict(checkpoint)
        except Exception as e:
            raise Exception(f"Error loading processor state: {e}")

    return True

Loads the files written by save from where (empty means <identity dir>/agent_state) and returns True. It returns False in three cases: (1) the processor is not a PyTorch module, (2) the folder or <node name>.pkl is missing and (3) where is empty without an identity folder. It restores the pickled attributes and, when <node name>.pt exists, the weights of the module and the state of the optimizer. A file that cannot be read raises Exception.

Network events

on_send_event async

on_send_event(peer_id: str, event: dict) -> None
Source code in unaiverse/agent_basics.py
async def on_send_event(self, peer_id: str, event: dict) -> None:
    """Reacts to an event of the send queue of a peer: override it in an agent or world (async).

    Called at the tick boundary (never inside behave()), after send_status was updated. Event types: "written"
    (messages up to event["seq"] left on the stream), "write_failed" (kept for a retry), "recovered", "refused"
    (a full queue refused event["count"] messages), "queue_dropped" (event["count"] messages lost, with
    event["reason"]: max_attempts, max_age or explicit). The default does nothing. Never fires in the browser.

    Args:
        peer_id: The peer.
        event: The event (see P2P.pop_send_events for its fields).
    """
    pass

A hook awaited at the tick boundary for each event of the send queue of a peer (async). send_status is already updated when it runs. The default does nothing. An exception is logged and does not stop the tick. It never fires in the browser.

event["type"] Meaning
"written" The messages up to event["seq"] were written.
"write_failed" A write failed and is kept for a retry.
"recovered" The queue works again.
"refused" A full queue refused event["count"] messages.
"queue_dropped" event["count"] messages were lost. event["reason"] is max_attempts, max_age or explicit.

See Networking.

on_transfer_progress async

on_transfer_progress(peer_id: str, direction: str, seq: int, done: int, total: int, files: list[str], reason: str | None) -> None
Source code in unaiverse/agent_basics.py
async def on_transfer_progress(self, peer_id: str, direction: str, seq: int, done: int, total: int,
                               files: list[str], reason: str | None) -> None:
    """Reacts to the progress of a message larger than a chunk (a chunked message, or a file message): override
    it in an agent or world, e.g. to show a percentage (async).

    Called at the tick boundary, throttled (at the first and last chunk, and in between at most every half second
    and every 1%), after transfers was updated. A restart from the first chunk (a broken stream) reports a smaller
    done again. A dropped received message reports its reason. Never fires in the browser.

    Args:
        peer_id: The peer.
        direction: "send" (bytes written to the transport, at most a chunk ahead of the peer) or "receive" (bytes
            received).
        seq: The sequence number of the message in the queue of the sender (for "send", the one of its ticket).
        done: Bytes so far.
        total: Bytes of the whole message (for a file message, the files and the message together).
        files: The names of the files of a file message (empty for a chunked message).
        reason: None, or why a received message was dropped (e.g. "timeout", "hash_mismatch", "too_large").
    """
    pass

A hook awaited at the tick boundary during a transfer larger than one chunk (async). transfers is already updated when it runs. It fires at the first and last chunk and in between at most every half second and every 1%. The default does nothing. It never fires in the browser.

Argument Type Meaning
peer_id str The peer.
direction str "send" (bytes written, at most one chunk ahead of the peer) or "receive".
seq int The sequence number of the message in the queue of the sender.
done int Bytes so far. A restart from the first chunk reports a smaller value again.
total int Bytes of the whole message with its files.
files list[str] The names of the files of a file message. A chunked message gives an empty list.
reason str or None Why a received message was dropped ("timeout", "hash_mismatch", "too_large"). It is None for a message that was not dropped.
class Uploader(Agent):
    async def on_transfer_progress(self, peer_id, direction, seq, done, total, files, reason):
        if reason is None and total > 0:
            print(f"{direction} {seq}: {100 * done // total}%")