Agent is the class that a developer instantiates or subclasses to put a processor on the network. It extends AgentBasics, the class that holds the processor, the streams, the known peers, the behaviors and the interaction manager. On top of that machinery Agent adds the built-in actions and the statistics that it reports to its world. The narrative guides are Agents, Actions and Interactions.
An action is an async method marked with @action that returns a bool. Three kinds of caller run actions.
A behavior runs the action that labels a transition of its current state. True means that the action completed and the behavior moves to the destination state. False means that the action failed or has not finished yet. The behavior retries it as long as the retry_timeout of the transition lasts and drops the attempt when no retry window is left.
Another agent requests an action with send. The behavior of the target queues the request on the action and runs it when the machine is in the source state of that transition.
The developer awaits an action from code that runs during a tick (another action, a callback, an override of behave). The call then returns the bool and runs outside any behavior.
An action that has a parameter named interaction receives the Interaction that it serves. When nobody requested it, the behavior serves it with a system interaction that the agent creates for itself (requester "system").
Many built-in actions work on a group of peers that earlier actions selected. The agent keeps two such groups: the found agents (filled by find_agents and connect_by_role) and the engaged agents (the partners of a task, filled by the engagement actions). A third group holds the agents that passed the last compare_eval. An action argument named agent follows one rule everywhere in this module.
Value of agent
Peers involved
a peer id, a node name or owner/name
that peer (the decorator resolves names to peer ids)
"<valid_cmp>"
the agents that passed the last compare_eval
a list or set of peer ids
those peers
None
the engaged agents when there are any, the found agents otherwise
An empty group logs an error and makes the action return False (or send nothing).
defaction(func:Callable)->Callable:"""Decorator (@action) that standardizes action method arguments. Applied to action methods to: - Resolve agent references from name to peer_id. - Mark the function as an action (sets ``_is_action = True``). - Handle unexpected exceptions. Args: func: The action method to decorate. Returns: The wrapped function. """@functools.wraps(func)asyncdefwrapper(self,*args,**kwargs):self:Agentresolved_kwargs={}iffunc.__name__notinCustom.SPECIAL_ACTION_NAMES:# Special actions (like 'send') resolve by themselvesforkey,valueinkwargs.items():ifkeyinCustom.AGENT_ARG_NAMES:ifisinstance(value,str):resolved=self.resolve_agent_ref(value)resolved_kwargs[key]=resolvedifresolvedisnotNoneelsevalueelifisinstance(value,list|tuple):_values=list(value)# Shallowfori,_valueinenumerate(_values):_resolved=self.resolve_agent_ref(_value)if_resolvedisnotNone:_values[i]=_resolvedresolved_kwargs[key]=_valueselse:resolved_kwargs[key]=valueelifkeyinCustom.STREAM_ARG_NAMES:public=notself.behaving_in_world()ifisinstance(value,str):resolved=self.resolve_stream_ref(value,public)resolved_kwargs[key]=resolvedifresolvedisnotNoneelsevalueelifisinstance(value,(list,tuple)):_values=list(value)# Shallowfori,_valueinenumerate(_values):_resolved=self.resolve_stream_ref(_value,public)if_resolvedisnotNone:_values[i]=_resolvedresolved_kwargs[key]=_valueselse:resolved_kwargs[key]=valueelse:resolved_kwargs[key]=valueelse:resolved_kwargs=kwargs# Calling the actiontry:ret=awaitfunc(self,*args,**resolved_kwargs)ifretisNone:log.critical(f"Invalid action '{func.__name__}' detected, it must return True/False ""(it is tolerated to return non-None stuff and interpreted as True, ""but not if it returns None, as happens here)")exceptExceptionase:importtraceback# Debugifnotisinstance(e,AssertionError):log.error(f"Action '{func.__name__}' failed since it raised an exception: {e}")# No-Debuglog.error(f"{traceback.format_exc()}")# Debugelse:log.error(f"Action '{func.__name__}' failed since it raised an AssertionError")# No-Debuglog.error(f"{traceback.format_exc()}")ret=Falsereturnretwrapper._is_action=Truereturnwrapper
The decorator of every action. It returns an async wrapper that does three things around the decorated coroutine.
It resolves the keyword arguments by name. agent, agents, partner, partners, target and targets go through resolve_agent_ref (a list is resolved item by item). stream and streams go through resolve_stream_ref on the network where the agent behaves. A value that does not resolve stays as it was. Positional arguments are never resolved and send is exempt because it resolves its own arguments.
It catches every exception of the action, logs it with its traceback and returns False. The node keeps running.
It logs a critical message when the action returns None. The None is returned as it is and the behavior reads it as a failure. Any other value is returned unchanged.
The wrapper carries the attribute _is_action = True. No other part of the SDK reads it in the current version.
fromunaiverse.agentimportAgent,actionclassRobot(Agent):@actionasyncdefmove_arm(self,angle:float,agent:str|None=None,interaction=None)->bool:# 'agent' arrives already resolved to a peer idreturnself.arm.rotate(angle)
def__init__(self,*args:Any,**kwargs:Any)->None:"""Initializes the agent and the status variables of its basic actions. Args: *args: Positional arguments forwarded to AgentBasics. **kwargs: Keyword arguments forwarded to AgentBasics. """super().__init__(*args,**kwargs)# Status variables (assumed to start with "_"): Agent exchangesself._available=True# It will be automatically set/changed during the agent's lifeself._found_agents=set()# Peer IDs discoveredself._valid_cmp_agents=set()# Agents for which the last evaluation was positiveself._engaged_agents=set()self._eval_results={}# The agents that disconnected() follows when called with no argument, removed since:# the removal empties the sets above, and these are what is left to check. Its name# keeps it out of the generic clean-up of the status attributes.self.__removed_followed_agents=set()# Status variables (assumed to start with "_"): Recordingsself._last_recorded_stream_num=1self._last_recorded_stream_dict=Noneself._last_recorded_count=0# Status variables (assumed to start with "_"): Playlistself._preferred_streams=[]# List of preferred streamsself._cur_preferred_stream=0# ID of the current preferred stream from the listself._repeat=1# Number of repetitions of the playlist# Statsself.stats=Stats(is_world=False)self.overwrite_stats=False# Whether to overwrite stats when receiving the next STATS_RESPONSE from the world
The agent class. The constructor takes the arguments of AgentBasics unchanged (proc, proc_inputs, proc_outputs, proc_opts, merge_flat_stream_labels, buffer_generated, buffer_generated_by_others, world_folder, policy_filter, policy_filter_lone_wolf). It then initializes the status of the built-in actions (found and engaged agents, evaluation results, recording counters, playlist) and creates the statistics recorder. The status attributes start with _ and the agent resets them when it leaves a world.
The Stats recorder of the agent. The constructor creates it with is_world=False. When the agent joins a world that ships its own statistics class, the node replaces it with an instance of that class. Its view holds the statistics that the world sends back.
bool, False by default. The node passes it to update_stats_view for every statistics answer of the world. With True the answer replaces the local view instead of merging into it.
defcollect_and_store_own_stats(self)->None:"""Collects this agent's own stats and pushes them to the stats recorder."""ifself.statsisNone:return_,own_private_pid=self.get_peer_ids()t=clock.get_time_ms()info=self.node_conn.get_world_connected_peers_info()ifinfoisNone:# The FFI call failed (transport state unknown): skip this sample rather than# record a false "zero peers", which would poison the world connectivity graph# with a phantom drop of every peer on a transient error.log.error("[Stats] connected peers unavailable (FFI error); skipping the sample")else:try:peers_list=[i['id']foriininfo]self.stats.store_stat('connected_peers',peers_list,group_key=own_private_pid,timestamp=t)exceptExceptionase:self.stats.store_stat('connected_peers',[],group_key=own_private_pid,timestamp=t)log.error(f"[Stats] Error collecting and storing own stats, clearing: {e}")try:behav=self.behavassertbehavisnotNoneself.stats.store_stat('state',behav.get_state_name(),group_key=own_private_pid,timestamp=t)self.stats.store_stat('action',behav.get_action_name(),group_key=own_private_pid,timestamp=t)self.stats.store_stat('last_action',behav.get_last_completed_action_name(),group_key=own_private_pid,timestamp=t)exceptExceptionase:log.error(f"[Stats] Error storing HSM stats: {e}")
Records the statistics of the agent itself under its private peer id with the current time in milliseconds: connected_peers (the peer ids that the world connection reports), state, action and last_action (from the world behavior). When the list of connected peers is not available it skips that statistic rather than record an empty list. send_stats_to_world calls it and so does a World for itself. It does nothing when stats is None.
asyncdefsend_stats_to_world(self)->None:"""Sends the agent's currently buffered stats to the world and clears them (async)."""ifnotself.in_world():log.debug("[send_stats_to_world] Not in a world, skipping stats send.")returnworld_peer_id=self.node_conn.get_world_node_peer_id()ifworld_peer_idisNone:log.error("Agent in world, but world_peer_id is None.")returnself.collect_and_store_own_stats()# update own statsassertself.statsisnotNonepayload=self.stats.get_payload_for_world()ifnotpayload:log.debug("[send_stats_to_world] No stats to send.")return# Send all statslog.misc(f"Sending stats update to world {world_peer_id}...")ifnot(awaitself.node_conn.send(world_peer_id,channel_trail=None,content=payload,content_type=Msg.STATS_UPDATE)):log.error("Failed to send stats update to world.")
Sends the buffered statistics to the world (async). The node calls it every Custom.SEND_STATS_EVERY seconds (30 by default). Outside a world it does nothing. It first calls collect_and_store_own_stats, takes the payload from Stats.get_payload_for_world() and sends it as a statistics update. An empty payload sends nothing and a failed send is logged.
defupdate_stats_view(self,received_view:dict,overwrite:bool=False)->None:"""Updates the stats view with the data received from the world. Args: received_view: The view dictionary received from the world. overwrite: Whether to overwrite existing entries. Defaults to False. """assertself.statsisnotNoneself.stats.update_view(received_view,overwrite)
Merges the statistics sent by the world (received_view) into the local view of stats. With overwrite=True the received entries replace the existing ones. The node calls it with the initial statistics when the agent joins a world and with every answer to ask_world_stats.
@actionasyncdefask_world_stats(self,filters:dict|None=None)->bool:"""Ask the world for stats: 'filters' is interpreted by the World subclass (method answer_stats_request); the answer arrives asynchronously as a STATS_RESPONSE and is merged into the agent's local stats view (see update_stats_view) (async)."""world_peer_id=self.node_conn.get_world_node_peer_id()ifworld_peer_idisNone:log.error("Not in a world: cannot ask stats")returnFalsereturnawaitself.node_conn.send(world_peer_id,channel_trail=None,content=filtersiffiltersisnotNoneelse{},content_type=Msg.STATS_REQUEST)
Action. Sends a statistics request to the world (async). filters (a dict, {} when None) is read by the answer_stats_request method of the world. The answer arrives later and the node merges it with update_stats_view. It returns the result of the send. Outside a world it returns False.
@actionasyncdefsuggest_role_to_world(self,agent:str|None,role:str)->bool:"""Suggests a role change for one or more agents to the world master. It iterates through the involved agents, checks if their current role differs from the suggested one, and sends a role suggestion message to the world master (async). Args: agent: The ID of the agent or a wildcard to suggest the role for. role: The new role to suggest (as a string). Returns: True if the suggestion was sent successfully, False otherwise. """log.misc("Suggesting role to world")agents=self.__involved_agents(agent)role_bits=(self.ROLE_STR_TO_BITS[role]>>2)<<2content=[]for_agentinagents:cur_role_bits=self.ROLE_STR_TO_BITS[self.all_agents[_agent].get_dynamic_profile()['connections']['role']]cur_role_bits=(cur_role_bits>>2)<<2ifcur_role_bits==role_bits:log.misc(f"Not suggesting to change the role of {_agent} "f"since it has already such a role")else:log.misc(f"Suggesting to change the role of {_agent} to {self.ROLE_BITS_TO_STR[role_bits]}")content.append({'peer_id':_agent,'role':role_bits})iflen(content)>0:world_peer_id=self.node_conn.get_world_node_peer_id()ifnot(awaitself.node_conn.send(world_peer_id,channel_trail=None,content=content,content_type=Msg.ROLE_SUGGESTION)):log.error("Failed to send role suggestion to the world")returnFalsereturnTrue
Action. Asks the world to change the role of one or more agents (async).
Argument
Type
Default
Meaning
agent
str, list or None
required
The agents (see the table of the agent argument).
role
str
required
The new role, for example "teacher". The comparison ignores the base part of the role (public agent, world agent or world master) and looks only at the role defined by the world.
An agent that already holds the custom role is skipped. The others go to the world in one role suggestion message. It returns False only when that send fails. A call with nothing to send returns True. The world decides whether to apply the change.
@actionasyncdefsuggest_badges_to_world(self,agent:str|None=None,score:float=-1.0,badge_type:str="completed",badge_description:str|None=None)->bool:"""Suggests one or more badges to the world master for specific agents. This is typically used to reward agents for completing tasks, such as for a competition. It sends a message with the badge details, including the score and type, to the world master (async). Args: agent: The ID of the agent or a wildcard for which to suggest the badge. score: The score associated with the badge. badge_type: The type of badge (e.g., 'completed'). badge_description: An optional description for the badge. Returns: True if the badge suggestion was sent successfully, False otherwise. """log.misc("Suggesting one or more badges to world")ifscore<0.:log.error("Invalid score (did you specify the 'score' argument? it must be positive)")returnFalseagents=self.__involved_agents(agent)world_peer_id=self.node_conn.get_world_node_peer_id()ifbadge_typenotinAgent.BADGE_TYPES:log.error(f"Unknown badge type: {badge_type}")returnFalselist_of_badge_dictionaries=[]forpeer_idinagents:list_of_badge_dictionaries.append({'peer_id':peer_id,'score':score,'badge_type':badge_type,'badge_description':badge_description,'agent_token':self.node_conn.get_last_token(peer_id)})ifnot(awaitself.node_conn.send(world_peer_id,channel_trail=None,content=list_of_badge_dictionaries,content_type=Msg.BADGE_SUGGESTIONS)):log.error("Failed to send badge suggestions to the world")returnFalseelse:returnTrue
Action. Suggests to the world a badge for one or more agents (async). A typical use is the end of a competition.
Argument
Type
Default
Meaning
agent
str, list or None
None
The agents to reward (see the table of the agent argument).
score
float
-1.0
The score of the badge. Because a negative score fails the action, the argument is required in practice.
badge_type
str
"completed"
One of BADGE_TYPES: "completed", "attended", "intermediate", "pro".
badge_description
str or None
None
A free description.
Each badge carries the peer id, the score, the type, the description and the last token of the agent. It returns True when the message reached the world.
@actionasyncdefsend(self,action_name:str|None=None,target:str|list[str]|None=None,action_kwargs:dict|None=None,streams:dict[str,str|list[str]]|list[str]|None=None,data_samples:list|dict[str,torch.Tensor|Image|str]|None=None,num_steps:int=-1,timeout:float=-1.,from_state:str|None=None,to_state:str|None=None,callback:str|None=None,forced_uuid:str|None="do_not_force",id:str|None="random",copy_sys:bool=False,wait_completion:bool=False,volatile:bool=False,num_samples_to_stream:int=-1,interaction:Interaction|None=None)->bool:"""Send an interaction request to one or more target agents (async). Accepts either a pre-built :class:`Interaction` object *or* raw arguments from which one will be created. Args: action_name: The action name (str) if building one from raw args. Ignored when a pre-built Interaction is provided. target: Peer ID (or wildcard such as ``"<valid_cmp>"``) of the target agent. It can be a list of agents. Ignored when a pre-built Interaction is provided. action_kwargs: Action arguments dict. Ignored when a pre-built Interaction is provided. streams: List of ``(stream_hash, num_samples)`` tuples (or just stream_hash if num_samples = 1). Ignored when a pre-built Interaction is provided. A lot of freedom here: stream_hash can be a net hash or a user hash. It is also fine to specify just the stream name or the stream group, then the user hash or the net hash will be automatically estimated. data_samples: List of actual data samples. Ignored when a pre-built Interaction is provided. It can also be a dictionary mapping one or more stream user hashes to data samples that will be artificially loaded on such streams, so that the 'streams' argument above is actually automatically populated. It can also be a string representing the payload that encodes a list of samples, if it was received from the net. num_steps: Number of steps the interaction spans (used when building from raw args). Ignored when a pre-built Interaction is provided. timeout: Maximum time for the interaction. Ignored when a pre-built Interaction is provided. from_state: Optional source state. Ignored when a pre-built Interaction provided. to_state: Optional destination state. Ignored when a pre-built Interaction provided. callback: Callback action (will be called when the interaction completes). forced_uuid: UUID of the interaction to explicitly force, use carefully. id: Optional ID of the interaction. Ignored when a pre-built Interaction is provided. copy_sys: True if the interaction must copy the last added stream data with system UUID to prepare initial data form the current interaction. wait_completion: If True, this action returns True if and only if we get a feed of interaction completion from all the involved agents (Default: False). volatile: If True, it is marked so that the recipient is asked to not send back any status about its completion. num_samples_to_stream: The maximum number of samples to stream. By default, no limits (the nun_steps is on the consumer side, the origin keeps streaming until timeout or completion). Default: -1 (no limits) interaction: The interaction triggered by the system to run this action (automatically set). Returns: True if at least of the target agents was reached. """# This action can only be triggered by the system or by the developer, no waysifinteractionisnotNoneandnotinteraction.is_system():returnFalseifwait_completionandvolatile:raiseGenException("You cannot wait for completion a volatile interaction (it will not return any updates)")ifwait_completionandinteractionisNone:raiseGenException("You cannot wait for completion by directly calling this action, without an interaction"" (the state of the action needs to be saved in the interaction object)")ifinteractionisNone:# This happens when calling 'send' from the code, e.g., inside another actionsystem_interaction=Nonefirst_run=Trueelse:system_interaction=interactionfirst_run=system_interaction.get_mark()isNoneiffirst_run:target=self.__involved_agents(target)sent_interaction=awaitself._send(None,action_name,target,action_kwargs,streams,data_samples,num_steps,timeout,from_state,to_state,callback,forced_uuid,id,copy_sys,volatile,num_samples_to_stream)ifwait_completion:assertsystem_interactionisnotNoneassertisinstance(system_interaction.action_ref,Action)system_interaction.action_ref.set_default_timeout()# This will make the action pedanticsystem_interaction.set_mark(sent_interaction)# First run, Saving the interaction that was sentreturnFalseelse:ifsystem_interaction:assertisinstance(system_interaction.action_ref,Action)ifnotsystem_interaction.action_ref.is_pedantic_by_default():system_interaction.action_ref.set_timeout(-1.)# Clear timeouts to ensure it is not pedanticreturnsent_interactionisnotNoneelse:assertsystem_interactionisnotNonesent_interaction=system_interaction.get_mark()# Loading the interaction that was sent at the first runsent_interaction:Interactionifsent_interaction.is_completed():ifnotsystem_interaction.action_ref.is_pedantic_by_default():system_interaction.action_ref.set_timeout(-1.)# Clear timeouts to ensure it is not pedanticreturnTrue# The mark will be automatically cleared by the Action classelse:returnFalse
Action. Sends an interaction to one or more agents (async). It is the one way to ask another agent to run an action (see Interactions).
Argument
Type
Default
Meaning
action_name
str or None
None
The action that the targets run, such as "process", "learn" or an action of a role file.
target
str, list[str] or None
None
The targets: a peer id, a node name, owner/name, a wildcard of the behavior ("<partner>") or a list. None and "<valid_cmp>" follow the table of the agent argument.
action_kwargs
dict or None
None
The arguments of the action on the target. Names reserved to the framework are refused.
streams
list[str], dict or None
None
The streams of this agent that carry the data. With a list the target decides where each stream goes. A dict with the keys stdin, stdtar, stdext and stdunk asks for inputs, learning targets or extras of the processor of the target. A stream can be given by its name, its group, its user hash or its net hash.
data_samples
dict, list or None
None
The data itself in place of streams. A dict maps a stream of this agent to one sample. The sample is written on that stream under the uuid of the interaction and reaches the targets through that stream. The dict is the recommended form.
num_steps
int
-1
How many steps the target runs with one sample per step. -1 gives one step to an interaction with data.
timeout
float
-1.0
The maximum life of the interaction in seconds. A non-positive value means 300 seconds.
from_state, to_state
str or None
None
The states of the behavior of the target where the interaction may start and where it should end.
callback
str or None
None
The name of an async method of this agent that the manager awaits once with interaction= when the interaction completes for any reason.
forced_uuid
str or None
"do_not_force"
A uuid to impose. Reserved for special cases.
id
str or None
"random"
The id of the interaction. The uuid is the id followed by _ and the peer id of this agent.
copy_sys
bool
False
After the send, copy onto the uuid of the interaction the last sample that each owned stream of the interaction holds under the system uuid (outside any interaction). The public behavior uses it to forward the last output of the processor.
wait_completion
bool
False
Only in a behavior: keep the action running until every target has completed the interaction.
volatile
bool
False
Ask the targets not to send a status back. The sent interaction as recorded by this agent completes with TIMEOUT at the next tick.
num_samples_to_stream
int
-1
The maximum number of samples that this agent streams for the interaction. -1 means no limit.
interaction
Interaction or None
None
Injected by the behavior. A developer never passes it.
The call works as follows.
It returns False when another peer requested the send. Only the agent itself (through a system interaction) or code can send.
It builds the interaction with this agent as requester and registers it with register_sent. Registration resolves targets and streams. A failure returns False.
It sends the interaction to each target and keeps the targets that the message reached. When no target was reached it unregisters the interaction and returns False.
Without wait_completion, a send that labels a transition is not retried after a False because the action clears its retry timeout. Only a retry timeout declared by the transition survives. With wait_completion=True the first call sends, stores the sent interaction in the mark of the system interaction, gives the action the default retry timeout (Custom.DEFAULT_TIMEOUT, 10 seconds) unless the transition declared one and returns False. Each later call returns True once the sent interaction is completed. Any completion reason counts (OK, REJECTED or TIMEOUT). A target that needs more time than the retry timeout makes the action fail. When the first call reached nobody, the next call sends again.
Two combinations are errors: (1) wait_completion=True with volatile=True and (2) wait_completion=True without an interaction (a call from code). The body raises GenException for both. The @action wrapper turns it into an error in the log and a False return value.
# From an action or a callback of the agent:ok=awaitself.send(action_name="process",target="ResNetAgent",data_samples={"proc_output_0":picture},callback="on_label")
@actionasyncdefall_sent_completed(self,action_name:str|None=None)->bool:"""True iff every sent interaction with the given `action_name` (or any, if None) has been completed by the IM. Negation of "are there any still-pending sends out there?". Useful as an HSM exit predicate after `send(action_name="...", ...)` was dispatched without `wait_completion` (async)."""forinterinself.im.sent.values():ifaction_nameisNoneorinter.action_name==action_name:ifnotinter.is_completed():returnFalsereturnTrue
Action. Returns True when no open sent interaction has the action name action_name. With action_name=None the check covers every open sent interaction. A behavior uses it as the exit condition after several send calls without wait_completion (async).
@actionasyncdefon_received(self,processing_fcn:str|None=None,data_type:str|None=None)->bool:"""Checks if any of the agents that received interactions from you have sent a stream sample back. Optionally, it can process the received data with a specified function (async). Args: processing_fcn: The name of a function to process the received data. data_type: Optional. A string with the type of data to consider (discarding the rest). Returns: True if at least one data sample was received, False otherwise. """_processing_fcn=Noneifprocessing_fcnisnotNone:ifhasattr(self,processing_fcn):_processing_fcn=getattr(self,processing_fcn)ifnotcallable(_processing_fcn):_processing_fcn=Noneif_processing_fcnisNone:log.error(f"Processing function not found: {processing_fcn}")got_something=Falsesent=list(self.im.sent.values())+list(self.im.sent_recently_completed)forinteractioninsent:uuid=interaction.uuidagents=interaction.targetforagentinagents:net_hash_to_stream_dict=self.find_streams(agent,"processor",discard_owned=True)forstream_dictinnet_hash_to_stream_dict.values():forstream_objinstream_dict.values():assertstream_obj.propsisnotNoneifdata_typeisnotNoneandstream_obj.props.data_type!=data_type:continueassertstream_obj.propsisnotNoneifnotstream_obj.props.is_public():data=stream_obj.get("received_some_asked_data",uuid=uuid)data_tag=stream_obj.get_tag(uuid=uuid)ifdataisnotNone:if_processing_fcnisNone:returnTrue# If some data arrived and no further processing is expected, just Trueelse:got_something=True_processing_fcn:Callable_processing_fcn(agent,stream_obj.props,data,data_tag)returngot_something
Action. Checks whether the answers to the requests of this agent have arrived (async). It scans the open sent interactions and the completed ones that are not yet drained. For each target it reads the processor streams of that target under the uuid of the interaction.
Argument
Type
Default
Meaning
processing_fcn
str or None
None
The name of a method of the agent. It is called as method(peer_id, props, data, data_tag) for each answer found. A name that is not a method is logged and treated as None.
data_type
str or None
None
Consider only the streams of this data type ("text", "img", "tensor", "file").
Without processing_fcn it returns True at the first answer found. With processing_fcn it calls the method for every answer and returns True when there was at least one. Reading does not consume the samples. The same answer is therefore found again at the next call until the interaction is drained. Because only private streams are scanned, the action always returns False on the public network.
@actionasyncdefprocess(self,interaction:Interaction|None=None)->bool:"""Runs one inference step: reads from stdin, calls the processor, and writes to stdout (async). Returns: True if the step ran successfully, False otherwise. """# Getting UUID of the interaction (used for tags and stdout)ifinteractionisnotNone:uuid=interaction.uuidelse:uuid=Custom.SYSTEM_INTERACTION_UUID# Possibly re-binding stdin to cope with human processor (it might also let the action fail, if needed)ifnotself.__rebind_stdin_if_human(interaction):returnFalse# Getting input data from the input streaminput_data=self.stdin.get(uuid=uuid,requested_by="process")# Use kwargsifinput_dataisNone:returnFalse# Getting data tagdata_tag=self.stdin.get_tag(uuid=uuid)ifdata_tagisNone:returnFalse# Post get actions to finalize what possibly started with the previous call to the rebind operation# (do this only after having received valid data from stdin)self.__rebind_stdin_if_human_finalizer(interaction)# Customizable input hooktry:input_data=self.hook_proc_tweak_inputs(input_data)ifinput_dataisNone:returnFalseexceptExceptionase:log.error(f"Error tweaking the processor inputs: {e}")returnFalse# Processing datatry:# A ModuleWrapper runs the module in its worker thread (the node keeps running meanwhile); any other# callable is called as it is. The steps of a multistep interaction run on the event loop instead (still# awaited: an async module, as the JS one of the AI mode in the browser, waits for its answer): its samples# come one per tick, and the ones arriving while the module runs in its worker would move stdin past the# samples not processed yet (skipped steps, lost answers). A long module goes to the worker all the same# (runs_long): a step of seconds would stop the node, Sessions included, and its samples come late anywayfirst,last=self.get_action_step()==0,self.is_last_action_step()ifisinstance(self.proc,ModuleWrapper):output_data=awaitself.proc.aforward(*input_data,first=first,last=last,offload=self.__offload_step())else:output_data=self.proc(*input_data,first=first,last=last)ifnotisinstance(output_data,tuple):output_data=(output_data,)exceptAnswerWithheldase:# What the processor produced was an answer to a form that does not honour it, and the agent# decided that nothing travels: the step fails quietly, the interaction that asked stays open,# and whoever is at the keyboard has already been told to answer againlog.debug(f"Processor output withheld: {e}")returnFalseexceptExceptionase:log.error(f"Error running the processor: {e}")returnFalse# Customizable output hooktry:output_data=self.hook_proc_tweak_outputs(output_data)exceptExceptionase:log.error(f"Error tweaking the processor outputs: {e}")returnFalse# Pushing output data to the output streamself.stdout.set(output_data,data_tag=data_tag,uuid=uuid)# Use kwargs for data_tag and uuidreturnTrue
Action. Runs one inference step of the processor (async). It is the action that a requester asks for with action_name="process" and that the public behavior runs on its own.
It reads the inputs from stdin under the uuid of the interaction (the system uuid when interaction is None) together with their tag. When the inputs or their tag are missing, it returns False. This is how a step waits for its data.
It calls the processor with first (step 0) and last (last step) flags. A ModuleWrapper is awaited through aforward. That method renders the interactive messages for the module and checks its answer to a form (see Interactive messages).
The outputs (wrapped in a tuple when needed) go through hook_proc_tweak_outputs and are written on stdout with the tag of the inputs under the same uuid. From there they travel to the requester.
An answer withheld by the interactive-message policy returns False without an error and leaves the interaction open. Any other exception of the processor is logged and returns False.
In a single-step interaction the processor runs in a worker thread of its wrapper (offloading) and the node keeps running during a long call. In a multi-step interaction it runs inline on the event loop to let each step take the sample of its own tick. A processor whose last call lasted at least Custom.OFFLOAD_SLOW_S seconds (0.5 by default, environment variable NODE_OFFLOAD_SLOW) is offloaded in multi-step interactions too. The wrapper never offloads in the browser or with NODE_OFFLOAD=0. Modules that echo their input or declare UAI_OFFLOAD = False are never offloaded either (see Agents).
For the agent of a person process does not call a model. The agent stores the request of a peer as the pending request of that peer until the person writes. In a world the pending request is stored under the peer id of the world whoever the requester is. A run on the initiative of the agent is refused while a request of the partner is pending. When the message of the person arrives on stdin, the pending request is cleared together with the input data of the interaction.
@actionasyncdeflearn(self,interaction:Interaction|None=None)->bool:"""Runs one learning step: first performs inference, then runs a backward pass (async). Returns: True if the learning step ran successfully, False otherwise. """ifnotself.is_human()and(self.proc_optsisNoneorself.proc_opts['optimizer']isNoneorself.proc_opts['losses']isNoneorlen(self.proc_opts['losses'])==0):log.misc(f"Current processor has no learning skills (or learning options not specified)")returnFalseassertinteractionisnotNone# Humans learn by themselves :)ifself.is_human():# Printinglog.debug(f"[learn] Step: {self.get_action_step()}, Tag: {self.stdin.get_tag()}, "f"Last Step: {interaction.num_steps-1}",rep=True),returnTrue# Inference firstifawaitself.process(interaction):# Getting the UUID of the interactionuuid=interaction.uuid# Getting input data from the input streamtarget_data=self.stdtar.get(uuid=uuid,requested_by="learn")# Use kwargs# Learning from the last performed inference and the current targets (inline in a multistep interaction,# as the inference in process)try:assertisinstance(self.proc,ModuleWrapper)loss_values=awaitself.proc.alearn_backward(target_data,offload=self.__offload_step())exceptExceptionase:log.error(f"Error while learning: {e}")returnFalse# Printinglog.user(f"Losses: {[x.item()forxinloss_values]}, "f"Step: {self.get_action_step()}, Tag: {self.stdin.get_tag()}, "f"Last Step: {interaction.num_steps-1}",rep=True),returnTrueelse:returnFalse
Action. Runs one learning step (async). It needs an interaction (a request or a behavior run with streams). It returns False for an artificial agent without optimizer or without losses in proc_opts.
It runs process on the interaction.
It reads the learning targets from stdtar under the uuid of the interaction.
It awaits alearn_backward of the wrapper. That call computes the losses of the outputs against the targets and makes one optimizer step. Offloading follows the rules of process.
It prints the loss values with the step and the tag.
It returns False when the inference fails or the backward raises. For the agent of a person it returns True without doing anything. See Learning over time.
@actionasyncdefrecord(self,interaction:Interaction|None=None,record_uuid:str|None="see_interaction_uuid")->bool:"""Records `interaction.num_steps` samples from the interaction's stdin stream group into a new owned `BufferedStream` group and exposes it via pubsub. Multistep by virtue of the interaction's `num_steps`; the framework's readiness gate already pauses execution on no-fresh-data cycles (async). Args: interaction: The driving interaction (auto-injected by the dispatch layer). record_uuid: Which `uuid` to read each source stream under. The default sentinel `"see_interaction_uuid"` means "use `interaction.uuid`" — the right choice when the source agent is a peer that knows about this interaction and publishes under it (process-style flow). Pass `record_uuid=None` (or any other explicit uuid string) when the source publishes under a different uuid — for instance when recording a world stream that has no per-interaction publish, in which case data lives in the source's `data_by_uuid[None]` slot. Triggered from HSM transits via: behav.add_transit("init", "next_state", action="record", args={"streams": {"stdin": ["<world>:group"]}, "num_steps": "<wildcard_or_int>", "record_uuid": None}) """ifinteractionisNone:returnFalseread_uuid=interaction.uuidifrecord_uuid=="see_interaction_uuid"elserecord_uuidk=self.get_action_step()ifk==0:dest={}fors_objininteraction.stream_proxy.values():ifnotisinstance(s_obj,Stream):continueasserts_obj.propsisnotNoneprops=s_obj.props.clone()props.set_group("recorded"+str(self._last_recorded_stream_num))dest[s_obj.props.get_name()]=BufferedStream(props=props)self._last_recorded_stream_dict=destdest=self._last_recorded_stream_dictfors_objininteraction.stream_proxy.values():ifnotisinstance(s_obj,Stream):continuex=s_obj.get(uuid=read_uuid,requested_by="record")ifxisNone:returnFalseasserts_obj.propsisnotNonedest_stream=dest[s_obj.props.get_name()]ifk%10==0:log.user(f"Recording Stream: {dest_stream.props.get_group()}.{dest_stream.props.get_name()}, "f"Step: {k}, Last: {interaction.num_steps-1}")dest_stream.set(x,k)ifself.is_last_action_step():fors_objindest.values():log.user(f"Recording Stream: {s_obj.props.get_name()}, Step: {k}, Last: {interaction.num_steps-1}")s_obj.is_read_only=Trues_obj.get(requested_by="send_stream_samples")self.add_streams(list(dest.values()),owned=True)self.update_streams_in_profile()awaitself.subscribe_to_pubsub_owned_streams()awaitself.send_profile_to_all()self._last_recorded_stream_num+=1self._last_recorded_stream_dict=NonereturnTrue
Action. Records the streams of an interaction into new owned buffered streams and offers them to the other agents (async). It is multi-step: the interaction gives the number of samples in num_steps.
Argument
Type
Default
Meaning
interaction
Interaction or None
None
The interaction that drives the recording (injected). Without it the action returns False.
record_uuid
str or None
"see_interaction_uuid"
The uuid under which the source streams are read. The default reads under the uuid of the interaction and suits a source that publishes for this interaction. None reads the data published outside any interaction (a world stream that broadcasts).
At step 0 it creates one BufferedStream per stream of the interaction with the same properties and the group recorded<n>. At each step it reads one sample of every source and stores it with the step index as tag. A missing sample returns False and the step is retried at the next tick. At the last step it marks the recorded streams read-only, adds them to the owned streams, writes them in the profile, opens their broadcast channels and sends the profile to every known agent. The counter n then advances.
@actionasyncdefshow(self,interaction:Interaction|None=None)->bool:"""A generic action that exploit the information in the interaction object for printing purposes, commonly used (by overriding it) to handle interaction-completion callbacks (async). Args: interaction: The interaction object that triggered this action. Returns: True all the times. """ifinteractionisNone:returnFalselog.debug(f"[show] The following interaction was completed: "f"{interaction.to_code_str(True,True)}")returnTrue
Action. Logs the completed interaction at debug level and returns True (async). It returns False without an interaction. It is the default callback of the public behavior and a starting point for a custom callback.
Engagement pairs an agent with others for a task inside a world. The requester finds candidates, offers engagement with send_engage and each candidate accepts with engage. An agent is available while it has no engaged agents and only an available agent accepts.
@actionasyncdefset_engaged_partner(self,agent:str|list[str]|set[str]|None,clear_found:bool=True)->bool:"""Virtually forces the engagement with a single agent (or a group of agents), clearing all existing engagements and results of previous find operations (async). Args: agent: The agent or the list of agents to engage (if None, we only clear the list of engaged partners). clear_found: Clears results of previously run find operations (True by default). Returns: True all the times. """ifclear_found:self._found_agents.clear()self._engaged_agents.clear()ifagentisnotNone:ifisinstance(agent,str):agent=[agent]forainagent:self._engaged_agents.add(a)self._available=len(self._engaged_agents)==0returnTrue
Action. Makes agent (a peer id, a list or a set) the only engaged agents (async). None only clears them. With clear_found=True (default) it also clears the found agents. The agent is available again when the result is empty. It returns True.
@actionasyncdefsend_engage(self)->bool:"""Offer engagement to the agents whose identifiers are in self._found_agents (async). Returns: True if engagement requests were successfully sent to at least one found agent, False otherwise. """iflen(self._found_agents)>0:log.misc(f"Sending engagement request to {', '.join([xforxinself._found_agents])}")my_role_str=self.node_profile.get_dynamic_profile()['connections']['role']ret=awaitself.send(target=self._found_agents,action_name="engage",action_kwargs={"sender_role":my_role_str},wait_completion=True,timeout=Custom.DEFAULT_TIMEOUT,interaction=self.im.get_current())ifret:marked=self.im.get_current().get_mark()# the exact interaction this "send" dispatchedengaged=marked.targetifmarkedisnotNoneelseNoneif(engagedisnotNone)andisinstance(engaged,list)andlen(engaged)>0:forenginengaged:self._engaged_agents.add(eng)# Marking this agent as not available since it engaged with another oneself._available=False# Removing the agent from the list of asked agentsself._found_agents.discard(eng)returnTrueelse:returnFalseelse:returnFalse
Action. Offers engagement to the found agents (async). It sends them an engage request with the role of this agent as sender_role and a timeout of Custom.DEFAULT_TIMEOUT (10 seconds). It then waits for completion as send with wait_completion=True does. It returns False while it waits. When the request has completed it moves every target of the request from the found agents to the engaged agents, marks the agent unavailable and returns True. Every target counts as engaged once the request completed for any reason. A target that refused is therefore counted too. The action needs a behavior and returns False when called from code.
@actionasyncdefengage(self,acceptable_role:str|None=None,sender_role:str|None=None,interaction:Interaction|None=None)->bool:"""Receive engagement from another agent whose authority is in the specified range (async). Args: acceptable_role: The role that the sender must have for engagement to be accepted. Defaults to None. sender_role: The role of the agent sending the engagement request. Defaults to None. interaction: The interaction triggered by the agent requesting engagement (automatically set). Returns: True if the engagement was successfully received and confirmed, False otherwise. """_requester=interaction.requesterifinteractionisnotNoneelseNonelog.misc(f"Getting engagement from {_requester}, whose role is {sender_role} (looking for {acceptable_role})")if_requesternotinself.world_agentsand_requesternotinself.world_masters:log.error(f"Unknown agent: {_requester}")returnFalseifsender_roleisNone:log.error(f"Unknown role of {_requester}")returnFalseifacceptable_roleisNone:log.error(f"Invalid acceptable role: {acceptable_role}")returnFalse# Confirmingifself._available:acceptable_role_int=self.ROLE_STR_TO_BITS[acceptable_role]if"~"notinacceptable_role:sender_role_int=(self.ROLE_STR_TO_BITS[sender_role]>>2)<<2else:sender_role_int=self.ROLE_STR_TO_BITS[sender_role]ifacceptable_role_int==sender_role_int:self._engaged_agents.add(_requester)# Marking this agent as not available since it engaged with another oneself._available=FalsereturnTrueelse:log.error(f"Cannot engage to {_requester}")returnFalseelse:log.error(f"Cannot engage to {_requester}")returnFalse
Action, request-only. Accepts an engagement offer (async).
Argument
Type
Default
Meaning
acceptable_role
str or None
None
The role that the requester must hold, written in the behavior of this agent. A plain custom role ("teacher") accepts a member or a master with that role. An augmented role ("world_master~teacher") must match exactly.
sender_role
str or None
None
The role of the requester as filled by send_engage.
interaction
Interaction or None
None
The request (injected).
It returns False in four cases: (1) the requester is not a member or master of the world, (2) either role is missing, (3) this agent is not available and (4) the roles do not match. Otherwise it adds the requester to the engaged agents, marks this agent unavailable and returns True.
@actionasyncdefsend_disengage(self,send_disconnection_too:bool=False)->bool:"""Ask for disengagement (async). Args: send_disconnection_too: Whether to send a disconnect-suggestion together with the disengagement. Returns: True if disengagement requests were successfully sent to at least one engaged agent, False otherwise. """iflen(self._engaged_agents)>0:log.misc(f"Sending disengagement request to {', '.join([xforxinself._engaged_agents])}")ifawaitself._send(target=list(self._engaged_agents),action_name="disengage",action_kwargs={"disconnect_too":send_disconnection_too}):self._engaged_agents.clear()# There is no "got_disengagement"returnTrueelse:log.error(f"Unable to send disengagement to {self._engaged_agents}")returnFalse
Action. Sends a disengage request to every engaged agent and clears the engaged agents (async). With send_disconnection_too=True the request asks the receivers to close the connection too. It returns False when there is no engaged agent or nobody was reached. The availability flag stays unchanged. To accept new engagements, call disengage_all or set_engaged_partner(None).
@actionasyncdefdisengage(self,disconnect_too:bool=False,interaction:Interaction|None=None)->bool:"""Get a disengagement request from an agent (async). Args: disconnect_too: Whether to disconnect the agent who sent the disengagement. interaction: The interaction triggered by the agent requesting disengagement (automatically set). Returns: True if the disengagement request was successfully processed, False otherwise. """_requester=interaction.requesterifinteractionisnotNoneelseNonelog.misc(f"Getting a disengagement request from {_requester}")if_requesternotinself.world_agentsand_requesternotinself.world_masters:log.error(f"Unknown agent: {_requester}")returnFalseif_requesternotinself._engaged_agents:log.error(f"Not previously engaged to {_requester}")returnFalseself._engaged_agents.discard(_requester)# Remove if presentifdisconnect_too:# Graceful disengage: carry WORLD_DISENGAGEMENT so __purge GOAWAYs the Session# and the remote sees Session.Closed instead of timing out via liveness (the# transport falls with the deferred settlement cut, after the farewell).awaitself.node_purge_fcn(_requester,reason=WORLD_DISENGAGEMENT)# Marking this agent as available if not engaged to any agentself._available=len(self._engaged_agents)==0returnTrue
Action, request-only. Accepts a disengagement request (async). The requester must be a member or master of the world and an engaged agent. The action removes the requester from the engaged agents. With disconnect_too=True the connection with the requester is closed with a world-disengagement reason. The agent becomes available when no engaged agent is left. It returns True when the checks pass and False otherwise.
@actionasyncdefdisengage_all(self)->bool:"""Disengage all the previously engaged agents (async). Returns: True if the disengagement procedure was successfully executed, False otherwise. """log.misc(f"Disengaging all agents")self._engaged_agents=set()# Marking this agent as availableself._available=TruereturnTrue
Action. Clears the engaged agents and marks the agent available (async). No message is sent. It returns True.
@actionasyncdefall_engagements_completed(self)->bool:"""Checks if all engagement requests that were sent have been confirmed. It returns True if there are no agents remaining in the `_found_agents` list, implying all have been engaged with or discarded (async). Returns: True if all engagements are complete, False otherwise. """returnlen(self._found_agents)==0
Action. Returns True when the found agents are empty (async). An empty group means that every candidate was engaged or dropped.
@actionasyncdeffind_agents(self,role:str|list[str],engage:bool=False,handshake_completed:bool=False)->bool:"""Locally searches through the agent's known peers (world and public agents) to find agents with a specific role. It populates the `_found_agents` set with the peer IDs of matching agents (async). Args: role: The role or list of roles to search for. handshake_completed: If True, only consider agents that have completed the handshake. engage: If you want to force the found agents to be the ones that you are engaged with. Returns: True if at least one agent is found, False otherwise. """log.misc(f"Finding an available agent whose role is {role}")self._found_agents.clear()self._found_agents.update(self.get_agents_by_role(role,handshake_completed=handshake_completed))log.debug(f"[find_agents] Found these agents: {self._found_agents}")ifengage:self._engaged_agents=copy.deepcopy(self._found_agents)returnlen(self._found_agents)>0
Action. Replaces the found agents with the known agents that hold role (async).
@actionasyncdefconnect_by_role(self,role:str|list[str],filter_fcn:str|None=None,accept_already_connected:bool=False)->bool:"""Finds and attempts to connect with agents whose profiles match a specific role. It can be optionally filtered by a custom function. It returns True if at least one valid agent is found (async). Args: role: The role or list of roles to search for. filter_fcn: The name of an optional filter function. accept_already_connected: If you want to consider the already connected peers as valid to make this method return True. Returns: True if at least one agent is found and a NEW connection request is made (and also if it was already established - if return_true_if_already_connected=True), False otherwise. """log.misc(f"Asking to get in touch with all agents whose role is {role}")self._found_agents.clear()role_list=roleifisinstance(role,list)else[role]at_least_one_is_valid=Falseforroleinrole_list:role=self.ROLE_STR_TO_BITS[role]found_addresses1,found_peer_ids1=self.node_conn.find_addrs_by_role(Agent.ROLE_WORLD_MASTER|role,return_peer_ids_too=True,discard_yourself=True)found_addresses2,found_peer_ids2=self.node_conn.find_addrs_by_role(Agent.ROLE_WORLD_AGENT|role,return_peer_ids_too=True,discard_yourself=True)found_addresses=found_addresses1+found_addresses2found_peer_ids=found_peer_ids1+found_peer_ids2iffilter_fcnisnotNone:ifisinstance(filter_fcn,str):ifhasattr(self,filter_fcn):filter_fcn=getattr(self,filter_fcn)else:log.error(f"Filter function not found: {filter_fcn}")returnFalseifcallable(filter_fcn):found_addresses,found_peer_ids=filter_fcn(found_addresses,found_peer_ids)log.misc(f"Found addresses ({len(found_addresses)}) with role: {role}")forf_addr,f_peer_idinzip(found_addresses,found_peer_ids):# is_connected reads pool residency, which a Session riding its reconnect# grace (up to 45s) still holds: the re-dial is deliberately skipped there,# RESUME on the surviving Session is the preferred recovery. Only the# terminal LOST evicts the pool and re-opens this dial path.ifnotself.node_conn.is_connected(f_peer_id):log.misc(f"Asking to get in touch with {f_peer_id}...")peer_id=awaitself.node_ask_to_get_in_touch_fcn(addresses=f_addr,public=False)ifpeer_idisnotNone:at_least_one_is_valid=Trueself._found_agents.add(peer_id)else:log.misc(f"Not-asking to get in touch with {f_addr}, "f"since I am already connected to the corresponding peer...")peer_id=f_peer_idifaccept_already_connected:at_least_one_is_valid=Trueself._found_agents.add(peer_id)log.misc(f"...returned {peer_id}")returnat_least_one_is_valid
Action. Connects to the peers of the world that hold a role (async). It clears the found agents and looks up the other members and masters with each role in the rendezvous of the world.
Argument
Type
Default
Meaning
role
str or list[str]
required
Custom role names.
filter_fcn
str, callable or None
None
A method name or a function f(addresses, peer_ids) -> (addresses, peer_ids) that filters the candidates. A name that is not an attribute returns False.
accept_already_connected
bool
False
Count the peers already connected as found.
For each candidate that is not connected it starts a connection and adds the peer to the found agents on success. A connection that is still within its reconnection grace period counts as connected and is not dialed again. It returns True when at least one peer was added.
@actionasyncdefconnect_to(self,peer_id:str)->bool:"""Gets in touch with a peer of the world, unless already connected to it (async). Args: peer_id: The peer to connect to. Returns: True if already connected or if getting in touch started, False otherwise. """addresses=self.node_conn.get_addrs(peer_id)ifnotself.node_conn.is_connected(peer_id):log.misc(f"Asking to get in touch with {peer_id}...")peer_id=awaitself.node_ask_to_get_in_touch_fcn(addresses=addresses,public=False)ifpeer_idisnotNone:returnTrueelse:returnFalseelse:log.misc(f"Not-asking to get in touch with {peer_id}, "f"since I am already connected to the corresponding peer...")returnTrue
Action. Starts a connection to peer_id in the world using the addresses that the connection pool knows (async). It returns True when the connection started or already existed. peer_id must be a peer id because the decorator does not resolve this argument name.
@actionasyncdefconnected(self,agent:str|list[str]|None=None,handshake_completed:bool=False)->bool:"""Checks if an agent is connected to us or not (async). Args: agent: The agent to check (or None if there are other already set engaged agents). handshake_completed: If True, only consider agents that have completed the handshake. Returns: True if all the requested agents are indeed connected. """# - if "agent" is a peer ID, the involved agents will be a list with one element.# - if "agent" is a known wildcard, as "<valid_cmp>", then involved agents will be self._valid_cmp_agents# - if "agent" is None, then the current agent in self._engaged_agents will be returnedinvolved_agents=self.__involved_agents(agent)iflen(involved_agents)==0:returnFalselog.misc(f"Checking if all these agents are connected to me now: {involved_agents}")foragentininvolved_agents:ifhandshake_completed:ifagentnotinself.all_agents:returnFalseelse:ifnotself.node_conn.is_connected(agent):returnFalsereturnTrue
Action. Returns True when every agent involved is connected (async). agent follows the table of the agent argument and an empty group returns False. With handshake_completed=True an agent counts only when it is in all_agents. Otherwise an open connection is enough.
@actionasyncdefdisconnected(self,agent:str|None=None,handshake_completed:bool=False)->bool:"""Checks if a specific set of agents (by ID or wildcard) are no longer connected to the agent. It returns False if any of the specified agents are still connected (async). Args: agent: The ID of the agent or a wildcard to check. handshake_completed: If True, only consider agents that have completed the handshake. Returns: True if all involved agents are disconnected, False otherwise. """# - if "agent" is a peer ID, the involved agents will be a list with one element.# - if "agent" is a known wildcard, as "<valid_cmp>", then involved agents will be self._valid_cmp_agents# - if "agent" is None, then the current agent in self._engaged_agents will be returned# With no argument, once the agents followed were removed (which empties the sets that# say whom we follow), the ones removed are checked.follows_nobody=agentisNoneandlen(self._engaged_agents)==0andlen(self._found_agents)==0iffollows_nobodyandlen(self.__removed_followed_agents)>0:involved_agents=list(self.__removed_followed_agents)else:ifagentisNone:self.__removed_followed_agents.clear()# We follow agents again, or nobodyinvolved_agents=self.__involved_agents(agent)iflen(involved_agents)==0:returnFalselog.misc(f"Checking if all these agents are not connected to me anymore: {involved_agents}")all_disconnected=Trueforagentininvolved_agents:ifhandshake_completed:ifagentinself.all_agents:all_disconnected=Falsebreakelse:ifagentinself.all_agentsorself.node_conn.is_connected(agent):all_disconnected=Falsebreakreturnall_disconnected
Action. Returns True when every agent involved is gone (async). agent follows the table of the agent argument and an empty group returns False. With handshake_completed=True an agent counts as gone when it is not in all_agents. Otherwise its connection must be closed too. A peer that leaves is removed from the found and engaged agents and the agent remembers it. With agent=None and both groups empty the action checks these remembered peers. A behavior can thus wait until all its partners have left.
@actionasyncdefdisconnect(self,agent:str)->bool:"""Disconnects an agent (async). Args: agent: The peer ID of the agent to disconnect. Returns: Always True. """log.misc(f"Disconnecting agent: {agent}")# Deliberate local teardown: GRACEFUL_SHUTDOWN so the remote sees a clean close.awaitself.node_purge_fcn(agent,reason=GRACEFUL_SHUTDOWN)# also calls remove_agent -> remove_streamsreturnTrue
Action. Closes the connection with agent gracefully and removes it with its streams (async). It returns True.
@actionasyncdefdisconnect_by_role(self,role:str|list[str],disengage_too:bool=False)->bool:"""Disconnects from all agents that match a specified role (async). It finds the agents and calls the node's purge function on each. Args: role: A string or list of strings representing the role(s) of agents to disconnect from. disengage_too: Also forces the sending of a disengagement (before disconnecting - default False). Returns: Always True. """log.misc(f"Disconnecting agents with role: {role}")ifdisengage_too:awaitself.send_disengage(send_disconnection_too=True)# Target only enrolled peers (handshake done), not every role match in the# rendezvous roster: disconnecting is meaningful only towards agents we are# actually connected to. Without this, in the template engage-by-role loop# this fires purge on not-yet-connected peers every behavior tick — a flood# of "close called in state known" no-ops plus a synchronous cgo# DisconnectFrom per peer, right on the main task's pump.ifawaitself.find_agents(role,handshake_completed=True):found_agents=copy.deepcopy(self._found_agents)foragentinfound_agents:# Role-based disconnect happens only in a world (roles exist only there), so# carry WORLD_DISENGAGEMENT, consistent with disengage.awaitself.node_purge_fcn(agent,reason=WORLD_DISENGAGEMENT)# Also calls remove_agent->remove_streamsreturnTrue
Action. Closes the connections with the connected agents that hold role (async). With disengage_too=True it first sends a disengagement with disconnection to the engaged agents. It replaces the found agents with the agents of that role whose handshake is complete and closes each connection with a world-disengagement reason. It returns True.
@actionasyncdefagents_are_waiting(self)->bool:"""Checks if there are any agents who have connected but have not yet been fully processed or added to the agent's known lists. This indicates that new agents are waiting to be managed (async). Returns: True if there are waiting agents, False otherwise. """# Session-era replacement for the old `_node_agents_waiting` dict: a found# agent is "waiting" while its per-peer Session exists but has not yet# reached ESTABLISHED (handshake in flight). The hosted entity only holds# `conn`, so this state is queried through NodeConn.is_peer_session_pending.waiting=[aforainself._found_agentsifself.node_conn.is_peer_session_pending(a)]log.misc(f"Current set of {len(waiting)} found agents with an in-flight (not yet "f"established) session: {waiting}")returnlen(waiting)>0
Action. Returns True when at least one found agent has a connection whose handshake is still in progress (async).
@actionasyncdefsend_subscribe(self,agent:str|None=None,stream_hashes:list[str]|None=None,unsubscribe:bool=False)->bool:"""Requests a remote agent or a group of agents to subscribe to or unsubscribe from a list of specified PubSub streams. It normalizes the stream hashes and sends an action request containing the stream properties (async). Args: agent: The target agent's ID or a wildcard. stream_hashes: A list of streams to subscribe to or unsubscribe from. unsubscribe: A boolean to indicate if it's an unsubscription request. Returns: True if the request was sent to at least one agent, False otherwise. """# - if "agent" is a peer ID, the involved agents will be a list with one element.# - if "agent" is a known wildcard, as "<valid_cmp>", then involved agents will be self._valid_cmp_agents# - if "agent" is None, then the current agent in self._engaged_agents will be returnedinvolved_agents=self.__involved_agents(agent)log.debug(f"[send_subscribe] Involved_agents: {involved_agents}")iflen(involved_agents)==0:log.debug(f"[send_subscribe] No involved agents, action ask_gen returns False")returnFalse# Create a copy of the stream hashes, normalizing them in the appropriate waystream_hashes_copy=self.__normalize_user_hash(stream_hashes)# Getting propertiesstream_owners=[]stream_props=[]foriinrange(len(stream_hashes_copy)):stream_dict=self.known_streams[stream_hashes_copy[i]]peer_id=DataProps.peer_id_from_net_hash(stream_hashes_copy[i])forname,stream_objinstream_dict.items():stream_owners.append(peer_id)stream_props.append(json.dumps(stream_obj.props.to_dict()))what="subscribe to"ifnotunsubscribeelse"unsubscribe from "log.misc(f"Asking {', '.join(involved_agents)} to {what}{stream_hashes}")interaction=awaitself._send(target=involved_agents,action_name="subscribe",action_kwargs={"stream_owners":stream_owners,"stream_props":stream_props,"unsubscribe":unsubscribe})ifinteractionisnotNone:correctly_asked=list(interaction.target)else:correctly_asked=[]log.debug(f"[send_subscribe] Overall, the action send_subscribe (unsubscribe: {unsubscribe})"f" will return {len(correctly_asked)>0}")returnlen(correctly_asked)>0
Action. Asks other agents to subscribe to (or leave) broadcast streams (async).
Argument
Type
Default
Meaning
agent
str, list or None
None
The agents to ask (see the table of the agent argument).
stream_hashes
list[str] or None
None
The groups as <peer_id>:<group> or net hashes. "<playlist>" means the current stream of the playlist.
unsubscribe
bool
False
Ask to leave instead of joining.
It sends a subscribe request with the owner and the properties of every stream of the groups. A group that the agent does not know makes the action fail. It returns True when at least one agent was reached.
@actionasyncdefsubscribe(self,stream_owners:list[str]|None=None,stream_props:list[str]|None=None,unsubscribe:bool=False,interaction:Interaction|None=None)->bool:"""Executes a subscription or unsubscription request received from another agent. It processes the stream properties, adds or removes the streams from the agent's known streams, and handles the underlying PubSub topic subscriptions (async). Args: stream_owners: A list of peer IDs who own the streams. stream_props: A list of JSON-serialized stream properties. unsubscribe: A boolean to indicate unsubscription. interaction: The interaction that triggered this subscription. Returns: True if the action is successful, False otherwise. """ifstream_propsisNoneorstream_ownersisNone:log.debug("[subscribe] Called without specifying required arguments")returnFalselog.debug(f"[subscribe] unsubscribe: {unsubscribe}, "f"stream_owners: {stream_owners}, stream_props: ... ({len(stream_props)} props)")# Building propertiesprops_dicts=[]props_objs=[]foriinrange(len(stream_props)):p_dict=json.loads(stream_props[i])props=DataProps.from_dict(p_dict)ifprops.is_pubsub():props_dicts.append(p_dict)props_objs.append(props)else:log.error(f"Expecting a pubsub stream, got a stream named {props.get_name()} "f"(group is {props.get_group()}), which is not pubsub")returnFalse# Adding new streams and subscribing (if compatible with our processor)something_good_happened=Falseforstream_owner,prop_dict,prop_objinzip(stream_owners,props_dicts,props_objs):ifnotunsubscribe:ifnot(awaitself.add_compatible_streams(peer_id=stream_owner,streams_in_profile=[prop_dict],buffered=False,public=False)):log.error(f"Unable to add a pubsub stream ({prop_obj.get_name()}) from agent {stream_owner}: "f"no compatible streams were found")else:something_good_happened=Trueelse:ifnot(awaitself.remove_streams(peer_id=stream_owner,name=prop_obj.get_name())):log.misc(f"Unable to unsubscribe from pubsub stream ({prop_obj.get_name()}) "f"of agent {stream_owner}")else:something_good_happened=Truereturnsomething_good_happened
Action, request-only. Executes a subscription request (async).
Argument
Type
Default
Meaning
stream_owners
list[str] or None
None
The owner of each stream.
stream_props
list[str] or None
None
The properties of each stream as JSON.
unsubscribe
bool
False
Leave the streams instead of joining.
interaction
Interaction or None
None
The request (injected).
Missing lists return False and so does a stream that is not a broadcast one. To join, it adds every stream compatible with the processor among the private streams and subscribes to it. To leave, it removes the streams. It returns True when at least one stream was added. When leaving it always returns False although the streams are removed. The removal method returns None and the action reads that as a failure.
A playlist is an ordered list of stream groups that an agent goes through, for example the lessons that a teacher streams one after the other. The playlist repeats repeat times and a pointer marks the current group. The stream reference "<playlist>" stands for the current group in evaluate, send_subscribe and in the stream arguments of actions.
@actionasyncdefset_pref_streams(self,net_hashes:list[str],repeat:int=1)->bool:"""Fills the agent's list of preferred streams (a playlist). It can repeat the playlist a specified number of times and resolves user-provided stream hashes to their full network hashes (async). Args: net_hashes: A list of stream hashes to add to the playlist. repeat: The number of times to repeat the playlist. Returns: Always True. """log.misc(f"Setting up a list of {len(net_hashes)} preferred streams")self._cur_preferred_stream=0self._preferred_streams=[]self._repeat=repeatforiinrange(0,self._repeat):fornet_hashinnet_hashes:# We are tolerating both peer_id:name_or_group and also peer_id::ps:name_or_groupcomponents=net_hash.split(":")peer_id=components[0]name_or_group=components[-1]net_hash_to_streams=self.find_streams(peer_id=peer_id,name_or_group=name_or_group)for_net_hashinnet_hash_to_streams.keys():self._preferred_streams.append(_net_hash)returnTrue
Action. Fills the playlist and puts the pointer on the first entry (async). Each item of net_hashes is <peer_id>:<name or group> (a net hash with ::ps: is accepted too) and adds every known group of that peer that matches. The whole list is repeated repeat times (default 1). An item that matches nothing adds nothing. It returns True.
@actionasyncdeffirst_pref_stream(self)->bool:"""Resets the internal pointer to the first stream in the list of preferred streams. This is useful for restarting a playback or processing loop (async). Returns: True if the move is successful, False if the list is empty. """iflen(self._preferred_streams)==0:log.error(f"Cannot move to the first stream because the list of preferred streams is empty")returnFalseself._cur_preferred_stream=0log.misc(f"Moving to the first preferred stream ({self._preferred_streams[self._cur_preferred_stream]})")returnTrue
Action. Moves the pointer to the first entry (async). It returns False for an empty playlist.
@actionasyncdefnext_pref_stream(self)->bool:"""Moves the internal pointer to the next stream in the list of preferred streams, which is often used for playlist-like operations. It wraps around to the beginning if it reaches the end (async). Returns: True if the move is successful, False if the list is empty. """iflen(self._preferred_streams)==0:log.error(f"Cannot move to the next stream because the list of preferred streams is empty")returnFalseself._cur_preferred_stream=(self._cur_preferred_stream+1)%len(self._preferred_streams)suffix=", warning: restarted"ifself._cur_preferred_stream==0else""log.misc(f"Moving to the next preferred stream ({self._preferred_streams[self._cur_preferred_stream]}){suffix}")returnTrue
Action. Moves the pointer to the next entry and back to the first after the last one (async). It returns False for an empty playlist.
@actionasyncdefcheck_pref_stream(self,what:str="last")->bool:"""Checks the position of the current preferred stream within the list. It can check if it's the first, last, or if it has completed a full round, among other checks (async). Args: what: A string specifying the type of check to perform (e.g., 'first', 'last', 'last_round'). Returns: True if the condition is met, False otherwise. """valid=['first','last','not_first','not_last','last_round','not_last_round','last_song','not_last_song']assertwhatinvalid,f"The what argument can only be one of {valid}"log.misc(f"Checking if the current preferred playlist item "f"(id: {self._cur_preferred_stream}) is the '{what}' one")ifwhat=="first":returnself._cur_preferred_stream==0elifwhat=="last":returnself._cur_preferred_stream==len(self._preferred_streams)-1elifwhat=="not_first":returnself._cur_preferred_stream!=0elifwhat=="not_last":returnself._cur_preferred_stream!=len(self._preferred_streams)-1elifwhat=="last_round":return(self._cur_preferred_stream+len(self._preferred_streams)//self._repeat>=len(self._preferred_streams))elifwhat=="not_last_round":return(self._cur_preferred_stream+len(self._preferred_streams)//self._repeat<len(self._preferred_streams))elifwhat=="last_song":ifself._repeat<=0orlen(self._preferred_streams)==0:returnFalsenum_streams_in_playlist=len(self._preferred_streams)//self._repeatreturn(self._cur_preferred_stream+1)%num_streams_in_playlist==0elifwhat=="not_last_song":ifself._repeat<=0orlen(self._preferred_streams)==0:returnFalsenum_streams_in_playlist=len(self._preferred_streams)//self._repeatreturn(self._cur_preferred_stream+1)%num_streams_in_playlist!=0else:returnFalse
Action. Tests the position of the pointer (async). Let L be the length of the repeated playlist, r the repetitions and n = L // r the entries of one round.
what
True when
"first", "not_first"
the pointer is (is not) on entry 0
"last", "not_last"
the pointer is (is not) on entry L - 1
"last_round", "not_last_round"
the pointer is (is not) in the last round, that is pointer + n >= L
"last_song", "not_last_song"
the pointer is (is not) on the last entry of a round. Both return False for an empty playlist.
Any other value fails the action. The default is "last".
@actionasyncdefevaluate(self,stream_hash:str,how:str,steps:int=100,re_offset:bool=False,agents_to_evaluate:str|list[str]|None=None)->bool:"""Evaluates the performance of agents that have completed a generation task. It compares the generated data from each agent with a local stream (which can be a ground truth or reference stream) using a specified comparison method (async). Args: stream_hash: The hash of the local stream to use for comparison. how: The name of the comparison method to use. steps: The number of steps to perform the evaluation. re_offset: A boolean to indicate whether to re-offset the streams. agents_to_evaluate: peer ID or list of peer IDs of agents that returned streams that were buffered, and that we are going to evaluate (default is None, meaning: "take the engaged agents"). Returns: True if the evaluation is successful, False otherwise. """ifself.buffer_generated_by_others=='none':log.error("Cannot evaluate if not buffering data generated by others")returnFalseifstream_hash=="<playlist>":iflen(self._preferred_streams)>self._cur_preferred_stream>=0:net_hash=self._preferred_streams[self._cur_preferred_stream]else:log.error("Invalid playlist index!")returnFalseelse:net_hash=self.user_stream_hash_to_net_hash(stream_hash)assertnet_hashisnotNone# Agents to evaluateifagents_to_evaluateisNone:agents_to_evaluate=self._engaged_agentselse:ifisinstance(agents_to_evaluate,str):agents_to_evaluate=[agents_to_evaluate]self._eval_results={}log.debug(f"[evaluate] Agents to evaluate: {agents_to_evaluate}")forpeer_idinagents_to_evaluate:ifpeer_idnotinself.last_buffered_peer_id_to_info:log.error(f"Missing buffered stream for {peer_id}, cannot evaluate it (skipping)")continuereceived_net_hash=self.last_buffered_peer_id_to_info[peer_id]["net_hash"]log.misc(f"Comparing {net_hash} with {received_net_hash}")eval_result,ret=self.__compare_streams(net_hash_a=net_hash,net_hash_b=received_net_hash,how=how,steps=steps,re_offset=re_offset)log.misc(f"Result of the comparison: {eval_result}")ifnotret:returnFalseelse:peer_id=DataProps.peer_id_from_net_hash(received_net_hash)self._eval_results[peer_id]=eval_resultreturnTrue
Action. Compares what other agents generated with a reference stream of this agent (async). The outputs of the other agents are read from their buffered copies. The action therefore needs buffer_generated_by_others other than "none".
Argument
Type
Default
Meaning
stream_hash
str
required
The reference group as <peer_id>:<group> or net hash. "<playlist>" means the current entry of the playlist.
how
str
required
The dissimilarity: "mse", "max" or "geq<x>" (see below).
steps
int
100
How many samples to compare.
re_offset
bool
False
Align the first tags of the two streams before comparing.
agents_to_evaluate
str, list[str] or None
None
The peers to evaluate. None means the engaged agents.
For each peer it compares the reference sample by sample along the tags with the last buffered copy of the processor output of that peer. A peer without a buffered copy is skipped with an error. Both streams must be buffered and compatible. The result is a dissimilarity in [0, +inf) averaged over steps. Lower is better.
how
Score of one pair of samples
"mse"
The mean squared error of the two tensors.
"max"
0 when the arguments of the maximum coincide and 1 when they differ.
"geq<x>"
The fraction of components on different sides of the threshold x = float(how[3:]). "geq0.5" uses 0.5. "geq-0.5" uses -0.5.
Three cases override how: (1) tensors of class indices (torch.long) score 1 - accuracy, (2) strings score 0 when equal and 1 when different and (3) tensors of different shapes score 1. A sample missing from the copy adds 1 (with "mse", 1.1 times the average so far). A sample of the copy that comes earlier than expected fails the action. The scores go to the evaluation results that compare_eval reads. It returns False at the first comparison that fails and True otherwise.
@actionasyncdefcompare_eval(self,cmp:str,thres:float,good_if_true:bool=True)->bool:"""Compares the results of a previous evaluation to a given threshold or finds the best result among all agents. It can check for minimum, maximum, or simple threshold-based comparisons, and it populates a list of 'valid' agents that passed the comparison (async). Args: cmp: The comparison operator (e.g., '<', '>', 'min'). thres: The threshold value for comparison. good_if_true: A boolean to invert the pass/fail logic. Returns: True if at least one agent passed the comparison, False otherwise. """assertcmpin["<",">",">=","<=","min","max"],f"Invalid comparison operator: {cmp}"assertthres>=0.orcmpin["min","max"],f"Invalid evaluation threshold: {thres} (it must be in >= 0.)"self._valid_cmp_agents=set()msgs=[]best_so_far=-1min_or_max=Noneleq_or_geq=Noneifcmpin["min","max"]:min_or_max="minimum"ifcmp=="min"else"maximum"leq_or_geq="<="ifcmp=="min"else">="iflen(self._eval_results)==0:log.user("No results to evaluate!")foragent_peer_id,eval_resultinself._eval_results.items():ifcmpnotin["min","max"]:log.misc(f"Checking if result {eval_result}{cmp}{thres}, for agent {agent_peer_id}")else:ifthres>=0:log.misc(f"Checking if result {eval_result} is the {min_or_max} so far, "f"only if {leq_or_geq}{thres}, for agent {agent_peer_id}")else:log.misc(f"Checking if result {eval_result} is the {min_or_max} so far, for agent {agent_peer_id}")ifeval_result<0.:log.user(f"Invalid evaluation result: {eval_result}")returnFalseowner_account=owner_handle(self.all_agents[agent_peer_id].get_static_profile())agent_name=self.all_agents[agent_peer_id].get_static_profile()['node_name']ifcmp!="min"andcmp!="max":outcome=Falseifcmp=="<"andeval_result<thres:outcome=Trueelifcmp=="<="andeval_result<=thres:outcome=Trueelifcmp==">"andeval_result>thres:outcome=Trueelifcmp==">="andeval_result>=thres:outcome=Trueifcmp[0]=="<":alias='error level'ifgood_if_trueelse'mark'else:alias='mark'ifgood_if_trueelse'error level'ifgood_if_true:ifoutcome:msgs.append(f"Agent {owner_account}/{agent_name} passed with {alias}{eval_result}/{thres}")self._valid_cmp_agents.add(agent_peer_id)else:msgs.append(f"Agent {owner_account}/{agent_name} did not pass, {alias}{eval_result}/{thres}")else:ifoutcome:msgs.append(f"Agent {owner_account}/{agent_name} did not pass, {alias}{eval_result}/{thres}")else:msgs.append(f"Agent {owner_account}/{agent_name} passed with {alias}{eval_result}/{thres}")self._valid_cmp_agents.add(agent_peer_id)else:if((cmp=="min"and(thres<0oreval_result<=thres)and(eval_result<best_so_farorbest_so_far<0))or(cmp=="max"and(thres<0oreval_result>=thres)and(eval_result>best_so_farorbest_so_far<0))):best_so_far=eval_resultself._valid_cmp_agents={agent_peer_id}msgs=[f"The best agent is {owner_account}/{agent_name}"]elifbest_so_far<0:msgs=[f"No best agent found for the considered threshold ({thres})"]formsginmsgs:log.user(msg)iflen(self._valid_cmp_agents)==0:# # cheating (hack):# self._valid_cmp_agents.append(agent_peer_id)# log.misc(", ".join(msgs))# return TruereturnFalseelse:returnTrue
Action. Selects the agents whose last evaluation passes a test and makes them the group "<valid_cmp>" (async).
Argument
Type
Default
Meaning
cmp
str
required
"<", ">", "<=", ">=", "min" or "max".
thres
float
required
The threshold. It must be non-negative with a comparison operator. With "min" and "max" a negative value means no threshold.
good_if_true
bool
True
With a comparison operator, False inverts the test: an agent passes when the comparison is false.
With a comparison operator every agent that passes enters the group. With "min" or "max" the group holds the single agent with the lowest or highest score within the threshold. The outcome of each agent is printed with its account and node name. It returns True when the group is not empty. A negative score or an unknown operator fails the action.
defresolve_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. """ifref=="<playlist>":returnself._preferred_streams[self._cur_preferred_stream] \
iflen(self._preferred_streams)>self._cur_preferred_stream>=0elseNoneelse:returnsuper().resolve_stream_ref(ref,public)
Resolves "<playlist>" to the net hash of the current entry of the playlist (None for an empty playlist) and every other reference as AgentBasics.resolve_stream_ref does.
defremove_peer_from_agent_status_attrs(self,peer_id:str)->None:"""Removes a peer from all agent-level status tracking sets (overrides parent) (async). Args: peer_id: The peer ID to remove from status tracking structures. """ifpeer_idin(self._engaged_agentsiflen(self._engaged_agents)>0elseself._found_agents):self.__removed_followed_agents.add(peer_id)super().remove_peer_from_agent_status_attrs(peer_id)self._available=len(self._engaged_agents)==0
Removes peer_id from the status attributes as the base method does. When the peer was among the engaged agents (or among the found agents when no agent was engaged) it is remembered for disconnected. The agent becomes available when no engaged agent is left.
defreset_agent_status_attrs(self)->None:"""Resets all agent-level status attributes to their initial values (overrides parent)."""super().reset_agent_status_attrs()# this sets status vars to [], {}, 0, 0., False, in function of their typeself.__removed_followed_agents=set()self._available=Trueself._repeat=1self._last_recorded_stream_num=1self._last_recorded_count=0
Resets the status attributes as the base method does and restores the values that are not zero at start. The agent becomes available, the playlist repeats once and the recording counter restarts from 1.