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.
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.
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>.
Peers: the profiles of the agents that this agent knows, split by network (public or world) and by kind (human or artificial).
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).
Interactions: the InteractionManager in im and four standard stream proxies, stdin, stdtar, stdext and stdout, that actions read and write.
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.
fromunaiverse.agentimportAgentclassEcho(Agent):defhook_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))returnoutputsagent=Echo(proc=lambdatext:text.upper(),proc_inputs=["text"],proc_outputs=["text"])
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 featuresself.behav:HybridStateMachine# HSM that describes the agent behavior in the private/world netself.behav_lone_wolf:HybridStateMachine# HSM that describes the agent behavior in public netself.behav_wildcards={}self.proc=procself.proc_updated_since_last_save=Falseself.proc_inputs=proc_inputsself.proc_outputs=proc_outputsself.proc_opts=proc_optsself.proc_last_inputs=Noneself.proc_last_outputs=Noneself.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 oneself.proc_optional_inputs:list[dict]|None=None# Must be None to be filled later: do not put an empty listself.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_labelsself.buffer_generated=buffer_generatedself.buffer_generated_by_others=buffer_generated_by_othersself.world_folder=world_folderself.policy_filter=policy_filterself.policy_filter_opts={}self.policy_filter_lone_wolf=policy_filter_lone_wolfself.policy_filter_lone_wolf_opts={}self.clock=clock# Backward compatibilityifself.buffer_generated_by_othersnotin{"one","all","none"}:raiseGenException("Param buffer_generated_by_others can be set to 'one', 'all', or 'none' only.")# Streamsself.known_streams={}# All streams that are known to this agent, organized by net hashself.owned_streams={}# The streams that are generated/offered by this agent, organized by net hashself.env_streams={}# The owned streams that come from environmental sources (e.g., a camera), by net hashself.proc_streams={}# The owned streams that are generated by the agent's processor, organized by net hashself.proc_in_streams={}# The owned streams that are input to the agent's processor, organized by net hashself.known_streams_by_user_hash={}# From peer_id:name to stream objectself.owned_streams_by_user_hash={}# From stream name to stream objectself.env_streams_by_user_hash={}# From peer_id:name to stream objectself.proc_streams_by_user_hash={}# From peer_id:name to stream objectself.proc_in_streams_by_user_hash={}# From peer_id:name to stream objectself.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 mastersself.all_agents:dict[str,NodeProfile]={}# ID -> profile (all types of agent)self.public_agents:dict[str,NodeProfile]={}# ID -> profile of agents talking in public mannerself.world_agents:dict[str,NodeProfile]={}# ID -> profile of all agents living in this worldself.world_masters:dict[str,NodeProfile]={}# ID -> profile of all master-agents living in this worldself.human_agents:dict[str,NodeProfile]={}# ID -> profile (human agents)self.artificial_agents:dict[str,NodeProfile]={}# ID -> profile (artificial agent)self.world_profile=Noneself.world_role_fsms=None# Dict role -> FSM (JSON string), delivered by the world's grant bundleself.is_world=False# If this instance is about a world: it will be discovered at creation timeself.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 agentsself.role_changed_by_world:bool=Falseself.received_address_update:bool=False# Internal properties about the way streams are usedself.last_buffered_peer_id_to_info={}# If buffering was turned onself.last_buffered_id_counter=0self.last_ref_uuid=Noneself.overridden_action_step=Noneself.locked_set_proc_input=False# Statsself.stats:Stats|None=None# Information inherited from the node that hosts this agentself.node_name="unk"self.node_conn=Noneself.node_profile=Noneself.node_ask_to_get_in_touch_fcn:Callable|None=Noneself.node_purge_fcn:Callable|None=Noneself.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 setself.compat_in_streams=[set()for_inrange(len(self.proc_inputs))] \
ifself.proc_inputsisnotNoneelse[]self.compat_out_streams=[set()for_inrange(len(self.proc_outputs))] \
ifself.proc_outputsisnotNoneelse[]# Interaction Manager, stdin/stdoutassertisinstance(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 droppedself.transfers:dict[tuple[str,str,int],dict]={}self.stdin=StreamProxy(replace_none_samples_with=[item["default_value"]ifitem["has_default"]elseNoneforiteminself.proc_optional_inputs])self.stdtar=StreamProxy()self.stdext=StreamProxy()self.stdout=StreamProxy()# Loading default public HSMifhasattr(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 packageself.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=Trueifself.world_folderisNone:raiseGenException("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).
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.
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).
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.
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.
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.
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).
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.
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.
The processor. After the constructor it is a ModuleWrapper around the module or callable given as proc (see unaiverse.modules.utils). Worlds have None.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
defset_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 referencesself.node_conn=connself.node_profile=profileself.node_name=profile.get_static_profile()['node_name']self.node_ask_to_get_in_touch_fcn=ask_to_get_in_touch_fcnself.node_purge_fcn=purge_fcnself.node_identity_dir=node_identity_dir# Checking if human, marking the nodeassertself.procisNoneorisinstance(self.proc,ModuleWrapper)# It is None in worlds!ifself.procisnotNoneandisinstance(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())fornet_hashinnet_hashes:ifnet_hash.startswith("<public_peer_id>")ornet_hash.startswith("<private_peer_id>"):stream_dict=self.known_streams[net_hash]forstream_objinstream_dict.values():self.add_stream(stream_obj,owned=True)# This will also re-add streams using the node clock# Removing place-holder streamsforpeer_idin["<public_peer_id>","<private_peer_id>"]:to_remove=[]fornet_hashinself.known_streams.keys():ifDataProps.peer_id_from_net_hash(net_hash)==peer_id:for_name,_streaminself.known_streams[net_hash].items():to_remove.append((net_hash,_name))# Removingfor(net_hash,name)into_remove:user_hash=DataProps.user_hash_from_net_hash(net_hash,name)delself.known_streams[net_hash][name]iflen(self.known_streams[net_hash])==0:delself.known_streams[net_hash]ifuser_hashinself.known_streams_by_user_hash:delself.known_streams_by_user_hash[user_hash]# Removing all the owned streams (environment and processor streams are of course "owned")ifnet_hashinself.owned_streams:ifnameinself.owned_streams[net_hash]:delself.owned_streams[net_hash][name]iflen(self.owned_streams[net_hash])==0:delself.owned_streams[net_hash]ifuser_hashinself.owned_streams_by_user_hash:delself.owned_streams_by_user_hash[user_hash]ifnet_hashinself.env_streams:ifnameinself.env_streams[net_hash]:delself.env_streams[net_hash][name]iflen(self.env_streams[net_hash])==0:delself.env_streams[net_hash]ifuser_hashinself.env_streams_by_user_hash:delself.env_streams_by_user_hash[user_hash]ifnet_hashinself.proc_streams:ifnameinself.proc_streams[net_hash]:delself.proc_streams[net_hash][name]iflen(self.proc_streams[net_hash])==0:delself.proc_streams[net_hash]ifuser_hashinself.proc_streams_by_user_hash:delself.proc_streams_by_user_hash[user_hash]ifnet_hashinself.proc_in_streams:ifnameinself.proc_in_streams[net_hash]:delself.proc_in_streams[net_hash][name]iflen(self.proc_in_streams[net_hash])==0:delself.proc_in_streams[net_hash]ifuser_hashinself.proc_in_streams_by_user_hash:delself.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.ifself.is_world:assertself.world_folderisnotNone# Check role-JSON files in the world folderrole_json_tracker=FileTracker(self.world_folder,ext=".json")# This usually does nothing, but if you like to dynamically create JSON files, overload this methodself.create_behav_files()# Loading and refactoring roles and behaviorsself.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 rolesself.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 outputself.create_proc_output_streams(buffered=self.buffer_generated)# Updating node profile by indicating the processor-related streamsself.update_streams_in_profile()# Blocking stdin for humansifhas_human_processor(self):self.set_default_stdin_binding(public=True)self.stdin.disable()self.set_default_stdin_binding(public=False)self.stdin.disable()returnTrue
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.
defget_connection_pool_manager(self)->NodeConn:"""Gets the connection pool manager (the NodeConn coordinator) of the node. Returns: The NodeConn of the node. """returnself.node_conn
defcreate_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 clockifself.proc_inputsisnotNone:fori,procsinenumerate(self.proc_inputs):assertnotisinstance(procs,str)procs.set_group("processor_in")# Adding default group info, forced, do not change this!# Creating the streamsforpropsinprocs.props:ifnotbuffered: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_idifstream.is_public()elseprivate_peer_idnet_hash=stream.net_hash(peer_id)ifstream.is_public():self.proc_in_net_hash['public']=net_hashelse:self.proc_in_net_hash['private']=net_hash# forcing the input stream to be compatible with proc inputsself.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.
defcreate_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 clockifself.proc_outputsisnotNone:fori,procsinenumerate(self.proc_outputs):assertnotisinstance(procs,str)procs.set_group("processor")# Adding default group info, forced, do not change this!# Creating the streamsforpropsinprocs.props:ifnotbuffered: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_idifstream.is_public()elseprivate_peer_idnet_hash=stream.net_hash(peer_id)ifstream.is_public():self.proc_net_hash['public']=net_hashelse: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.
defget_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. """returnself.proc_net_hash['public']ifpublicelseself.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.
defget_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. """returnself.proc_in_net_hash['public']ifpublicelseself.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.
defupdate_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 handleddynamic_profile=self.node_profile.get_dynamic_profile()if(hasattr(self,'proc_outputs')andhasattr(self,'proc_inputs')andself.proc_outputsisnotNoneandself.proc_inputsisnotNone):dynamic_profile['proc_outputs']= \
[dctfordinself.proc_outputsifhasattr(d,"to_list_of_dicts")fordctind.to_list_of_dicts()]# noqadynamic_profile['proc_inputs']= \
[dctfordinself.proc_inputsifhasattr(d,"to_list_of_dicts")fordctind.to_list_of_dicts()]# noqa# Adding the list of locally-created ("environmental") streams to the profilelist_of_props=[]public_peer_id,private_peer_id=self.get_peer_ids()fornet_hash,streams_dictinself.owned_streams.items():ifnet_hashnotinself.proc_streams.keys()andnet_hashnotinself.proc_in_streams.keys():if(DataProps.peer_id_from_net_hash(net_hash)==public_peer_idorDataProps.peer_id_from_net_hash(net_hash)==private_peer_id):forstreaminstreams_dict.values():list_of_props.append(stream.get_props().to_dict())# DataPropiflen(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.
asyncdefsend_profile_to_all(self)->None:"""Sends the agent's profile to all known agents (async)."""agents=list(self.all_agents.keys())forpeer_idinagents:log.misc(f"Sending profile to {peer_id}")ifnot(awaitself.node_conn.send(peer_id,channel_trail=None,content=self.node_profile.get_all_profile(),content_type=Msg.PROFILE)):ifself.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)awaitself.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.
asyncdefsubscribe_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)fornet_hashinlist(self.owned_streams.keys()):# A copy: the loop awaitsis_pubsub=Stream.is_pubsub_from_net_hash(net_hash)ifis_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 hashifnot(awaitself.node_conn.subscribe(peer_id,channel=net_hash)):log.error(f"Cannot open a channel for owned stream hash {net_hash}")returnFalsereturnTrue
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.
@staticmethoddefgenerate_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.
asyncdefadd_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.ifpeer_idinself.all_agents:ifprofile.get_static_profile()["node_type"]!=self.all_agents[peer_id].get_static_profile()["node_type"]:must_remove_agent_before_adding_again=Truedynamic_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']defcompare(A:list[dict]|None,B:list[dict]|None):set_A={json.dumps(d,sort_keys=True)fordin(Aor[])}set_B={json.dumps(d,sort_keys=True)fordin(Bor[])}returnset_A-set_B,set_B-set_Aadded,lost=compare(environmental_streams,_environmental_streams)if(add_env_streamsandlen(added)>0)orlen(lost)>0:must_remove_agent_before_adding_again=Trueadded,lost=compare(proc_streams,_proc_streams)if(add_proc_streamsandlen(added)>0)orlen(lost)>0:must_remove_agent_before_adding_again=Trueifmust_remove_agent_before_adding_again:# If the agent was already there, we remove it and add will add it again (in case of changes)awaitself.remove_agent(peer_id)# It has no effects if the agent is not existingelse:# If nothing structural changed, do not try to deal with streamsifadd_env_streams:add_env_streams=Falseifadd_proc_streams:add_proc_streams=False# Temporarily remove the agent from these dicts, since they depend on the role, that might have changedself.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]=profileifrole&1==self.ROLE_PUBLIC:self.public_agents[peer_id]=profilepublic=Trueelifrole&3==self.ROLE_WORLD_AGENT:self.world_agents[peer_id]=profilepublic=Falseelifrole&3==self.ROLE_WORLD_MASTER:self.world_masters[peer_id]=profilepublic=Falseelse:log.error(f"Cannot add agent with peer ID {peer_id} - unknown role: {role}")delself.all_agents[peer_id]returnFalse# Human or artificial?ifprofile.get_static_profile()["node_type"]==AgentBasics.HUMAN:self.human_agents[peer_id]=profileelse:self.artificial_agents[peer_id]=profile# Check compatibility of the streams owned by the agent we are adding with our-agent's processorifself.proc_outputsisnotNoneandself.proc_inputsisnotNone:# Check compatibility of the environmental streams of the agent we are adding with our-agent's processorenvironmental_streams=profile.get_dynamic_profile()['streams']if(add_env_streamsandenvironmental_streamsisnotNoneandnot(awaitself.add_compatible_streams(peer_id,environmental_streams,buffered=False,public=public,skip_pubsub=notadd_pubsub_streams))):awaitself.remove_agent(peer_id)# ClearingreturnFalse# Check compatibility of the generated streams of the agent we are adding with our-agent's processorproc_streams=profile.get_dynamic_profile()['proc_outputs']if(add_proc_streamsandproc_streamsisnotNoneandnot(awaitself.add_compatible_streams(peer_id,profile.get_dynamic_profile()['proc_outputs'],buffered=False,public=public,skip_pubsub=notadd_pubsub_streams))):awaitself.remove_agent(peer_id)# ClearingreturnFalselog.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 turnsifpublic:self.set_lone_wolf_partner(peer_id)returnTrue
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.
asyncdefremove_agent(self,peer_id:str)->None:"""Remove an agent (async). Args: peer_id: The unique identifier of the peer to remove. """ifpeer_idinself.all_agents:# Removing from agent listdelself.all_agents[peer_id]ifpeer_idinself.world_agents:delself.world_agents[peer_id]elifpeer_idinself.world_masters:delself.world_masters[peer_id]elifpeer_idinself.public_agents:delself.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(behavisnotNoneandnotself.is_human()andbehav.get_wildcards().get(Custom.PARTNER_WILDCARD)==peer_id):self.set_lone_wolf_partner(next(reversed(self.public_agents),None))ifpeer_idinself.artificial_agents:delself.artificial_agents[peer_id]elifpeer_idinself.human_agents:delself.human_agents[peer_id]ifpeer_idinself.proc_human_peer_id_to_interaction:delself.proc_human_peer_id_to_interaction[peer_id]# Clearing from the list of processor-input-compatible-streamsifself.compat_in_streamsisnotNone:fori,_inenumerate(self.compat_in_streams):to_remove=[]fornet_hash_nameinself.compat_in_streams[i]:ifDataProps.peer_id_from_net_hash(net_hash_name[0])==peer_id:to_remove.append(net_hash_name)fornet_hash_nameinto_remove:self.compat_in_streams[i].remove(net_hash_name)# Clearing from the list of processor-output-compatible-streamsifself.compat_out_streamsisnotNone:fori,_inenumerate(self.compat_out_streams):to_remove=[]fornet_hash_nameinself.compat_out_streams[i]:ifDataProps.peer_id_from_net_hash(net_hash_name[0])==peer_id:to_remove.append(net_hash_name)fornet_hash_nameinto_remove:self.compat_out_streams[i].remove(net_hash_name)# Clearing streams owned by the removed agent from the list of known streamsawaitself.remove_streams(peer_id)# Removing from the status variablesself.remove_peer_from_agent_status_attrs(peer_id)# Updating buffered stream indexifpeer_idinself.last_buffered_peer_id_to_info:delself.last_buffered_peer_id_to_info[peer_id]# Only if present# Resetting counter, if needediflen(self.last_buffered_peer_id_to_info)==0:self.last_buffered_id_counter=0# Clearing pending interactionsawaitself.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.
defremove_all_agents(self)->None:"""Remove all known agents."""# Clearing all agentsself.all_agents={}self.public_agents={}self.world_masters={}self.world_agents={}self.human_agents={}self.artificial_agents={}# Clearing the list of processor-output-compatible-streamsifself.compat_in_streamsisnotNoneandself.proc_inputsisnotNone:self.compat_in_streams=[set()for_inrange(len(self.proc_inputs))]ifself.compat_out_streamsisnotNoneandself.proc_outputsisnotNone:self.compat_out_streams=[set()for_inrange(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.
asyncdefclear_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 variablesself.reset_agent_status_attrs()# Clear/resetawaitself.__remove_all_world_private_streams()awaitself.__remove_all_world_related_agents()ifworld_peer_idinself.proc_human_peer_id_to_interaction:delself.proc_human_peer_id_to_interaction[world_peer_id]self.node_conn.reset_rendezvous_tag()awaitself.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.
defresolve_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_idifrefinself.all_agents:returnref# Search by owner/node_name (if only node_name is provided, assumes it is one of your agents)if'/'notinref:ref=build_unaid(self.get_profile(),ref)forpeer_id,profileinself.all_agents.items():ifbuild_unaid(profile)==ref:returnpeer_idreturnNone
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 accountpeer_id=self.resolve_agent_ref("alice/ResNetAgent")# a node of another account
defget_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. """returnself.node_name
Returns the name of the node (node_name). Before set_node_info the name is "unk".
defget_profile(self)->NodeProfile:"""Returns the profile of the node hosting this agent/world. Returns: The NodeProfile of this node. """returnself.node_profile
Returns the NodeProfile of the node. Before set_node_info it returns None.
defget_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()ifself.behaving_in_world():returnprivate_peer_idelse:returnpublic_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.
defget_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=Noneprivate_peer_id=Noneifself.node_profileisnotNone:dynamic_profile=self.node_profile.get_dynamic_profile()public_peer_id:str=dynamic_profile['peer_id']# Publicprivate_peer_id:str=dynamic_profile['private_peer_id']# Privatepublic_peer_id:str='<public_peer_id>'ifpublic_peer_idisNoneelsepublic_peer_idprivate_peer_id:str='<private_peer_id>'ifprivate_peer_idisNoneelseprivate_peer_idreturnpublic_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>".
defis_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. """ifself.node_profileisnotNone:returnself.node_profile.get_static_profile()["node_type"]==self.HUMANelse:returnFalse
Returns True when the node type in the profile is "human". It returns False before set_node_info.
defin_world(self)->bool:"""Check if the agent is currently operating within a 'world'. Returns: True if the agent is in a world, False otherwise. """ifself.node_profileisnotNone:returnself.ROLE_STR_TO_BITS[self.node_profile.get_dynamic_profile()['connections']['role']]&1==1else:returnFalse
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.
defbehaving_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. """assertself.behavisnotNonereturnself.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.
defget_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)<<2returnself.ROLE_BITS_TO_STR[base_role_int]ifbase_role_intinself.ROLE_BITS_TO_STRelseNone
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".
defget_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=roleifisinstance(role,list)else[role]searched_roles_int=set()forroleinrole_list:is_augmented="~"inrolerole_int=self.ROLE_STR_TO_BITS[role]ifnotis_augmented:forrole_prefix_intin{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=[]forrole_intinsearched_roles_int:_,_found_connected_peer_ids=self.node_conn.find_addrs_by_role(role_int,return_peer_ids_too=True)ifhandshake_completed:foragentin_found_connected_peer_ids:ifagentinself.all_agents:found_agents.append(agent)else:found_agents+=_found_connected_peer_idsreturnfound_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.
defget_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. """ifself.in_world():role_str=self.node_profile.get_dynamic_profile()['connections']['role']ifignore_base_role:role_str=role_str.split("~")[-1]ifnotreturn_int:returnrole_strelse:returnself.ROLE_STR_TO_BITS[role_str]else:returnNone
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.
defaccept_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 nonebase_role_to_behav=self.world_role_fsmsor{}ifnotbase_role_to_behavandself.world_profileisnotNone: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 mapifdefault_behavisnotNoneandisinstance(default_behav,str)andlen(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.
defevaluate_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 foundif(profile.get_dynamic_profile()['connections']['role']inself.ROLE_STR_TO_BITSandself.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]}")returnFalse# Cheater found# These are just examples: you are expected to reimplement this method in your custom agent fileif(role&1==self.ROLE_PUBLICandprofile.get_dynamic_profile()['guessed_location']=='Some Dummy Location, Just An Example Here'):returnFalseelif(role&3==self.ROLE_WORLD_MASTERandprofile.get_dynamic_profile()['guessed_location']=='Some Other Location, Just Another Example Here'):returnFalseelse:returnTrue
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.
@staticmethoddefbuild_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:vfork,vinAgentBasics.ROLE_BITS_TO_STR.items()}role_str_to_bits={k:vfork,vinAgentBasics.ROLE_STR_TO_BITS.items()}# Both Agent and World: Fusing basic roles and custom rolesiflen(custom_roles)>0:iflen(custom_roles)>30:# Safe value, could be increasedlog.critical("Maximum number of custom role overcame (max is 30)")fori,role_strinenumerate(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_introle_bits_to_str[role_int]=role_strAgentBasics.ROLE_STR_TO_BITS[role_str]=role_int# Both Agent and World: Augmenting rolesroles_not_to_be_augmented={AgentBasics.ROLE_PUBLIC,AgentBasics.ROLE_WORLD_AGENT,AgentBasics.ROLE_WORLD_MASTER}role_bits_to_str_original={k:vfork,vinrole_bits_to_str.items()}forrole_int,role_strinrole_bits_to_str_original.items():ifrole_intnotinroles_not_to_be_augmentedand"~"notinrole_str:forrole_base_intin{AgentBasics.ROLE_WORLD_AGENT,AgentBasics.ROLE_WORLD_MASTER}:augmented_role_int=role_base_int|role_intaugmented_role_str=role_bits_to_str[role_base_int]+"~"+role_strifaugmented_role_strnotinrole_str_to_bits:role_str_to_bits[augmented_role_str]=augmented_role_introle_bits_to_str[augmented_role_int]=augmented_role_strreturnrole_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.
defaugment_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, ...)"""ifrole_bits_to_strisNoneorrole_str_to_bitsisNone:role_bits_to_str,role_str_to_bits=AgentBasics.build_augmented_roles_dictionaries(self.CUSTOM_ROLES)self.ROLE_BITS_TO_STR.clear()fork,vinrole_bits_to_str.items():self.ROLE_BITS_TO_STR[k]=vself.ROLE_STR_TO_BITS.clear()fork,vinrole_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.
defload_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 folderifself.world_folderisnotNoneandself.is_world:# Guessing roles from the list of JSON fileslistdir=os.listdir(self.world_folder)# Do this only oncelistdir.sort()# Keep it stableself.CUSTOM_ROLES=[os.path.splitext(f)[0]forfinlistdirifos.path.isfile(os.path.join(self.world_folder,f))andf.lower().endswith(".json")]iflen(self.CUSTOM_ROLES)==0:raiseGenException(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)forfinlistdirifos.path.isfile(os.path.join(self.world_folder,f))andf.lower().endswith(".json")]# Loading Python files in the "world" foldertry:self.packed_agent_files=pack_py_files(collect_py_files(self.world_folder,exclude_dirs={'pdf','stats'}))exceptExceptionase:raiseGenException(f'Error while reading the agent-related python files in {self.world_folder} [{e}]')# Loading and refactoring behaviorsagent_files=unpack_py_files(self.packed_agent_files)# We keep the compatibility with the case of a single agent.pyiflen(self.CUSTOM_ROLES)>0:found=0found_agent_py=Falseforroleinself.CUSTOM_ROLES:forfile_nameinagent_files.keys():iffile_name=="agent.py":found_agent_py=Trueiffile_name==f"{role}.py":found+=1breakiffound!=len(self.CUSTOM_ROLES):iffound_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 bundleagent_files={f"{k}.py":code_contentforkinself.CUSTOM_ROLES}ifstats_sourceisnotNone:agent_files['stats.py']=stats_sourceelse:raiseGenException(f'Mismatching JSON-file roles and .py files in {self.world_folder}')forrole,default_behav_fileinzip(self.CUSTOM_ROLES,default_behav_files):dummy_agent_memory_finder=Nonetry:# Creating a dummy agent which supports the actions of the following state machinestry:dummy_agent,dummy_agent_memory_finder=load_agent_in_memory(agent_files,role,proc=None)loaded_roles=dummy_agent.CUSTOM_ROLESdummy_agent.CUSTOM_ROLES=self.CUSTOM_ROLESexceptExceptionase:raiseGenException(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 matterifloaded_rolesandset(loaded_roles)!=set(self.CUSTOM_ROLES):raiseGenException(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)exceptExceptionase:raiseGenException(f'Error while loading or handling 'f'behav file {default_behav_file} for role {role} [{e}]')# Refactoring and saving PDFtry:if(force_saveorbehav.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'))exceptExceptionase:raiseGenException(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 aboveifdummy_agent_memory_finderisnotNone: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"forroleinself.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}"ifkept_privateelse""))
Prepares the role files of a world. set_node_info calls it on worlds only.
It reads the role names from the *.json files of world_folder in alphabetical order. A folder without JSON files raises GenException.
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.
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/.
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.
defcreate_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.
defset_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)ifbehavisNoneorself.is_human():returnvalue=peer_idifpeer_idisnotNoneelseCustom.PARTNER_WILDCARDwildcards=behav.get_wildcards()ifCustom.PARTNER_WILDCARDnotinwildcardsorwildcards[Custom.PARTNER_WILDCARD]==value:returnbehav.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.
defadd_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.
asyncdefbehave(self)->None:"""Behave in the current environment, calling the state-machines of the public and private networks (async)."""assertisinstance(self.behav_lone_wolf,HybridStateMachine)assertisinstance(self.behav,HybridStateMachine)ifself.in_world():log.set_sub("prv")log.misc("Behaving (world)...")ifself.behavisNone:log.error("No behaviour specified")else:ifself.behav_lone_wolfisnotNone: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)awaitself.on_tick()awaitself.behav.act()self.behav.enable(False)log.set_sub("pub")log.misc("Behaving (public)...")ifself.behav_lone_wolfisNone:log.error("No behaviour specified")else:ifself.behavisnotNone: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)awaitself.behav_lone_wolf.act()self.behav_lone_wolf.enable(False)log.set_sub("gen")# Clear expired interactions at every clock cycle and notify originatorsawaitself.im.complete_expired()# Also drain recently completed interactions for status notificationcompleted=self.im.drain_completed()# Clear stream-expired dataself.im.clear_expired_stream_data()forinteractionincompleted:if(interaction.requesterisnotNoneandnotinteraction.volatileandinteraction.requesterinself.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()ifinteraction.requesterinself.public_agents:my_peer_id:str=my_public_peer_idelse:my_peer_id:str=my_private_peer_idret=awaitself.node_conn.send(interaction.requester,channel_trail=None,content=interaction.to_status_dict(status_generated_by=my_peer_id),content_type=Msg.INTERACTION_STATUS)ifnotretandself.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 timeoutlog.error(f"Interaction status to {interaction.requester} refused (send queue full)")elifnotret:log.error(f"Failed to send interaction status to peer {interaction.requester}, disconnecting it")assertself.node_purge_fcnisnotNone# Send-failure teardown: LOCAL_ERROR (best-effort GOAWAY on a possibly dead link).awaitself.node_purge_fcn(interaction.requester,reason=LOCAL_ERROR)
Runs one tick of the agent (async). The node calls it at every cycle.
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.
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.
It completes the expired interactions, drains the completed ones and drops the stream data of closed interactions.
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.
asyncdefon_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.
deflearn_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.
asyncdefset_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. """ifisinstance(policy_method_name_or_policy_fcn,str):policy_fcn=getattr(self,policy_method_name_or_policy_fcn,None)ifnotcallable(policy_fcn):returnFalsebehav=self.behavifnotpublicelseself.behav_lone_wolfassertisinstance(behav,HybridStateMachine)policy_fcn:Callable[[int,Interaction|None,list[Action],dict],tuple[int,Interaction|None]]|Nonebehav.set_policy(policy_fcn)returnTrueelifcallable(policy_method_name_or_policy_fcn):policy_fcn=policy_method_name_or_policy_fcnbehav=self.behavifnotpublicelseself.behav_lone_wolfassertisinstance(behav,HybridStateMachine)policy_fcn:Callable[[int,Interaction|None,list[Action],dict],tuple[int,Interaction|None]]|Nonebehav.set_policy(policy_fcn)returnTruereturnFalse
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.
defset_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. """ifisinstance(filter_method_name_or_policy_fcn,str):filter_fcn:Callable|None=getattr(self,filter_method_name_or_policy_fcn,None)ifnotcallable(filter_fcn):returnFalseifpublic:self.policy_filter_lone_wolf=filter_fcnassertisinstance(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']=Trueelse:self.policy_filter=filter_fcnassertisinstance(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']=FalsereturnTrueelifcallable(filter_method_name_or_policy_fcn):ifpublic:self.policy_filter_lone_wolf=filter_method_name_or_policy_fcnassertisinstance(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']=Trueelse:self.policy_filter=filter_method_name_or_policy_fcnassertisinstance(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']=FalsereturnTruereturnFalse
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.
defpolicy_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. """fori,actioninenumerate(actions_list):ifaction.is_high_priority:_list_of_requests=action.get_list_of_interactions()_selected_action_idx=i_selected_interaction=_list_of_requests.get_oldest_interaction() \
iflen(_list_of_requests)>0elseNonereturn_selected_action_idx,_selected_interactionfori,actioninenumerate(actions_list):_list_of_requests=action.get_list_of_interactions()iflen(_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_interactionfori,actioninenumerate(actions_list):ifaction.is_ready(consider_interactions=False):_selected_action_idx=i_selected_interaction=Nonereturn_selected_action_idx,_selected_interaction_selected_action_idx=-1_selected_interaction=Nonereturn_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.
The first high-priority action together with its oldest pending interaction (or None).
The first action with a pending request together with its oldest interaction.
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).
definject_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 objectinteraction=Interaction.from_dict(interaction_dict)# Markingpublic=senderinself.public_agents# Also register with the HSM for action selectionbehav=self.behav_lone_wolfifpublicelseself.behavassertisinstance(behav,HybridStateMachine)if(interaction.action_nameisnotNoneandlen(interaction.action_name)>0andnotbehav.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 InteractionManagerlog.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 lastifself.im.register_received(interaction,public)andpublic: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.
asyncdefreject_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_idifsenderinself.public_agentselsemy_private_peer_id,'uuid':interaction_dict.get('uuid')ifisinstance(interaction_dict,dict)elseNone,'status':InteractionStatus.COMPLETED.value,'completion_reason':CompletionReason.REJECTED.value,'destination_state':None,'data_tags':None}ifnot(awaitself.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.
defadd_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 hashassertstream.propsisnotNoneifnet_hashisNone:public_peer_id,private_peer_id=self.get_peer_ids()peer_id=public_peer_idifstream.is_public()elseprivate_peer_idnet_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 changeifnet_hashnotinself.known_streamsanduser_hashinself.known_streams_by_user_hash:raiseGenException(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 streamifnet_hashnotinself.known_streams:self.known_streams[net_hash]={}else:for_streaminself.known_streams[net_hash].values():public=_stream.get_props().is_public()pubsub=_stream.get_props().is_pubsub()ifpublicandnotstream.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{}ifpubsubandnotstream.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{}breakself.known_streams[net_hash][stream.get_props().get_name()]=stream# Overwrite if existingself.known_streams_by_user_hash[user_hash]=stream# Overwrite if existingifowned:is_proc_outputs_stream=Falseis_proc_inputs_stream=False# Adding an 'owned' processor output stream (i.e., the stream coming from OUR OWN processor)ifself.proc_outputsisnotNone:proc_outputs_name_and_group=set()forpropsinself.proc_outputs:assertnotisinstance(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())inproc_outputs_name_and_group:ifnet_hashnotinself.proc_streams:self.proc_streams[net_hash]={}self.proc_streams[net_hash][stream.get_props().get_name()]=streamself.proc_streams_by_user_hash[user_hash]=streamifstream.is_public():self.__proc_streams_by_user_hash_pub[user_hash]=streamelse:self.__proc_streams_by_user_hash_prv[user_hash]=streamis_proc_outputs_stream=True# Adding an 'owned' processor input stream (i.e., the stream entering OUR OWN processor)ifself.proc_inputsisnotNoneandnotis_proc_outputs_stream:proc_inputs_name_and_group=set()forpropsinself.proc_inputs:assertnotisinstance(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())inproc_inputs_name_and_group:ifnet_hashnotinself.proc_in_streams:self.proc_in_streams[net_hash]={}self.proc_in_streams[net_hash][stream.get_props().get_name()]=streamself.proc_in_streams_by_user_hash[user_hash]=streamifstream.is_public():self.__proc_in_streams_by_user_hash_pub[user_hash]=streamelse:self.__proc_in_streams_by_user_hash_prv[user_hash]=streamis_proc_inputs_stream=Trueifnet_hashnotinself.owned_streams:self.owned_streams[net_hash]={}self.owned_streams[net_hash][stream.get_props().get_name()]=streamself.owned_streams_by_user_hash[user_hash]=streamifnotis_proc_outputs_streamandnotis_proc_inputs_stream:ifnet_hashnotinself.env_streams:self.env_streams[net_hash]={}self.env_streams[net_hash][stream.get_props().get_name()]=streamself.env_streams_by_user_hash[user_hash]=streamifstream.is_public():self.__env_streams_by_user_hash_pub[user_hash]=streamelse:self.__env_streams_by_user_hash_prv[user_hash]=streamelse:# 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.ifstream.props.delta>=0.:stream.props.delta=-1.# Forcing# If needed, merging descriptor labels (attribute labels) and sharing them with all streamsifself.merge_flat_stream_labels:self.merge_flat_data_stream_props()returnself.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.
defadd_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 streamret=[]forstreaminstreams:stream_dict=self.add_stream(stream,owned,net_hash)iflen(stream_dict)==0:return[]ret.append(stream_dict)returnret
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.
asyncdefremove_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 removeto_remove=[]fornet_hashinself.known_streams.keys():ifDataProps.peer_id_from_net_hash(net_hash)==peer_id:for_name,_streaminself.known_streams[net_hash].items():ifnameisNoneorname==_name:to_remove.append((net_hash,_name))# Removingfor(net_hash,name)into_remove:ifnotowned_tooandnet_hashinself.owned_streams:continuegroup=DataProps.name_or_group_from_net_hash(net_hash)user_hash=DataProps.user_hash_from_net_hash(net_hash,nameifnameisnotNoneelsegroup)delself.known_streams[net_hash][name]iflen(self.known_streams[net_hash])==0:delself.known_streams[net_hash]ifuser_hashinself.known_streams_by_user_hash:delself.known_streams_by_user_hash[user_hash]# Unsubscribing to pubsubifDataProps.is_pubsub_from_net_hash(net_hash):ifpeer_id!="<private_peer_id>"andpeer_id!="<public_peer_id>":ifnot(awaitself.node_conn.unsubscribe(peer_id,channel=net_hash)):# log.error(f"Failed in unsubscribing from pubsub, peer_id: {peer_id}, channel: {net_hash}")passelse: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")ifnet_hashinself.owned_streams:ifnameinself.owned_streams[net_hash]:delself.owned_streams[net_hash][name]iflen(self.owned_streams[net_hash])==0:delself.owned_streams[net_hash]ifuser_hashinself.owned_streams_by_user_hash:delself.owned_streams_by_user_hash[user_hash]ifnet_hashinself.env_streams:ifnameinself.env_streams[net_hash]:delself.env_streams[net_hash][name]iflen(self.env_streams[net_hash])==0:delself.env_streams[net_hash]ifuser_hashinself.env_streams_by_user_hash:delself.env_streams_by_user_hash[user_hash]ifnet_hashinself.proc_streams:ifnameinself.proc_streams[net_hash]:delself.proc_streams[net_hash][name]iflen(self.proc_streams[net_hash])==0:delself.proc_streams[net_hash]ifuser_hashinself.proc_streams_by_user_hash:delself.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.
defremove_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). """ifnotowned_too:self.known_streams={k:vfork,vinself.owned_streams.items()}self.known_streams_by_user_hash={k:vfork,vinself.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.
defget_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. """ifpeer_idisNone:peer_id=self.get_peer_id()user_hash=DataProps.build_user_hash(peer_id,name_or_group)ifuser_hashinself.known_streams_by_user_hash:returnself.known_streams_by_user_hash[user_hash]else:streams=self.get_streams(group_name=name_or_group,peer_id=peer_id)ifstreamsisnotNoneandlen(streams)>0:ifdata_typeisnotNone:forstreaminstreams:assertstream.propsisnotNoneifstream.props.data_type==data_type:returnstreamreturnNoneeliflen(streams)==1:returnstreams[0]else:returnNone# Ambiguous caseelse:returnNone
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 streamanswer=self.get_stream("processor",peer_id=peer,data_type="text")
defget_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. """ifpeer_idisNone:peer_id=self.get_peer_id()net_hash_ps=DataProps.build_net_hash(peer_id,pubsub=True,name_or_group=group_name)ifnet_hash_psinself.known_streams:returnlist(self.known_streams[net_hash_ps].values())else:net_hash_dm=DataProps.build_net_hash(peer_id,pubsub=False,name_or_group=group_name)ifnet_hash_dminself.known_streams:returnlist(self.known_streams[net_hash_dm].values())else:returnNone
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.
deffind_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={}fornet_hash,streams_dictinself.known_streams.items():ifdiscard_ownedandnet_hashinself.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)ifpeer_id==_peer_id:ifname_or_groupisNoneorname_or_group==_name_or_group:ret[net_hash]=streams_dictelse:for_name,_streaminstreams_dict.items():ifname_or_group==_name:ifnet_hashnotinret:ret[net_hash]={}ret[net_hash][name_or_group]=_streamreturnret
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:
defget_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=[]forpeer_id,profileinself.all_agents.items():ifprofile.get_static_profile()['node_name']==agent_name:net_hash_to_stream_dict=self.find_streams(peer_id,name_or_group="processor")fornet_hash,streams_dictinnet_hash_to_stream_dict.items():forstream_name,stream_objinstreams_dict.items():data_list.append(stream_obj.get())returndata_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.
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. """# If already a valid user hashifrefinself.known_streams_by_user_hash:returnref# If already a valid net hashifrefinself.known_streams:returnref# If it is formatted as a net hash, but was not found, then nothing to doifStream.is_net_hash(ref):returnNone# By default, we will try to resolve by looking at owned (first) and other (then) streamssearch_owned_streams=Truesearch_other_streams=Trueowner=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 lookifStream.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=notsearch_owned_streamsowner=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)ifsearch_owned_streams:foruser_hash,stream_objinself.owned_streams_by_user_hash.items():ifpublicandnotstream_obj.is_public():continueifref==Stream.name_from_user_hash(user_hash):returnuser_hashfornet_hash,stream_dictinself.owned_streams.items():iflen(stream_dict)==0:continueifpublicandnotnext(iter(stream_dict.values())).is_public():continueifref==Stream.name_or_group_from_net_hash(net_hash):returnnet_hash# Search all streams thenifsearch_other_streams:foruser_hash,stream_objinself.known_streams_by_user_hash.items():ifpublicandnotstream_obj.is_public():continueifownerisnotNoneandDataProps.peer_id_from_user_hash(user_hash)!=owner:continueifref==Stream.name_from_user_hash(user_hash):returnuser_hashfornet_hash,stream_dictinself.known_streams.items():iflen(stream_dict)==0:continueifpublicandnotnext(iter(stream_dict.values())).is_public():continueifownerisnotNoneandDataProps.peer_id_from_net_hash(net_hash)!=owner:continueifref==Stream.name_or_group_from_net_hash(net_hash):returnnet_hashreturnNone
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>.
defuser_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. """ifuser_stream_hashisNone:returnNoneif"::"inuser_stream_hash:returnuser_stream_hash# It was already finecomponents=user_stream_hash.split(":")peer_id=components[0]name=components[-1]fornet_hash,stream_dictinself.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_idand_name_or_group==name:returnnet_hashfor_nameinstream_dict.keys():if_peer_id==peer_idand_name==name:returnnet_hashreturnNone
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.
asyncdefadd_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=[]ifadd_all:# This is the case in which we add all streams, storing all pairs (DataProps, net_hash)forjinstreams_in_profile:jj=DataProps.from_dict(j)if(public==jj.is_public()and(notjj.is_pubsub()ornotskip_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 streamsadded_net_hash_to_prop_name={}# Find streams that are compatible with our 'proc_inputs'assertself.proc_inputsisnotNonefori,in_procinenumerate(self.proc_inputs):assertnotisinstance(in_proc,str)forjinstreams_in_profile:jj=DataProps.from_dict(j)if(public==jj.is_public()andin_proc.is_compatible(jj)and(notjj.is_pubsub()ornotskip_pubsub)):net_hash=jj.net_hash(peer_id)ifnet_hashnotinadded_net_hash_to_prop_name:added_net_hash_to_prop_name[net_hash]=set()ifjj.namenotinadded_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 listself.compat_in_streams[i].add((net_hash,jj.get_name()))# Find streams that are compatible with our 'proc_outputs'has_cross_entropy=[]assertself.proc_outputsisnotNoneassertself.proc_optsisnotNoneif'losses'inself.proc_opts:foriinrange(0,len(self.proc_outputs)):ifself.proc_opts['losses'][i]isnotNoneand \
(self.proc_opts['losses'][i]==torch.nn.functional.cross_entropyorisinstance(self.proc_opts['losses'][i],torch.nn.CrossEntropyLoss)or"cross_entropy"inself.proc_opts['losses'][i].__name__):has_cross_entropy.append(True)else:has_cross_entropy.append(False)fori,out_procinenumerate(self.proc_outputs):out_proc:StreamTypeforjinstreams_in_profile:jj=DataProps.from_dict(j)if((public==jj.is_public()and(out_proc.is_compatible(jj)or(jj.is_tensor_target_id()andhas_cross_entropy[i])))and(notjj.is_pubsub()ornotskip_pubsub)):net_hash=jj.net_hash(peer_id)ifnet_hashnotinadded_net_hash_to_prop_name:added_net_hash_to_prop_name[net_hash]=set()ifjj.namenotinadded_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 listself.compat_out_streams[i].add((net_hash,jj.get_name()))net_hashes_to_subscribe=set()# For each compatible stream found...for(props,net_hash)inadded_streams:# Check if it is a new stream or a data stream to add to an already known streamalready_known_stream=net_hashinself.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())ifknownisnotNoneandisinstance(known,BufferedStream)==buffered:known_props,new_props=known.get_props().to_dict(),props.to_dict()known_props.pop('delta')new_props.pop('delta')ifknown_props==new_props:continue# Creating the stream objectifnotbuffered: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 subscribeifprops.is_pubsub()andnotalready_known_stream:net_hashes_to_subscribe.add(net_hash)# Opening PubSubsfornet_hashinnet_hashes_to_subscribe:log.misc(f"Opening channel for the not-owned but processor-compatible stream {net_hash}")ifnot(awaitself.node_conn.subscribe(peer_id,channel=net_hash)):log.error(f"Error subscribing to {net_hash}")returnFalsereturnTrue
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.
defmerge_flat_data_stream_props(self)->None:"""Merge the labels of the descriptor components, across all streams, sharing them."""# Set of pivot labelssuperset_labels=[]# Checking the whole list of streams, but considering only the ones with generic data, flat, and labelsconsidered_streams=[]forstream_dictinself.owned_streams.values():forstreaminstream_dict.values():# Skipping not flat, or not generic, or unlabeled streamsifnotstream.props.is_flat_tensor_with_labels():continue# Saving list of considered streamsconsidered_streams.append(stream)# Adding the current stream-labels to the pivot labelsforlabelinstream.props.tensor_labels:iflabelnotinsuperset_labels:superset_labels.append(label)# Telling each stream in which positions their labels fall, given the pivot labelsforstreaminconsidered_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!)ifisinstance(stream,BufferedStream):assertstream.propsisnotNoneforuuidinstream.data_buffer_by_uuid.keys():fordatainstream.data_buffer_by_uuid[uuid]:data.data=stream.props.clear_label_adaptation(data.data)# Updating labelsassertstream.propsisnotNoneandisinstance(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 labelsifisinstance(stream,BufferedStream):assertstream.propsisnotNoneforuuidinstream.data_buffer_by_uuid.keys():fordatainstream.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.
defget_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 herenet_hash=DataProps.normalize_net_hash(net_hash)added_data=[]log.misc(f"Got a stream sample from {net_hash}...")ifsample_dictisNone:log.error(f"Invalid sample (expected a dictionary, got None)")returnadded_dataifnet_hashinself.known_streams:forname,data_and_tag_and_uuidinsample_dict.items():if('data'notindata_and_tag_and_uuidor'data_tag'notindata_and_tag_and_uuidor'data_uuid'notindata_and_tag_and_uuid):log.error(f"Invalid sample in data stream named {name} (missing one or more keys)")continuedata,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 orderskip=Falsereason=Nonehas_data=Falseifnotskip:ifdataisNone:skip=Truereason="Data is None"ifnotskip:ifnet_hashnotinself.known_streams:skip=Truereason=f"The net hash {net_hash} is not a known stream hash"ifnotskip:ifnamenotinself.known_streams[net_hash]:skip=Truereason=(f"The data stream named {name} is not present for net hash {net_hash} "f"(names: {list(self.known_streams[net_hash].keys())})")ifnotskip: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)ifhas_data:assertdata_tagisnotNoneasserthas_this_data_tagisnotNoneifdata_tag<=has_this_data_tag:skip=Truereason=(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...ifnotskip:log.misc(f"Accepted sample named {name}: tag={data_tag}, uuid={data_uuid}"+(": it is a new UUID"ifnothas_dataelse""))# 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 returnadded_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 againstifisinstance(data,str)andhas_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 processorif(self.buffer_generated_by_others!="none"andDataProps.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 counterclear=Falseif_peer_idinself.last_buffered_peer_id_to_info:ifself.buffer_generated_by_others=="one":_buffered_uuid_to_id=self.last_buffered_peer_id_to_info[_peer_id]["uuid_to_id"]ifdata_uuidnotin_buffered_uuid_to_id:_id=next(iter(_buffered_uuid_to_id.values()))_buffered_uuid_to_id.clear()_buffered_uuid_to_id[data_uuid]=_idclear=Trueelse: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"]ifdata_uuidnotin_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 beforeif_net_hashnotinself.known_streams:log.debug(f"[get_stream_sample] Adding a new buffered stream to the list of known "f"streams, hash: {_net_hash}")forstream_objin_processor_stream_dict.values():# Same properties of the stream of the processor of the source agentprops=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 streamself.add_stream(BufferedStream(props=props),owned=False,net_hash=_net_hash)# Saving hash of the new buffered streamself.last_buffered_peer_id_to_info[_peer_id]["net_hash"]=_net_hashelse:ifclear:forstream_objinself.known_streams[_net_hash].values():stream_obj.clear_buffer()# Saving sampleself.known_streams[_net_hash][_name].set(data,data_tag,uuid=data_uuid)ifself.known_streams[_net_hash][_name].get_interaction(data_uuid)isNone:interaction=self.known_streams[net_hash][name].get_interaction(data_uuid)ifinteractionisnotNone: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}")ifnet_hashnotinself.known_streams:log.debug(f"[get_stream_sample] "f"The net hash {net_hash} was not found in the set of known streams")else:ifnamenotinself.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)}")returnadded_data# If this stream is not known at all...else:log.misc(f"Skipping sample from {net_hash} (data stream is unknown)")# Miscreturnadded_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.
asyncdefsend_stream_samples(self)->None:"""Collect and send stream samples from all owned streams to appropriate recipients (async)."""# For each owned net hash...fornet_hash,streams_dictinlist(self.owned_streams.items()):# A copy: the loop awaits# Skipping our processor inputifDataProps.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 sendvalid_samples_count={}# For each stream within this net hash...forname,streaminstreams_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'sifstream.is_pubsub()andnotisinstance(stream,BufferedStream):uuids=list(uuids)+[uforuinstream.get_data_uuids()ifuisnotNoneandunotinuuids]# 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 casesifstream.is_pubsub()andstream.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)foruuidinuuids:interaction=stream.get_interaction(uuid)recipient=None# Invalid agent? Skip!ifnotstream.is_pubsub():assertinteractionisnotNonerecipient=self.im.get_recipients(interaction)iflen(recipient)==0:continue# Skipping system-triggered interactionsifrecipient==[Custom.SYSTEM_INTERACTION_LABEL]:continue# Skipping interactions that already provided all the required dataifinteractionisnotNone:ifinteraction.all_samples_streamed():continue# Get datadata=stream.get(requested_by="send_stream_samples",uuid=uuid)data_tag=stream.get_tag(uuid=uuid)assertstream.propsisnotNonelog.debug(f"[send_stream_sample] data from stream {stream.props.get_name()} = {data}")ifdataisnotNone:count_recipients=len(recipient)ifrecipientisnotNoneelse1# Force the lazy decode now to avoid race condition afterward (PIL loads only when needed)ifisinstance(data,Image):data.load()# Forcing load here, for safetylog.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 recipientifuuidnotincontents_by_uuid:interactions_by_uuid[uuid]=interactionrecipients_by_uuid[uuid]=recipientcontents_by_uuid[uuid]=[{name:{'data':None,'data_tag':None,'data_uuid':None}fornameinstreams_dict.keys()}for_inrange(0,count_recipients)]contents_data_by_uuid[uuid]={name:Nonefornameinstreams_dict.keys()}valid_samples_count[uuid]=0# Pack into the prepared data structuresforiinrange(0,count_recipients):contents_by_uuid[uuid][i][name]={'data':data,'data_tag':data_tag,'data_uuid':uuid}contents_data_by_uuid[uuid][name]=datavalid_samples_count[uuid]+=1else: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 messagesuuid_to_remove=[]foruuid,countinvalid_samples_count.items():ifcount==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)})")foruuidinuuid_to_remove:delinteractions_by_uuid[uuid]delrecipients_by_uuid[uuid]delcontents_by_uuid[uuid]delcontents_data_by_uuid[uuid]delvalid_samples_count[uuid]# If direct message...ifnotStream.is_pubsub_from_net_hash(net_hash):name_or_group=DataProps.name_or_group_from_net_hash(net_hash)foruuid,recipientsinrecipients_by_uuid.items():contents=contents_by_uuid[uuid]content_data=contents_data_by_uuid[uuid]interaction=interactions_by_uuid[uuid]fori,recipientinenumerate(recipients):log.debug(f"[send_stream_samples] "f"Sending samples of {net_hash} by direct message to {recipient}...")content=contents[i]fornameincontent.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']isNone})")# One send per recipient, concurrently (one failure does not cancel the others)results=awaitasyncio.gather(*(self.node_conn.send(recipient,channel_trail=name_or_group,content_type=Msg.STREAM_SAMPLE,content=contents[i])fori,recipientinenumerate(recipients)),return_exceptions=True)# Checking result of sendingforrinresults:ifisinstance(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 objectifinteractionisnotNone:ifany(risTrueforrinresults):interaction.inc_streamed_samples()# If pubsub...ifStream.is_pubsub_from_net_hash(net_hash):foruuid,recipientsinrecipients_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]fornameincontent.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']isNone}")peer_id=Stream.peer_id_from_net_hash(net_hash)# Guessing agent peer ID from the net hashresult=awaitself.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))ifinteractionisnotNoneandresult: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.
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.
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.
defstreams_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([((" @"ifuser_hashinself.owned_streams_by_user_hashelse" ")+DataProps.peer_id_from_user_hash(user_hash)+" => "+str(stream).replace("\n","\n "))foruser_hash,streaminself.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.
defset_default_stdin_binding(self,public:bool|None=None)->None:"""Set default bindings for the stdin."""if(publicisnotNoneandnotpublic)or(publicisNoneandself.behaving_in_world()):self.stdin.bind(self.__proc_in_streams_by_user_hash_prv,uuid=Custom.SYSTEM_INTERACTION_UUID)if(publicisnotNoneandpublic)or(publicisNoneandnotself.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.
defset_default_stream_binding(self,public:bool|None=None)->None:"""Set default bindings for the stdin, stdtar, stdext, stdout stream proxies."""if(publicisnotNoneandnotpublic)or(publicisNoneandself.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(publicisnotNoneandpublic)or(publicisNoneandnotself.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.
defget_default_stdin_bindings(self,public:bool|None=None)->dict:"""Returns the streams that are bind by default on the stdin."""if(publicisnotNoneandnotpublic)or(publicisNoneandself.behaving_in_world()):returnself.__proc_in_streams_by_user_hash_prvif(publicisnotNoneandpublic)or(publicisNoneandnotself.behaving_in_world()):returnself.__proc_in_streams_by_user_hash_pubreturn{}
Returns the dict (user hash to Stream) that set_default_stdin_binding would bind for public.
defget_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(publicisnotNoneandnotpublic)or(publicisNoneandself.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(publicisnotNoneandpublic)or(publicisNoneandnotself.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.
defprepare_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 elseself.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 IDpeer_id=peer_idifpublicelseself.node_conn.get_world_node_peer_id()# First of all, clearing residuals of interactions that were completed in the pastto_remove=[]for_peer_id,_interactioninself.proc_human_peer_id_to_interaction.items():if_interaction.is_completed():to_remove.append(_peer_id)for_peer_idinto_remove:delself.proc_human_peer_id_to_interaction[_peer_id]# Getting existing interaction or defaulting to the system oneifpeer_idinself.proc_human_peer_id_to_interaction:interaction=self.proc_human_peer_id_to_interaction[peer_id]uuid=interaction.uuidelse:interaction=Noneuuid=Custom.SYSTEM_INTERACTION_UUID# Getting data tagifinteractionisnotNoneandinteraction.stdin_streamsisnotNoneandlen(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()returnuuid,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).
defdisable_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)]forstream_objinstream_dict.values():ifstream_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.
defenable_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)]forstream_objinstream_dict.values():ifstream_obj.is_public()==public:stream_obj.enable()
Enables again the processor input streams of the public (public=True) or the private network.
defset_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]ifpublicelseself.get_peer_ids()[1]proc_in=self.find_streams(peer_id,"processor_in")ifproc_inisNoneorlen(proc_in)==0:returnFalsefornet_hash,stream_dictinproc_in.items():ifnotDataProps.is_pubsub_from_net_hash(net_hash):forstream_name,stream_objinstream_dict.items():assertstream_obj.propsisnotNoneifstream_obj.props.is_public()==public:if(dataisNoneor((data_type=="text"orisinstance(data,str))andstream_obj.props.is_text())or((data_type=="img"orisinstance(data,Image))andstream_obj.props.is_img())or((data_type=="tensor"orisinstance(data,torch.Tensor))andstream_obj.props.is_tensor())):stream_obj.set(data,uuid=uuid)# This might fail if the stream is disabledstream_obj.set_tag(data_tag,uuid=uuid)returnTruereturnFalse
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.
defget_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. """ifnet_hashinself.known_streams:data_tag=-1stream_dict=self.known_streams[net_hash]forstream_objinstream_dict.values():t=stream_obj.get_tag(uuid)iftisnotNone:data_tag=max(data_tag,t)returndata_tagreturn-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.
defset_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. """ifnet_hashinself.known_streams:stream_dict=self.known_streams[net_hash]forstream_objinstream_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.
defget_current_interaction(self)->Interaction|None:"""Gets the interaction currently being executed. Returns: The current interaction, or None. """returnself.im.get_current()
Returns the interaction served by the running action. Outside an action it returns None.
defget_last_sent_interaction(self)->Interaction:"""Gets the last interaction this agent sent. Returns: The last sent interaction. """returnself.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.
defget_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. """assertisinstance(self.behav,HybridStateMachine)assertisinstance(self.behav_lone_wolf,HybridStateMachine)behav=self.behavifself.behav.is_enabled()elseself.behav_lone_wolfreturnbehav.get_action_step_idx()ifself.overridden_action_stepisNoneelseself.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.
defforce_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=stepifstep>=0elseNone
Makes get_action_step return step. A negative value removes the override. The behavior keeps its own step count.
defis_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. """ifself.im.currentisnotNone:returnself.im.current.was_last_step_done()else:returnNone
Returns True when the current interaction has done its last step (see Interaction.was_last_step_done) and None without a current interaction.
defis_multi_steps_action(self)->bool:"""Determines if the current action is a multistep action. Returns: True if the action is multistep, False otherwise. """ifself.im.currentisnotNone:returnself.im.current.is_multi_steps()else:returnFalse
Returns True when the current interaction spans more than one step and False without a current interaction.
defstepwise(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. """ifinteractionisNone:gen=make_gen(*args,**kwargs)whileTrue:try:next(gen)exceptStopIterationasstop:returnTrue,stop.valueifretry_timeout<=0.:raiseGenException("stepwise retry_timeout must be > 0")run=interaction.get_mark()ifrunisNone:action_ref=interaction.action_refassertisinstance(action_ref,Action)ifnotaction_ref.is_pedantic():action_ref.set_timeout(retry_timeout)# So that returning False means retrynow=time.perf_counter()run=_StepwiseRun(make_gen(*args,**kwargs),now+retry_timeout,now)interaction.set_mark(run)assertisinstance(run,_StepwiseRun)iftime.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)raiseGenException(f"Stepwise computation exceeded its retry budget "f"({run.deadline-run.started_at:.0f} s, "f"{run.chunks} chunks done)")try:next(run.gen)exceptStopIterationasstop: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")returnTrue,stop.valueexceptException:self._finish_stepwise(interaction,healthy=False)raise# -> @action wrapper -> False -> non-pedantic -> discarded in one shotrun.chunks+=1returnFalse,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.
defhook_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=inputsreturninputs
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.
defhook_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=outputsreturnoutputs
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.
defhook_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. """returndata
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.
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.
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.
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).
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.
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.
defuai_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)returnparts_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.
defuai_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 belowattempts=[tfortin(attemptsor[])ifisinstance(t,str)andt.strip()]iflen(attempts)>1and(eventisNoneorevent.via!=VIA_BLOCK):values,event,raw_texts=self.uai_merge_reads(spec,attempts)ifvaluesisnotNone:# 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 breakingiflen(answer.encode("utf-8"))>MAX_OUTPUT_BYTES:returnAnswerOutcome()self.uai_forget_form(spec)returnAnswerOutcome(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 moreifeventisnotNoneandevent.via==VIA_BLOCK:ifevent.to==spec.get("id"):self.uai_forget_form(spec)returnAnswerOutcome()# 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)ifeventisNoneor(event.via==VIA_FREETEXTandnotasked_nowandattempt==0andnotself.uai_can_reprompt_person()):ifnottext.strip()and(asked_noworattempt>0):returnself.uai_answer_fell_short(text,spec,None,attempt,model_view)returnAnswerOutcome()returnself.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.
With more than one attempt and no block written by the processor, the attempts are read together with uai_merge_reads.
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.
A block that the processor wrote itself travels as it is. When it answers this form, the form is forgotten.
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.
defuai_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_FREETEXTfortinattempts:_,e=read_answer(t,spec)ifeisNoneor(e.toisnotNoneande.to!=spec.get("id")):continueife.values:contributors.append(t)merged.update(e.values)issues=dict(e.issues)ife.issueselse{}# Only the LATEST attempt's complaints standlast_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"]forfininteractive_fields(spec)iff.get("required")andf["name"]notinmergedandf["name"]notinissues]event=ReplyEvent(to=spec.get("id"),name=spec.get("name"),values=merged,missing=missing,issues=issues,raw=attempts[-1]ifattemptselse"",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 overreturn(mergedifnotmissingandnotissueselseNone),event,(contributorsorattempts[-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.
The merged values when no required field is missing and the latest attempt raised no complaint. In every other case None.
The ReplyEvent of the merged reading with its missing fields and complaints.
The texts that contributed values in order from the oldest. When none did, the last attempt alone.
defuai_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.ifhas_human_processor(self):ifnotself.uai_can_reprompt_person():returnAnswerOutcome()# 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 timelog.user(f"⚠️ {reprompt_person(spec,event)}",rep=True)returnAnswerOutcome(withhold=True)# A module that gives back what it was given is a relay, not the author: there is nobody to askifself.uai_module_echoes():returnAnswerOutcome()# 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 sentifself.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)})")returnAnswerOutcome(withhold=True)ifattempt<self.UAI_MAX_RETRIES:returnAnswerOutcome(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)ifnottext.strip():log.misc(f"The answer to '{spec.get('name',spec.get('id'))}' was never given after "f"{attempt} more attempts: nothing is sent")returnAnswerOutcome(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 waylog.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,attemptsifattemptselsetext,event)ifpartialisnotNone:self.uai_forget_form(spec)returnAnswerOutcome(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.
The agent of a person in the browser: the words travel as written. Nothing printed by the node reaches the chat of that person.
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.
A module that echoes its input: the words travel as written.
defuai_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_TIMEOUTinteraction=self.get_current_interaction()ifinteractionisnotNoneandnotinteraction.is_system():ifinteraction.timeoutisnotNoneandinteraction.timeout>0.:budget=min(budget,interaction.timeout)budget-=self.clock.get_time()-interaction.timestamp_createdreturnbudget-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.
defuai_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. """returnhas_human_processor(self)andsys.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.
defuai_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."""returnself.procisnotNoneandbool(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.
defuai_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()ifinteractionisnotNoneandnotinteraction.is_system()andinteraction.requesterisnotNone:returninteraction.requesterifself.uai_writing_toisnotNone:returnself.uai_writing_tobehav=self.behavifself.behaving_in_world()elseself.behav_lone_wolfwildcards=behav.get_wildcards()ifbehavisnotNoneelse{}returnwildcards.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.
defuai_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. """ifpeer_idisNoneornotisinstance(text,str):returnparts=parse_message(text)spec=newest_form(parts)ifspecisNone:returnself.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 instructionself.uai_inbox[peer_id]=(spec,self.clock.get_time(),parts_to_model_text(parts))whilelen(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.
defuai_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)ifpeer_idisnotNoneelseNoneifentryisNone:returnNonespec,remembered_at=entry[0],entry[1]# Older than any interaction can be, so nobody is waiting for an answer any moreifself.clock.get_time()-remembered_at>Custom.DEFAULT_INTER_TIMEOUT:delself.uai_inbox[peer_id]returnNonereturnspec
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.
defuai_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."""ifself.uai_pending_form()isNone:returnNonepeer_id=self.uai_peer()entry=self.uai_inbox.get(peer_id)ifpeer_idisnotNoneelseNonereturnentry[2]ifentryisnotNoneelseNone
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.
defuai_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)ifpeer_idisnotNoneelseNoneifentryisnotNoneandentry[0].get("id")==spec.get("id"):delself.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.
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.
defremove_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 '_'."""forattr_nameindir(self):ifattr_name.startswith("_")and(notattr_name.startswith("__")andnotattr_name.startswith("_Agent")andnotattr_name.startswith("_WAgent")):try:value=getattr(self,attr_name)ifisinstance(value,list):setattr(self,attr_name,[vforvinvalueifv!=peer_id])elifisinstance(value,set):value.discard(peer_id)elifisinstance(value,dict):ifpeer_idinvalue:delvalue[peer_id]exceptAttributeError: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.
defreset_agent_status_attrs(self)->None:"""Resets attributes that represent the status of the agent, assuming to be the ones that start with '_'."""forattr_nameindir(self):if(attr_name.startswith("_")andnotattr_name.startswith("__")andnotattr_name.startswith("_Agent")andnotattr_name.startswith("_WAgent")andnotattr_name.startswith("_AgentBasics")):try:value=getattr(self,attr_name)ifisinstance(value,list):setattr(self,attr_name,[])elifisinstance(value,set):setattr(self,attr_name,set())elifisinstance(value,dict):setattr(self,attr_name,{})elifisinstance(value,int):setattr(self,attr_name,0)elifisinstance(value,float):setattr(self,attr_name,0.)elifisinstance(value,bool):setattr(self,attr_name,False)exceptAttributeError: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.
defagent_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)forkinsave_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.
defsave(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. """ifnot(isinstance(self.proc,ModuleWrapper)andisinstance(self.proc.module,torch.nn.Module)):returnFalseifwhere=='':ifself.node_identity_dirisNoneorlen(self.node_identity_dir)==0:returnFalsewhere=os.path.join(self.node_identity_dir,"agent_state")# Default save pathos.makedirs(where,exist_ok=True)# Saving the processorifself.procisnotNoneandself.proc_updated_since_last_save:assertisinstance(self.proc,ModuleWrapper)proc:ModuleWrapper=self.procassertisinstance(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 tooassertself.proc_optsisnotNoneifself.proc_opts.get('optimizer',None)isnotNone:checkpoint['optimizer_state_dict']=self.proc_opts['optimizer'].state_dict()torch.save(checkpoint,pt_tmp)os.replace(pt_tmp,pt_final)# Atomic moveself.proc_updated_since_last_save=FalseexceptExceptionase:ifos.path.exists(pt_tmp):os.remove(pt_tmp)log.error(f"Error saving processor: {e}")raisee# Save Agent Statepkl_final=os.path.join(where,f"{self.node_name}.pkl")pkl_tmp=pkl_final+".tmp"try:state=self.agent_state_dict()withopen(pkl_tmp,"wb")asf:pickle.dump(state,f)os.replace(pkl_tmp,pkl_final)exceptExceptionase:log.error(f"Could not save "+("agent"ifnotself.is_worldelse"world")+f": {e}")ifos.path.exists(pkl_tmp):os.remove(pkl_tmp)raiseereturnTrue
Saves the agent into the folder where and returns True. The node calls it every save_checkpoint_every seconds when that value is positive.
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.
When the processor learned since the last save, it writes {"model_state_dict": ..., "optimizer_state_dict": ...} to <node name>.pt.
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.
defload(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. """ifnot(isinstance(self.proc,ModuleWrapper)andisinstance(self.proc.module,torch.nn.Module)):returnFalseifwhere=='':ifself.node_identity_dirisNoneorlen(self.node_identity_dir)==0:returnFalsewhere=os.path.join(self.node_identity_dir,"agent_state")# Default save path# Check if directory existsifnotos.path.exists(where):log.error("No state folder found for "+("agent"ifnotself.is_worldelse"world")+f" {self.node_name}.")returnFalse# Check if the specific pickle file existspkl_path=os.path.join(where,f"{self.node_name}.pkl")ifnotos.path.exists(pkl_path):log.error("No saved state found for "+("agent"ifnotself.is_worldelse"world")+f" {self.node_name}.")returnFalse# Loading the agent state dictionarytry:withopen(pkl_path,"rb")asf:agent_state_dict=pickle.load(f)exceptExceptionase:raiseException(f"Error loading pickle file at {pkl_path}: {e}")# Update self's attributes with the loaded object's attributesself.__dict__.update(agent_state_dict)# Check if we also need to load the processor statept_path=os.path.join(where,f"{self.node_name}.pt")load_proc=self.procisnotNoneandos.path.exists(pt_path)ifload_proc:try:assertself.procisnotNoneassertself.proc_optsisnotNoneproc:ModuleWrapper=self.procassertisinstance(proc.module,torch.nn.Module)checkpoint=torch.load(pt_path)ifisinstance(checkpoint,dict)and'model_state_dict'incheckpoint:proc.module.load_state_dict(checkpoint['model_state_dict'])# Restore Optimizer to proc_optsif'optimizer_state_dict'incheckpointandself.proc_opts.get('optimizer')isnotNone:self.proc_opts['optimizer'].load_state_dict(checkpoint['optimizer_state_dict'])else:proc.module.load_state_dict(checkpoint)exceptExceptionase:raiseException(f"Error loading processor state: {e}")returnTrue
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.
asyncdefon_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.
asyncdefon_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.