An interaction is a request from one agent to one or more other agents: run this action, with these arguments, on these data. The agent that asks is the requester and the agents that run the action are the targets. A developer creates interactions with Agent.send and reads them in callbacks and actions. Everything else in this module runs inside the node: the node registers an incoming interaction, the behavior runs its action and the manager completes it, notifies the requester and frees the stream data. The narrative guide is Interactions.
One request, with its action, arguments, streams or samples, timing, status and per-target outcome. It is also the unit that travels on the network (to_dict and from_dict).
The bookkeeper of one agent. The agent holds it in agent.im. It keeps the interactions sent, received and lazy, binds the standard streams of the agent to the interaction being served and completes the expired ones.
Whether the manager registered it as sent, received or lazy.
The life of a request on the two sides follows these steps.
The requester builds an Interaction (status CREATED) and register_sent stores it in im.sent with status REQUESTED.
The target rebuilds it with Interaction.from_dict. Its behavior links it to the requested action and register_received stores it in im.received with status RECEIVED.
When the behavior serves it, set_current marks it RUNNING and binds the standard streams of the agent to the streams of the interaction. Another interaction can pause it (PAUSED).
When the action ends, complete marks it COMPLETED with a CompletionReason and moves it to received_recently_completed. At the next tick drain_completed returns it and the agent sends its status to the requester.
The requester applies that status with update_sent_status. When every target has completed, the copy of the requester becomes COMPLETED and its callback runs.
fromunaiverse.agentimportAgentfromunaiverse.interactionimportCompletionReasonclassAsker(Agent):asyncdefon_label(self,interaction=None):ifinteraction.completion_reason==CompletionReason.OK:print("Target reached",interaction.destination_state)else:print("Ended with",interaction.completion_reason.value)returnTrue# Inside an action or a behave() override of Asker:# await self.send(action_name="process", target="ResNetAgent",# data_samples={"proc_output_0": picture}, callback="on_label")
Three identifiers recur on this page. The id is a short string chosen by the requester (eight hexadecimal characters by default). The uuid is the id followed by _ and the peer id of the requester. Both agents store the interaction and its stream data under this key. A system interaction is one that an agent creates for itself when a behavior runs an action that nobody requested. Its requester is the label "system" (Custom.SYSTEM_INTERACTION_LABEL) and it never travels.
def__init__(self,action_name:str|None=None,action_kwargs:dict|None=None,streams:dict[str,str|list[str]]|list[str]|None=None,data_samples:list|dict[str,torch.Tensor|Image.Image|str]|str|None=None,num_steps:int=-1,requester:str|None=None,target:str|list[str]|None=None,from_state:str|None=None,to_state:str|None=None,timeout:float=-1.,callback:str|None=None,volatile:bool=False,forced_uuid:str|None="do_not_force",id:str|None="random",num_samples_to_stream:int=-1)->None:"""Create a new Interaction. Args: action_name: The name of the action being requested (e.g. "process", "learn"). action_kwargs: Action arguments (dict, no streams). streams: List of (stream_name - a.k.a. stream user hash, num_samples) tuples specifying expected data. data_samples: List of actual data samples (alternative to streams specification). It can also be a dictionary mapping one or more stream user hashes to data samples that will be artificially loaded on such streams, so that the 'streams' argument above is actually automatically populated. It can also be a string representing the payload that encodes a list of samples, if it was received from the net. num_steps: Total number of steps for this interaction (-1 means no data-based steps). requester: Peer ID of the agent originating this interaction. target: Peer ID of the target agent or list of peer IDs. from_state: Name of the state from which the interaction is expected to happen. to_state: Name of the state where the interaction is supposed to yield. timeout: Maximum retry_timeout until which the interaction is valid (-1 means no limit: the InteractionManager will override this with its internal retry_timeout valid for all actions). callback: Name of the method to call on the agent (the InteractionManager will do it) when this interaction finishes (it must be a method with a single argument, which is the interaction object). volatile: If True, it is marked so that the recipient is asked to not send back any status about its completion. forced_uuid: A very custom option to force a specific UUID (None is a valid UUID here), that is by default a mixture of the id (below) and the target fields. To be used only in very special cases. Defaults to "do_not_force". id: Identifier string (might not be unique); ``"random"`` generates one automatically (default). When set to None, it defaults to the UUID of a system interaction. The requester will be appended to it (separated by "_") to get the final UUID, that is the "unique" identification of the interaction. num_samples_to_stream: The maximum number of samples to stream. By default, no limits (the nun_steps is on the consumer side, the origin keeps streaming until timeout or completion). Default: -1 (no limits) """# Participantsself.requester:str|None=requester# Shallow copy targets, since they will be resolved laterself.target:list[str|None]=list(target)ifisinstance(target,list)else[target]# Identityself.id=_uuid.uuid4().hex[0:8]if(idisnotNoneandid=='random')elseid \
ifidisnotNoneelseCustom.SYSTEM_INTERACTION_UUID# Indexing string (the actual unique identifier of the interaction, that also involves the requester)self.uuid=Interaction.build_uuid(self.id,str(self.requester))# Forcing a specific UUID (if needed)ifforced_uuid!="do_not_force":self.id=Noneself.uuid=forced_uuid# Action requestedself.action_name=action_nameself.action_kwargs:dict=action_kwargsifaction_kwargsisnotNoneelse{}# Timing informationself.timestamp_created:float=-1.self.timestamp_started:float=-1.self.timeout:float=timeoutself.cycle_created:int=-1self.cycle_started:int=-1self.timestamp_completed:float=-1.self.cycle_completed:int=-1# Statesself.from_state:str|None=from_stateself.to_state:str|None=to_state# Samples specification: list of (stream_name, num_samples)self.streams:dict={}self.data_samples=[]self.num_steps:int=num_steps# Generic not-data-based interactions have -1 hereself.num_samples_to_stream:int=num_samples_to_stream# Stream-based specificationifstreamsisnotNoneandlen(streams)>0:self.parse_streams(streams)# This will create a specific stream structureifisinstance(data_samples,str):# If it is JSON string of a list of dicts, each is type_name->base64...data_samples=deserialize_payload(data_samples)# List of PIL.Image, torch.Tensor, str, ...# Actual data (alternative to samples above)iflen(self.streams)>0and(data_samplesisnotNoneandlen(data_samples)>0):log.error("You are not expected to build an interaction object specifying both streams and data_samples. ""Keeping streams only!")# Ensure all data-involving-interactions have at least self.num_steps = 1iflen(self.streams)>0and(notisinstance(self.num_steps,str)andself.num_steps<0):# Could be wildcardself.num_steps=1eliflen(self.streams)==0and(data_samplesisnotNoneandlen(data_samples)>0):self.data_samples=data_samples# List of PIL.Image, torch.Tensor, str, or dict user hash -> sampleself.num_steps=1# Checkingifself.num_samples_to_stream>=0andself.num_steps>self.num_samples_to_stream:log.error(f"You cannot ask to stream {self.num_samples_to_stream} samples and require the consumer to "f"run {self.num_steps} action steps.")# Statusself.status:InteractionStatus=InteractionStatus.CREATEDself.volatile:bool=volatile# Pointersself.action_ref=None# Reference to the actual Action object# Data tagsself.data_tags:dict[str,list[int]]={}# Streams could have different data tags# Completion reasonself.completion_reason:CompletionReason|None=None# Destination state reached, if the action was completed (for status messages)self.destination_state:str|None=None# Params that depends on the way it is stored in the actionself.by_insertion_order_id=-1self.by_requester_insertion_order_id=-1# Status of the running actionself.__step_idx=-1# The first done step will have index 0, while -1 means "no steps done so far"self.__starting_time=0.self.__timeout_starting_time=0.self.__mark=Noneself.__num_streamed_samples=0self.stdin_streams={}# User hash to stream objectself.stdtar_streams={}# User hash to stream objectself.stdext_streams={}# User hash to stream objectself.owned_streams={}# User hash to stream objectself.lazy_streams={}# User hash to stream objectself.stream_proxy=StreamProxy()# Virtual stream IO associated to all streams above (not the lazy ones)# Target-related infoself.target_data_tags:list[dict[str,list[int]]]=[{}for_inrange(len(self.target))]self.target_cycle_completed:list[int]=[-1]*len(self.target)self.target_timestamp_completed:list[float]=[-1.]*len(self.target)self.target_completion_reason:list[CompletionReason|None]=[None]*len(self.target)self.target_destination_state:list[str|None]=[None]*len(self.target)# Back-reference to the InteractionManager (set when registered)self.__im:InteractionManager|None=None# Interaction type (from Interaction Manager)self.type:InteractionType|None=None# Callback method nameself.callback=callback# Checkingifself.callbackisnotNoneandself.volatile:raiseGenException("You cannot set a callback on a volatile interaction")
One request between agents, on the side of the requester or on the side of a target. The two copies are distinct objects. The requester keeps its copy in im.sent and each target rebuilds its own from the dictionary that travels on the network. A developer rarely calls the constructor directly because Agent.send builds the interaction from its own arguments and the node rebuilds the received ones.
Argument
Type
Default
Meaning
action_name
str or None
None
The action that the targets run, for example "process", "learn" or an action of a role file. An interaction with no action name is completed with TIMEOUT at the first tick of the manager.
action_kwargs
dict or None
None
The arguments of that action. None becomes {}. The manager refuses names reserved to the framework (max_duration, retry_timeout, delay, action_kwargs, interaction) and fields of the interaction echoed with a different value (see check_consistency_between_action_kwargs_and_interaction_fields).
streams
list[str], dict[str, list[str]] or None
None
The streams that carry the data. parse_streams parses them. Each entry can be a stream name, a group, a user hash (peer_id:name) or a net hash. When streams are given and num_steps is negative, num_steps becomes 1.
data_samples
list, dict, str or None
None
The data itself in place of streams. A dict maps a stream of the requester to one sample and the manager later moves it onto that stream (see resolve). A list holds samples (PIL.Image.Image, torch.Tensor, str). A str is the serialized payload of a list received from the network and is decoded at once. Samples given together with streams are dropped with an error in the log. Samples alone force num_steps to 1.
num_steps
int or str
-1
How many steps the target runs with one sample per step. -1 means no data-based steps. A behavior file may pass a wildcard string such as "<eval_steps>" that the behavior replaces later.
requester
str or None
None
The peer id of the requester. send fills it with the peer id of the agent on the network where it behaves.
target
str, list[str] or None
None
The targets. A string becomes a one-element list and None becomes [None]. The list is copied.
from_state, to_state
str or None
None
The state of the behavior of the target where the interaction may start and the state where it should end.
timeout
float
-1.0
The maximum life of the interaction in seconds from its registration. A non-positive value leaves the limit to the manager. The manager applies Custom.DEFAULT_INTER_TIMEOUT (300 seconds) to every interaction and a positive value lower than 300 wins.
callback
str or None
None
The name of an async method of the requester that the manager awaits once with interaction= when the interaction completes.
volatile
bool
False
Asks the targets not to send any status back. The requester completes its own copy with TIMEOUT at the next tick.
forced_uuid
str or None
"do_not_force"
Any value other than the sentinel "do_not_force" becomes the uuid as it is (None included) and the id becomes None. Reserved for special cases.
id
str or None
"random"
"random" draws eight hexadecimal characters. None uses Custom.SYSTEM_INTERACTION_UUID ("sys_system"). Any other string is used as it is.
num_samples_to_stream
int
-1
The maximum number of samples that the owner of the streams sends for this interaction. -1 streams until completion or timeout. A non-negative value lower than num_steps is logged as an error.
The constructor raises GenException in two cases: (1) a callback on a volatile interaction and (2) a malformed streams argument. It does not contact anybody and does not register the interaction.
The unique key of the interaction, a str of the form <id>_<requester> built by build_uuid. Both sides store the interaction under this key and the samples of its streams travel under it. A forced uuid replaces it as it is.
The short identifier chosen by the requester (str). Two requesters can use the same id because the uuid appends the requester. It is None when the uuid was forced.
The peer id of the requester (str or None). It is "system" for a system interaction and None for an interaction built without one (see has_dummy_requester).
The list of the targets. Before registration an entry can be a node name, an owner/name reference or a wildcard. register_sent replaces every entry with a peer id and Agent.send then keeps only the targets that the message reached (see update_target). The per-target lists below follow the order of this list.
The CompletionReason of the whole interaction. It stays None until the interaction completes. With several targets it is the reason of the last target that completed.
The state that the behavior of the target reached when it completed the action (str or None). On the requester it comes from the status message of the target. A successful process in the default public behavior ends in "generated".
The timeout given at construction in seconds (float). A non-positive value means that the interaction has no limit of its own. It travels in the dictionary under the key retry_timeout.
The time of the node clock (clock.get_time(), seconds) at which a manager registered the interaction. It is -1.0 before registration. Four other attributes complete the timing of the interaction.
Attribute
Type
Meaning
timestamp_started
float
Clock time of the first mark_running (-1.0 before it).
timestamp_completed
float
Clock time of the completion (-1.0 before it).
cycle_created, cycle_started, cycle_completed
int
The same three moments as clock cycles from clock.get_cycle() (-1 before each of them).
The number of steps (int, or a wildcard str before the behavior replaces it). -1 marks an interaction without data-based steps. Read it with get_total_steps.
The stream specification after parsing: a dict with the keys stdin, stdtar, stdext and stdunk, each holding a list of stream references. It is {} for an interaction without streams. During registration the manager replaces the references with user hashes or net hashes.
The samples carried by the interaction itself. It is a list of samples or a dict from stream to sample. The manager moves the samples of a dict onto their streams and then empties this attribute.
The name of the method of the requester to await on completion (str or None). The callback is not part of the dictionary that travels. The copy of a target therefore never has one.
The Action of the behavior that serves the interaction, assigned by set_action_ref on the target and on system interactions. It is None on the copy of the requester.
The data tags that this agent has consumed for the interaction, a dict from stream user hash to the list of tags in the order of consumption. get_new_stream_data_tags compares the current tag of each stream with the last one here to decide whether a sample is fresh. The status message sends this dictionary to the requester.
On the copy of the requester, a list aligned with target that holds the completion reason of each target. Four sibling lists share the same alignment and are reset by update_target.
Attribute
Type of each entry
Meaning
target_completion_reason
CompletionReason or None
Why that target completed. It is None until the target completes.
A StreamProxy bound under the uuid of the interaction to every stream that the manager assigned to it (stdin_streams, stdtar_streams, stdext_streams, owned_streams) and to the samples of data_samples under the keys <data_sample_0>, <data_sample_1> and so on. Iterating over it yields the bound objects. An action such as record reads the streams of the interaction through it.
The streams that feed the inputs of the processor for this interaction, a dict from user hash to stream object in the order of the inputs. A missing input with a default value appears under the key <default_input_pos_i> with that value. Four sibling dictionaries complete the assignment made by the manager.
Attribute
Content
stdtar_streams
The streams used as learning targets of the outputs of the processor.
stdext_streams
The streams that fit no input or output of the processor.
owned_streams
The streams among the ones above that this agent owns.
The position of the interaction in the queue of its action (int, -1 until the action queues it). Its sibling by_requester_insertion_order_id is the position among the requests of the same requester. Both are maintained by the action and read by is_valid.
@staticmethoddefbuild_uuid(id:str|None,requester:str|None=None)->str:"""Builds the uuid of an interaction from its id and its requester. Args: id: The id of the interaction (None means the system interaction id). requester: The requester (None means the system interaction label) (default: None). Returns: The uuid, "<id>_<requester>". """ifidisNone:id=Custom.SYSTEM_INTERACTION_IDifrequesterisNone:requester=Custom.SYSTEM_INTERACTION_LABELreturnid+"_"+requester
Static method that returns the uuid id + "_" + requester. A None id becomes Custom.SYSTEM_INTERACTION_ID ("sys") and a None requester becomes Custom.SYSTEM_INTERACTION_LABEL ("system"). With both None the result is "sys_system". Every system interaction has this uuid.
@staticmethoddefget_id_from_uuid(uuid:str|None)->str|None:"""Extracts the id of an interaction from its uuid. Args: uuid: The uuid of the interaction. Returns: The id, or None when the uuid is None. """ifuuidisNone:returnNone# Safety guardreturnuuid.split("_")[0]
Static method that returns the part of uuid before the first _. A None uuid gives None. A forced uuid without _ comes back whole.
defupdate_target(self,target:str|list[str])->None:"""Sets the target(s) of the interaction, resetting the per-target completion data. Args: target: A target or a list of targets. """ifisinstance(target,str):target=[target]self.target=targetself.target_completion_reason=[None]*len(self.target)self.target_data_tags=[{}for_inrange(len(self.target))]self.target_timestamp_completed=[-1.]*len(self.target)self.target_destination_state=[None]*len(self.target)self.target_cycle_completed=[-1]*len(self.target)
Replaces the attribute target with the argument target (a string becomes a one-element list) and resets the five per-target lists to their initial values. After sending, Agent.send calls it with the list of the targets that the message reached.
definc_streamed_samples(self)->None:"""Increments the counter of the samples streamed for this interaction."""self.__num_streamed_samples+=1
Adds one to the private count of the samples streamed for this interaction. The agent calls it after a sample of an owned stream left for at least one recipient.
defall_samples_streamed(self)->bool:"""Tells whether all the samples to stream for this interaction were streamed. Returns: True if the count of streamed samples reached the (positive) number of samples to stream. """returnself.__num_streamed_samples>=self.num_samples_to_stream>0
Returns True when num_samples_to_stream is positive and the count of streamed samples has reached it. With the default -1 it always returns False. The agent stops sending samples of an interaction for which it returns True.
defset_manager(self,im:'InteractionManager',stdin_streams:dict[str,Stream|object],stdtar_streams:dict[str,Stream|object],stdext_streams:dict[str,Stream|object],owned_streams:dict[str,Stream|object])->None:"""Bind this interaction to its owning InteractionManager and initialize its stream references. Args: im: The InteractionManager that owns this interaction. stdin_streams: Mapping from user-hash to stream objects used as processor inputs. stdtar_streams: Mapping from user-hash to stream objects used as processor targets. stdext_streams: Mapping from user-hash to stream objects used as extra (non-input) streams. owned_streams: Mapping from user-hash to stream objects owned by this agent. """self.__im=imself.timestamp_created=clock.get_time()self.cycle_created=clock.get_cycle()self.stdin_streams=stdin_streamsself.stdtar_streams=stdtar_streamsself.stdext_streams=stdext_streamsself.owned_streams=owned_streamsdata_samples_dict={"<data_sample_"+str(i)+">":self.data_samples[i]foriinrange(0,len(self.data_samples))}self.stream_proxy.bind(self.stdin_streams|self.stdtar_streams|self.stdext_streams|self.owned_streams|data_samples_dict,uuid=self.uuid)
Binds the interaction to its manager and to the streams that the manager chose. The manager calls it during registration.
Argument
Type
Meaning
im
InteractionManager
The manager that owns the interaction.
stdin_streams
dict
User hash to stream object (or default value) for the inputs of the processor.
stdtar_streams
dict
The same for the learning targets.
stdext_streams
dict
The same for the extra streams.
owned_streams
dict
The same for the streams owned by the agent.
It records timestamp_created and cycle_created from the node clock, stores the four dictionaries and binds stream_proxy to all of them and to the data samples under the uuid of the interaction.
defreset_state(self)->None:"""Resets the state, including the step counter and timing metrics, allowing it to be re-run from the beginning. """self.__step_idx=-1self.__starting_time=0.self.__timeout_starting_time=0.
Brings the step index back to -1 and the starting time and timeout starting time back to 0.0. The behavior calls it to rerun an action from its first step. Status, mark and data tags are untouched.
defset_mark(self,mark:object)->None:"""Store an arbitrary marker object on the interaction."""self.__mark=mark
Stores an arbitrary object on the interaction. An action keeps its state in the mark across the ticks in which it returns False. Agent.send with wait_completion=True keeps the sent interaction there and AgentBasics.stepwise keeps its generator there. The action clears the mark when it completes.
defset_step_idx(self,steps:int)->None:"""Directly assign the current step index. Args: steps: The step index to set. """self.__step_idx=steps
Writes the step index directly. The action uses it. A developer who needs to move the step of the running action calls AgentBasics.force_action_step instead.
defset_starting_time(self,t:float)->None:"""Record the wall-clock time at which execution started. Args: t: Starting timestamp (from ``time.perf_counter()``). """self.__starting_time=t
Records the time.perf_counter() value t as the moment the action started serving the interaction. is_timed_out measures the max_duration of the transition from it.
defset_timeout_starting_time(self,t:float)->None:"""Record the wall-clock time used as the baseline for next-step retry_timeout checks. Args: t: Timeout baseline timestamp (from ``time.perf_counter()``). """self.__timeout_starting_time=t
Records the time.perf_counter() value t as the baseline of the retry_timeout of the transition. The action moves it forward after each successful step.
defget_total_steps(self)->int:"""Retrieves the total number of steps configured for the action. Returns: An integer representing the total steps. """returnself.num_steps
defget_starting_time(self)->float:"""Retrieves the timestamp when the action's current execution started. Returns: A float representing the starting time. """returnself.__starting_time
Returns the value recorded by set_starting_time (0.0 before).
defget_timeout_starting_time(self)->float:"""Retrieves the timestamp used as the baseline for next-step retry_timeout checks. Returns: A float representing the retry_timeout starting time. """returnself.__timeout_starting_time
Returns the value recorded by set_timeout_starting_time (0.0 before).
defis_multi_steps(self)->bool:"""Determines if the action is configured to be a multistep action (i.e., not a single-step action). Returns: A boolean indicating if the action is multistep. """# The first part of this check sounds weird, I know,# it happens if num_steps is specified as a wildcard like <eval_steps>returnisinstance(self.num_steps,str)orself.num_steps>1
Returns True when num_steps is greater than one or is still a wildcard string.
defis_single_step(self)->bool:"""Return True if this is a single-step action (one data sample or no data at all)."""returnself.num_steps==1orself.num_steps<0# Action with a single data sample or no data samples at all
Returns True when num_steps is 1 or negative. With a wildcard string still in num_steps the comparison raises TypeError.
defis_valid(self)->bool:"""Return True if the interaction has been assigned insertion-order IDs by the action."""returnself.by_insertion_order_id>=0andself.by_requester_insertion_order_id>=0
Returns True once an action has queued the interaction. This happens when both by_insertion_order_id and by_requester_insertion_order_id are non-negative.
defis_system(self)->bool:"""Return True if the interaction is a system-level interaction."""returnself.requester==Custom.SYSTEM_INTERACTION_LABEL
Returns True when the requester is "system", the label of the interactions that an agent creates for itself. Several built-in actions branch on it. For example send refuses to run for any requester other than the system.
defis_completed(self)->bool:"""Return True if the interaction status is COMPLETED."""returnself.status==InteractionStatus.COMPLETED
Returns True when the status is COMPLETED for any reason. A rejected or expired interaction is completed too. Its completion_reason tells these cases apart.
defset_arg(self,arg_name:str,arg_value:object)->None:"""Set or overwrite an action keyword argument. Args: arg_name: The argument name. arg_value: The value to assign. """self.action_kwargs[arg_name]=arg_value
Writes action_kwargs[arg_name] = arg_value and adds the key when it is missing.
defget_arg(self,arg_name:str)->object:"""Retrieve an action keyword argument by name. Args: arg_name: The argument name to look up. Returns: The argument value, or ``None`` if the argument is not present. """returnself.action_kwargs[arg_name]ifarg_nameinself.action_kwargselseNone
Returns action_kwargs[arg_name]. A missing key gives None. A stored None and a missing key give the same result.
defwas_last_step_done(self)->bool:"""Determines if the action has reached its completion criteria, either by reaching the total number of steps or by exceeding the maximum allowed execution time. Returns: True if the action is completed, False otherwise. """return((self.num_steps<0andself.__step_idx==0)or# Action with no data (no steps)(self.num_steps>0andself.__step_idx==self.num_steps-1))# Action with one or more steps
Returns True when the last step is done: step 0 for an interaction without data-based steps (num_steps < 0) and step num_steps - 1 otherwise. AgentBasics.is_last_action_step reads it on the current interaction.
defis_delayed(self,starting_time:float)->bool:"""Checks if the action is currently in a delayed state and cannot be executed yet, based on a defined delay period. Args: starting_time: The time the delay period began. Returns: True if the action is delayed, False otherwise. """returnself.action_ref.get_delay()>0and(time.perf_counter()-starting_time)<=self.action_ref.get_delay()
Returns True while less than the delay of the action has passed since starting_time (a time.perf_counter() value). It returns False when the action has no delay. The method needs action_ref.
defis_timed_out(self)->bool:"""Checks if the action has exceeded its configured retry_timeout period since the last successful execution attempt. Returns: True if the action has timed out, False otherwise. """# If the action was never started (even a failed attempt), this method has no senseifself.__starting_time<=0.:returnFalse# Checking global retry_timeout: if too much time passed, no matter if the action started or not,# it's retry_timeout!ifself.action_ref.get_total_time()>0:ifself.action_ref.get_total_time()<=(time.perf_counter()-self.__starting_time):log.inter(f"Timeout for {self.action_name}! "f"({(time.perf_counter()-self.__starting_time)}/"f"{self.action_ref.get_total_time()})!")returnTrueelse:log.debug(f"Running retry_timeout for {self.action_name}! "f"({(time.perf_counter()-self.__starting_time)}/"f"{self.action_ref.get_total_time()})!")# Checking next-step retry_timeoutifself.__timeout_starting_time>0.andself.action_ref.get_timeout()>0:ifself.action_ref.get_timeout()<=(time.perf_counter()-self.__timeout_starting_time):log.inter(f"Hot retry_timeout for {self.action_name}! "f"({(time.perf_counter()-self.__timeout_starting_time)}/"f"{self.action_ref.get_timeout()})!")returnTrueelse:log.debug(f"Running hot retry_timeout for {self.action_name} "f"({(time.perf_counter()-self.__timeout_starting_time)}/"f"{self.action_ref.get_timeout()})!")returnFalseelse:returnFalse
Tells the action whether to give up on the interaction. It returns False before the first attempt. It requires action_ref and returns True in two cases: (1) the action has a positive max_duration and that many seconds have passed since set_starting_time and (2) the action has a positive retry_timeout and that many seconds have passed since set_timeout_starting_time.
defset_action_ref(self,action_ref:"Action")->None:"""Bind the interaction to its Action object and validate/augment its argument list. Args: action_ref: The Action instance that will execute this interaction. """self.action_ref=action_ref# Augmenting argument list, by fusing with the arguments defined in the HSMaction_kwargs=self.action_kwargsifself.action_kwargsisnotNoneelse{}self.action_ref.check_provided_args(action_kwargs,exception=True)# Force a default retry_timeout on multistep actions, to avoid infinite trialsifself.is_multi_steps()andself.action_ref.get_timeout()<=0:self.action_ref.set_default_timeout()
Links the interaction to the Action that serves it. The behavior calls it when it accepts a request. It checks action_kwargs against the signature of the action and raises ValueError on an argument that the action does not accept. A multi-step interaction on an action without a retry_timeout gets the default one (Custom.DEFAULT_TIMEOUT, 10 seconds) to prevent endless retries.
defhas_stream(self,user_hash:str)->bool:"""Return True if a stream with the given user hash is already registered. Args: user_hash: The stream's user-level hash identifier. """returnuser_hashinself.stream_proxyoruser_hashinself.lazy_streams
Returns True when the stream with user hash user_hash is bound to the stream proxy or attached as a lazy stream.
defadd_lazy_stream(self,user_hash:str,stream_obj:Stream,is_owned:bool=False)->None:"""Lazily attach an additional stream to this interaction after it was created. Args: user_hash: The stream's user-level hash identifier. stream_obj: The stream object to attach. is_owned: Whether the stream is owned by the current agent. """ifnotself.has_stream(user_hash):self.lazy_streams[user_hash]=stream_objifis_owned:self.owned_streams[user_hash]=stream_objself.stream_proxy.add_new_bind(user_hash,stream_obj)
Attaches a stream after registration. It does nothing when the stream is already there. Otherwise it stores stream_obj in lazy_streams and binds it to the stream proxy under user_hash. With is_owned=True the stream also goes into owned_streams. The manager calls it through add_lazy_stream_to_interaction.
defmark_running(self)->None:"""Mark this interaction as currently running."""self.status=InteractionStatus.RUNNINGifself.timestamp_started<=0:self.timestamp_started=clock.get_time()self.cycle_started=clock.get_cycle()
Changes the status to RUNNING. At the first call it also records timestamp_started and cycle_started.
defmark_completed(self,reason:'CompletionReason',dest_state:str|None=None,target:str|None=None)->None:"""Mark this interaction as completed. Args: reason: The reason for completion. dest_state: The destination state reached by completing this action. target: The target agent who completed this interaction (Default: None). """iftargetisNone:self.destination_state=dest_stateself.completion_reason=reasonself.timestamp_completed=clock.get_time()self.cycle_completed=clock.get_cycle()self.status=InteractionStatus.COMPLETED_time=clock.get_time()_cycle=clock.get_cycle()self.target:listfori,tarinenumerate(self.target):ifself.target_completion_reason[i]isNone:self.target_destination_state[i]=dest_stateself.target_completion_reason[i]=reason# The completion reason of the whole interactionself.target_timestamp_completed[i]=_timeself.target_cycle_completed[i]=_cycleelse:num_completed=0_time=clock.get_time()_cycle=clock.get_cycle()fori,tarinenumerate(self.target):iftar==target:self.target_destination_state[i]=dest_stateself.target_completion_reason[i]=reasonself.target_timestamp_completed[i]=_timeself.target_cycle_completed[i]=_cycleifself.target_completion_reason[i]isnotNone:num_completed+=1ifnum_completed==len(self.target):self.mark_completed(reason,dest_state)# The completion reason of the last target who completed
Records a completion. The manager calls it through complete.
Argument
Type
Default
Meaning
reason
CompletionReason
required
Why it completed.
dest_state
str or None
None
The state reached.
target
str or None
None
The target that completed. None completes the whole interaction.
With target=None the interaction becomes COMPLETED with this reason, state and time. Every target that has no reason yet receives the same values. With a target, only the entries of that target change. When the last target completes, the whole interaction completes with the reason and state of that last target.
defclear_from_action(self)->None:"""Deregister this interaction from its action's interaction list."""# Clearing interaction from action listifself.action_refisnotNone:self.action_ref.get_list_of_interactions().remove(self)
Removes the interaction from the queue of its action. Without an action_ref it does nothing.
defis_expired(self,timeout_secs:float|None=None)->bool:"""Check if this interaction has expired based on an external retry_timeout. Args: timeout_secs: Maximum higher-priority retry_timeout in seconds (default: None). Returns: True if the interaction is older than timeout_secs. """# Deciding the real value of timeout_specs also in function of the interaction-specific retry_timeout (if given)iftimeout_secsisnotNoneandtimeout_secs>0.andself.timeoutisnotNoneandself.timeout>0.:timeout_secs=min(timeout_secs,self.timeout)eliftimeout_secsisNoneortimeout_secs<=0.:timeout_secs=self.timeout# It could still be None or < 0.iftimeout_secsisNoneortimeout_secs<=0.:# Perpetual interactionreturnFalseelse:return(clock.get_time()-self.timestamp_created)>=timeout_secs
Returns True when the interaction is older than its timeout, measured on the node clock from timestamp_created. The timeout is the smaller positive value between timeout_secs and the timeout of the interaction. Without any positive value the interaction never expires. The manager calls it with Custom.DEFAULT_INTER_TIMEOUT (300 seconds).
defget_new_stream_data_tags(self,all_fresh_or_fail:bool=False)->dict[str,list[int]]|None:"""Checks all streams involved in this interaction, and if they have fresh data it returns their tags. Args: all_fresh_or_fail: If True, return None if there is at least one stream with no fresh data (Default: False). Returns: A dictionary "stream user hash to data tag", only involving streams with fresh data. It can return None if the all_fresh_or_fail option was turned on. """data_tags={}forstream_user_hash,stream_objinself.stream_proxy.items():# Skipping data samples and default input valuesifnotisinstance(stream_obj,Stream):continueif(stream_user_hashinself.data_tagsandlen(self.data_tags[stream_user_hash])>0):last_handled_data_tag=self.data_tags[stream_user_hash][-1]else:last_handled_data_tag=None# Check if stream has data with a tag not yet consumed by this interactioncurrent_tag=stream_obj.get_tag(self.uuid)ifcurrent_tagisNoneandself.is_system():# Lazy/system interactions may read sources that publish under uuid=None# (e.g. 'record' with record_uuid=None reading world streams): evaluate# freshness on the None slot in that case.current_tag=stream_obj.get_tag(None)ifcurrent_tagisNoneor(last_handled_data_tagisnotNoneandcurrent_tag==last_handled_data_tag):ifall_fresh_or_fail:returnNoneelse:continue# Storingdata_tags[stream_user_hash]=[current_tag]returndata_tags
Finds the streams of the interaction that carry a sample not yet consumed. For each stream in the stream proxy (data samples and default values are skipped) it reads the tag stored under the uuid. For a system interaction without data under its uuid the method reads the tag of the None slot. A stream keeps in that slot the data published outside any interaction. A stream counts as fresh when it has a tag that differs from the last one in data_tags.
Argument
Type
Default
Meaning
all_fresh_or_fail
bool
False
Return None as soon as one stream is not fresh.
It returns a dict from stream user hash to a one-element list with the fresh tag. With all_fresh_or_fail=True and a stale stream it returns None. An interaction without streams returns {}.
defrecord_data_tags(self,data_tags:dict[str,list[int]]|None=None,target:str|None=None)->None:"""Record that data with the given tag was received for this interaction. Args: data_tags: The data tags/sequence numbers. target: The agent who handled the data tags (if None, then it's the current agent). """ifdata_tagsisNone:data_tags:dict[str,list[int]]|None=self.get_new_stream_data_tags()ifdata_tagsisNoneorlen(data_tags)==0:returniftargetisNone:handled_data_tags=self.data_tagselse:iftargetinself.target:i=self.target.index(target)handled_data_tags=self.target_data_tags[i]else:log.error(f"Invalid target {target} specified to record data tags: "f"it does not exist in the list of targets ({self.target}) of "f"interaction with UUID {self.uuid}")return_time=clock.get_time()forstream_name,list_of_data_tagindata_tags.items():ifstream_namenotinhandled_data_tags:handled_data_tags[stream_name]=[]handled_data_tags[stream_name]+=list_of_data_tag
Appends consumed tags to the tag history of this agent or of one target.
Argument
Type
Default
Meaning
data_tags
dict[str, list[int]] or None
None
The tags to record. None takes the fresh tags from get_new_stream_data_tags().
target
str or None
None
None records in data_tags (this agent). A target records in its entry of target_data_tags. An unknown target is logged and ignored.
The action calls it after a step and the manager calls it with the tags of a status message.
defcheck_if_doable(self)->bool:"""Return True if the interaction can currently be executed. Delegates to the owning InteractionManager when present; for system interactions without a manager, returns True as long as the interaction is not yet completed. """ifself.__imisnotNone:returnself.__im.check_if_doable(self)else:returnnotself.completed# System interactions does not have an interaction manager
Returns True when the interaction can run now. With a manager it delegates to InteractionManager.check_if_doable. Without one (a system interaction) it returns True until the interaction completes.
defalter_arg(self,arg_name:str,arg_value:object)->bool:"""Overwrite an existing action keyword argument, leaving the dict unchanged if the key is absent. Args: arg_name: The argument name to update. arg_value: The new value to assign. Returns: True if the argument existed and was updated; False otherwise. """ifarg_nameinself.action_kwargs:self.action_kwargs[arg_name]=arg_valuereturnTrueelse:returnFalse
Overwrites action_kwargs[arg_name] only when the key exists. It returns True when it changed the value and False when the key is missing.
defto_dict(self)->dict:"""Serialize this interaction for network transmission. Returns: A dictionary representation of this interaction. """assertisinstance(self.data_samples,list)iflen(self.data_samples)>0andlen(self.streams)>0:log.critical("You are trying to convert to dictionary (to_dict) an interaction object where both streams ""and data_samples are specified, that is unexpected, and might create troubles when sent ""through the net. Only one of them can be provided")return{'id':self.id,'uuid':self.uuid,'action_name':self.action_name,'requester':self.requester,'target':self.target,'action_kwargs':self.action_kwargs,'streams':self.streams,'data_samples':serialize_payload(self.data_samples),'num_steps':self.num_steps,'completion_reason':self.completion_reason.valueifself.completion_reasonelseNone,'destination_state':self.destination_state,'from_state':self.from_state,'to_state':self.to_state,'retry_timeout':self.timeout,'volatile':self.volatile,'status':self.status.value,'num_samples_to_stream':self.num_samples_to_stream}
Returns the dictionary that travels on the network. Its keys are id, uuid, action_name, requester, target, action_kwargs, streams, data_samples (serialized), num_steps, completion_reason (the value or None), destination_state, from_state, to_state, retry_timeout (the timeout attribute), volatile, status (the value) and num_samples_to_stream. The callback and every local attribute stay on the requester. It logs a critical message when both streams and data samples are present.
@classmethoddeffrom_dict(cls,d:dict)->'Interaction':"""Deserialize an Interaction from a dictionary. Args: d: Dictionary from to_dict(). Returns: A new Interaction instance. """interaction=cls(id=d['id'],action_name=d['action_name'],action_kwargs=d.get('action_kwargs',{}),streams=d.get('streams',None),data_samples=d.get('data_samples',None),num_steps=d.get('num_steps',-1),requester=d.get('requester'),target=d.get('target'),from_state=d.get('from_state'),to_state=d.get('to_state'),volatile=d.get('volatile',False),timeout=d.get('retry_timeout',-1.),num_samples_to_stream=d.get('num_samples_to_stream',-1),)interaction.uuid=d['uuid']interaction.status=InteractionStatus(d['status'])ifd.get('completion_reason'):interaction.completion_reason=CompletionReason(d['completion_reason'])interaction.destination_state=d.get('destination_state')returninteraction
Class method that rebuilds an interaction from the output of to_dict. It passes the fields to the constructor and then restores uuid, status, completion_reason and destination_state from the dictionary. The node calls it on every incoming interaction.
defto_status_dict(self,status_generated_by:str)->dict:"""Build a minimal status dict for status update messages. Args: status_generated_by: The agent who generate this dict. Returns: A dictionary with status_generated_by, uuid, status, completion_reason, destination_state, and data_tag. """return{'status_generated_by':status_generated_by,'uuid':self.uuid,'status':self.status.value,'completion_reason':self.completion_reason.valueifself.completion_reasonelseNone,'destination_state':self.destination_state,'data_tags':self.data_tagsiflen(self.data_tags)>0elseNone,}
Returns the status message that a target sends to the requester: status_generated_by (the argument, the peer id of the target on the network of the interaction), uuid, status, completion_reason, destination_state and data_tags (None when empty).
defto_code_str(self,include_id:bool=False,include_received_tags:bool=False)->str:"""Return a compact single-line representation for logs and debugging. Args: include_id: Prepend the interaction UUID to the output when True. include_received_tags: Append the received data tags when True. Returns: A compact string describing the interaction. """s=""t=self.targetifinclude_id:s=f"{self.uuid} => "ifinclude_received_tags:t:list[str]=[]fori,tarinenumerate(self.target):all_tags=[str(num)forsublistinself.target_data_tags[i].values()fornuminsublist]ifall_tags:t.append(f"{tar}_("+",".join(all_tags)+")")else:t.append(f"{tar}")returns+(f"artss:{self.action_name}|{self.requester}|{t}|"f"{self.stream_proxy}|{self.status.value[0:3]}"+(("_"+self.completion_reason.value[0:3])ifself.completion_reasonisnotNoneelse""))
Returns a one-line description for the logs: artss:<action>|<requester>|<targets>|<stream proxy>|<first three letters of the status> followed by _ and the first three letters of the completion reason when there is one. include_id=True prepends <uuid> =>. include_received_tags=True writes each target as <peer id>_(<tags>) with the tags that it reported.
defto_str(self)->str:"""Return a JSON-encoded string with the core interaction fields for logging. Returns: A JSON string containing requester, action_kwargs, timestamp_created, and uuid. """returnjson.dumps([self.requester,self.action_kwargs,self.timestamp_created,self.uuid])
Returns the JSON string of the list [requester, action_kwargs, timestamp_created, uuid].
defparse_streams(self,streams:list|dict)->None:"""Parse the list of streams provided by the user, standardizing its format and saving it. The user can specify streams in these two ways, where "stream_hash_j" can be just the stream name, the stream group, the net hash, or the user hash. (1) [..., stream_hash_j (str), ...] (2) { "stdin": [..., stream_hash_j (str), ...], "stdtar": [..., stream_hash_k (str), ...], "stdext": [..., stream_hash_z (str), ...], "stdunk": [..., stream_hash_z (str), ...], } The last one (2) optionally specifies if the stream is expected to become an input of the processor ('stdin'), a target ('stdtar'), and extra stream ('stdext'), or no preferences (None). Notice that this choice could be re-arranged by the Interaction Manager, in function of the actual capabilities of the processor. Args: streams (list | dict): The list or dict of streams (see the example above). """invalid_msg=f'Invalid syntax for streams involved in an interaction: {streams}'self.streams={"stdin":[],"stdtar":[],"stdext":[],"stdunk":[]}ifisinstance(streams,list):forstreaminstreams:ifnotisinstance(stream,str):raiseGenException(invalid_msg)self.streams["stdunk"].append(stream)elifisinstance(streams,dict):forredirect,streams_listinstreams.items():ifredirectnotinself.streams:raiseGenException(invalid_msg)forstreaminstreams_list:ifnotisinstance(stream,str):raiseGenException(invalid_msg)self.streams[redirect]=list(streams_list)# Shallow copy (that's why we have "list(...)" - NEEDED!)else:raiseGenException(invalid_msg)
Normalizes the stream specification into streams. Each reference is a str: a stream name, a group, a user hash or a net hash.
A list puts every reference under stdunk. The target is then free to place it.
A dictionary with any of the keys stdin, stdtar, stdext and stdunk keeps each list under its key and copies it. stdin asks for an input of the processor of the target, stdtar for a learning target and stdext for an extra stream. The target may still move a stream that does not fit (see match_streams).
Any other type, an unknown key or a reference that is not a string raises GenException. The result always has the four keys.
def__init__(self,agent:"AgentBasics",max_interactions:int=-1)->None:"""Create an InteractionManager. Args: agent: Back-reference to the owning agent (AgentBasics instance). max_interactions: Maximum number of simultaneously tracked interactions (sent + received + lazy). """self.agent=agentself.max_interactions=max_interactionsifmax_interactions>0elseCustom.MAX_INTERACTIONSself.sent:dict[str|None,Interaction]={}# uuid -> Interaction (sent by this agent)self.received:dict[str|None,Interaction]={}# uuid -> Interaction (received from others)self.lazy:dict[str|None,Interaction]={}# uuid -> Interaction (added by you)self.current:Interaction|None=None# Currently executing interactionself.last_registered:Interaction|None=Noneself.sent_recently_completed:set[Interaction]=set()# Completed interactionsself.received_recently_completed:set[Interaction]=set()# Completed interactionsself.lazy_recently_completed:set[Interaction]=set()# Completed interactions
The bookkeeper of the interactions of one agent. AgentBasics creates it in its constructor as agent.im with max_interactions=Custom.MAX_INTERACTIONS (100). A developer reads it (agent.im.sent, agent.im.get_current()) and rarely calls its methods. The node, the behavior and the built-in actions drive it.
Argument
Type
Default
Meaning
agent
AgentBasics
required
The agent that owns the manager. The manager reads its streams, its known agents and its behaviors.
max_interactions
int
-1
The maximum number of open interactions (sent, received and lazy together). A non-positive value uses Custom.MAX_INTERACTIONS.
The manager keeps three groups. Each group has a dict from uuid to Interaction for the open interactions and a set for the interactions completed and not yet drained.
Group
Open
Completed, not yet drained
Who creates them
Sent
sent
sent_recently_completed
Agent.send on this agent.
Received
received
received_recently_completed
Other agents.
Lazy
lazy
lazy_recently_completed
The behavior of this agent for its own actions (system interactions) and the agent for samples that arrive under an interaction it does not know.
The set of the sent interactions completed and not yet drained. Agent.on_received scans it together with sent because an answer can arrive after the status. Its siblings received_recently_completed and lazy_recently_completed hold the other two groups.
defroom_for_registration(self)->bool:"""Return True if there is capacity to register another interaction."""returnlen(self.sent)+len(self.received)+len(self.lazy)<self.max_interactions
Returns True when the open interactions (sent, received and lazy, completed ones excluded) are fewer than max_interactions.
defcount_interactions(self)->int:"""Return the total number of tracked interactions, including recently completed ones."""return(len(self.sent)+len(self.received)+len(self.lazy)+len(self.sent_recently_completed)+len(self.received_recently_completed)+len(self.lazy_recently_completed))
Returns the number of open interactions plus the completed ones not yet drained.
defclear_from_all_streams(self,interaction:Interaction,clear_data:bool=False)->None:"""Remove the given interaction from every stream that references it. Args: interaction: The interaction to deregister from all the known streams. clear_data: Default False. Forces the removal of the stream data associated to this interaction. """forstream_objinself.agent.known_streams_by_user_hash.values():ifstream_obj.has_interaction(interaction.uuid):stream_obj.remove_interaction(interaction)ifclear_data:stream_obj.remove_data(interaction.uuid)
Detaches interaction from every known stream of the agent that references its uuid. With clear_data=True it also deletes the data that those streams hold under the uuid.
defunregister_all(self)->None:"""Deregister all current interactions"""all_interactions=(set(self.sent.values())|set(self.received.values())|set(self.lazy.values()))forinteractioninall_interactions:self.unregister(interaction)
Calls unregister on every open interaction. A running interaction stays.
defunregister(self,interaction:Interaction)->bool:"""Deregister an interaction from all tracking dicts and dissociate it from streams and actions. Args: interaction: The interaction to remove. Returns: True if the interaction was found and removed from at least one tracking dict. """ifinteraction.status==InteractionStatus.RUNNING:# Avoid de-registering a currently running interactionreturnFalseinteraction.clear_from_action()self.clear_from_all_streams(interaction)found=Falseifself.sent.get(interaction.uuid)isinteraction:delself.sent[interaction.uuid]found=Trueifself.received.get(interaction.uuid)isinteraction:delself.received[interaction.uuid]found=Trueifself.lazy.get(interaction.uuid)isinteraction:delself.lazy[interaction.uuid]found=Truereturnfound
Forgets an interaction without completing it. The method removes the interaction from its action and from every stream and deletes it from sent, received and lazy. It returns False without changes for a RUNNING interaction and otherwise True when it found the interaction in at least one group. No status is sent and no callback runs. Agent.send uses it when no target was reached.
defregister_sent(self,interaction:Interaction,public:bool)->bool:"""Register an interaction that this agent has sent. Args: interaction: The Interaction to register. public: Whether the interaction is about a public agent or a private/world one. Returns: True if registration succeeded; False if there is no room or the streams are invalid. """existing=self.sent.get(interaction.uuid)ifexistingisnotNoneandexistingisnotinteraction:log.error(f"UUID collision on {interaction.uuid}, refusing to evict an in-flight interaction")returnFalseself.__check_callback_method(interaction)ifnotself.room_for_registration():log.error(f"No more room for interactions (limit: {self.max_interactions})")returnFalseifnotInteractionManager.check_consistency_between_action_kwargs_and_interaction_fields(interaction):returnFalse# The error message is printed inside the method# This will resolve target names, data samples, stream namesifnotself.resolve(interaction,public):returnFalse# Ensuring all the streams mentioned in the interaction are known, and normalizing them_,expanded_owned_streams=self.expand_and_normalize_streams(interaction)# Converting format for owned streams (no matter what the matching routine decided)owned_user_hashes_to_stream_objs={_stream_user_hash:self.agent.known_streams_by_user_hash[_stream_user_hash]for_streams_listinexpanded_owned_streams.values()for_stream_user_hashin_streams_list}forstream_objinowned_user_hashes_to_stream_objs.values():stream_obj.add_interaction(interaction)interaction.set_manager(self,stdin_streams={},stdtar_streams={},stdext_streams={},owned_streams=owned_user_hashes_to_stream_objs)# No matter what the interaction does: the processor output streams of the target be aware of the possibility# that this interaction might yield new datafortarget_agentininteraction.target:asserttarget_agentisnotNonestreams_of_target_agent=self.agent.find_streams(target_agent,'processor',discard_owned=True)forstream_dictinstreams_of_target_agent.values():forstreaminstream_dict.values():stream.add_interaction(interaction)# Registeringself.sent[interaction.uuid]=interactioninteraction.status=InteractionStatus.REQUESTEDinteraction.type=InteractionType.SENTself.last_registered=interactionreturnTrue
Registers an interaction that this agent is about to send. Agent.send calls it before the message leaves.
Argument
Type
Meaning
interaction
Interaction
The interaction to register.
public
bool
True on the public network and False in the world. It decides which streams the names resolve to.
The steps are the following.
It refuses the interaction when a different one is already registered with the same uuid.
It checks the callback (a critical log when the method is missing or its signature is wrong), the capacity and the action arguments.
It attaches the interaction to the owned streams that it names and to the processor streams of every target. The answers that arrive on those streams then belong to it.
It stores it in sent with status REQUESTED and type SENT.
It returns True on success and False with an error in the log otherwise.
defregister_received(self,interaction:Interaction,public:bool)->bool:"""Register an interaction received from another agent. Args: interaction: The Interaction to register. public: Whether the interaction is about a public agent or a private/world one. Returns: True if registration succeeded; False if there is no room, streams are invalid, or matching failed. """existing=self.received.get(interaction.uuid)ifexistingisnotNoneandexistingisnotinteraction:log.error(f"UUID collision on {interaction.uuid}, refusing to evict an in-flight interaction")returnFalseifself.__register_received_or_lazy(interaction,public):self.received[interaction.uuid]=interactioninteraction.status=InteractionStatus.RECEIVEDinteraction.type=InteractionType.RECEIVEDreturnTrueelse:returnFalse
Registers an interaction received from another agent. The agent calls it after the behavior accepted the request (see AgentBasics.inject_received_interaction). Besides the checks of register_sent it requires a requester that the agent knows. It resolves the streams without touching the targets and assigns them to the inputs, targets and extras of the processor with match_streams. It then attaches the interaction to those streams and to the processor output streams of the same network. The output of the processor thus travels back to the requester. It stores the interaction in received with status and type RECEIVED. It returns False when a check fails or when a required input of the processor has no stream and no default value.
defregister_lazy(self,interaction:Interaction,public:bool)->bool:"""Register an interaction that you manually generated within this agent. Args: interaction: The Interaction to register. public: Whether the interaction is about a public agent or a private/world one. Returns: True if registration succeeded; False if there is no room or the streams are invalid. """existing=self.lazy.get(interaction.uuid)ifexistingisnotNoneandexistingisnotinteraction:log.error(f"UUID collision on {interaction.uuid}, refusing to evict an in-flight interaction")returnFalseifself.__register_received_or_lazy(interaction,public):self.lazy[interaction.uuid]=interactioninteraction.status=InteractionStatus.LAZYinteraction.type=InteractionType.LAZYreturnTrueelse:returnFalse
Registers an interaction created inside this agent and runs the same checks as register_received. A system requester is accepted. It stores the interaction in lazy with status and type LAZY. The behavior calls it for the system interaction of an action that runs on its own initiative.
defresolve(self,interaction:Interaction,public:bool,resolve_target:bool=True)->bool:# A. Resolving targets"""Resolves the targets and the streams of an interaction to the ones known by the agent. It resolves the target references to peer ids, moves the data samples given as a dictionary into the corresponding streams (turning the interaction into a stream-based one), and resolves the stream references. Args: interaction: The interaction to resolve. public: True when the interaction is on the public network, False for the world one. resolve_target: Whether to resolve the targets too (default: True). Returns: True if everything was resolved, False otherwise (the error is logged). """ifresolve_target:target=interaction.targetiftargetisnotNone:fori,_targetinenumerate(target):assert_targetisnotNone_target_bck=_target_target=self.agent.resolve_agent_ref(_target)if_targetisnotNone:target[i]=_targetelse:log.error(f"Unknown target specified in an interaction ({_target_bck})")returnFalse# B. Moving data samples to streams, if needed (when data_samples is a dictionary)# In this case, "streams" must be None (if not None, then the data_samples field is ignored)already_resolved=Falseifisinstance(interaction.data_samples,dict):# This is already an empty list (otherwise the data_samples field would not be there), but better# be extra safestreams=[]forstream_hash,data_sampleininteraction.data_samples.items():stream_user_hash_or_net_hash=self.agent.resolve_stream_ref(stream_hash,public)ifStream.is_net_hash(stream_user_hash_or_net_hash):log.error("When using a stream name in the data sample field of an interaction, ""it MUST be provided in the form of a stream hash or something that can be unambiguously ""resolved to a stream hash")returnFalseifstream_user_hash_or_net_hashisNone:log.error(f"Unknown stream hash specified in an interaction ({stream_hash})")returnFalsestream_user_hash=stream_user_hash_or_net_hashstream:Stream=self.agent.known_streams_by_user_hash[stream_user_hash]stream.set(data_sample,uuid=interaction.uuid)# Appending the stream to the interaction, that now looks like a stream-based interactionstreams.append(stream_user_hash)# Purginginteraction.data_samples=[]interaction.parse_streams(streams)# Rebuilding the stream dictionariesalready_resolved=True# C. Resolving streamsstreams=interaction.streamsifstreamsisnotNoneandnotalready_resolved:streams:dictforredirect,streams_listinstreams.items():forj,stream_hashinenumerate(streams_list):stream_user_hash_or_net_hash=self.agent.resolve_stream_ref(stream_hash,public)ifstream_user_hash_or_net_hashisNone:log.error(f"Unknown stream hash specified in an interaction ({stream_hash})")returnFalsestreams_list[j]=stream_user_hash_or_net_hash# If it is a net hash, it will be expanded laterreturnTrue
Resolves the references of an interaction (targets, keys of the samples and streams) to the peer ids and stream hashes that the agent knows. It works in three steps.
With resolve_target=True it replaces every target with the peer id returned by AgentBasics.resolve_agent_ref. An unknown target fails the call.
When data_samples is a dict, it resolves each key to a stream user hash, writes the sample on that stream under the uuid of the interaction, empties data_samples and rebuilds streams from the resolved user hashes. A key that resolves to a net hash (a group with more than one stream) fails the call.
Otherwise it resolves each stream reference with AgentBasics.resolve_stream_ref on the network given by public. An unknown reference fails the call.
It returns True when everything resolved and False with an error in the log otherwise. The interaction is modified in place.
defexpand_and_normalize_streams(self,interaction:Interaction)->(tuple[dict[str|None,list[str]],dict[str|None,list[str]]]):"""Resolve all stream references in an interaction to fully-populated stream dicts. Translates user-level and net-level hashes into detailed dicts containing ``user_hash``, ``net_hash``, ``name``, ``group``, and the stream object itself, grouped by their suggested redirection (``'stdin'``, ``'stdtar'``, ``'stdext'``, or ``None``). Args: interaction: The interaction whose stream list should be expanded. Returns: A 2-tuple ``(expanded_streams, expanded_owned_streams)`` where each element is a dict keyed by redirection hint (``'stdin'``, ``'stdtar'``, ``'stdext'``, ``None``) mapping to lists of fully-populated stream dicts. """# Guessing net hash and specific name af each stream: if the name was not provided, then all the streams of the# group are considered. Generating a full list of streams, distinguishing them in function of their suggested# redirection, i.e., 'stdin', 'stdtar', 'stdext', None (meaning 'no suggestions').expanded_streams={'stdin':[],'stdtar':[],'stdext':[],"stdunk":[]}expanded_owned_streams={'stdin':[],'stdtar':[],'stdext':[],"stdunk":[]}# Checkingiflen(interaction.streams)==0:returnexpanded_streams,expanded_owned_streamsforredirect,streams_listininteraction.streams.items():forstream_hashinstreams_list:ifStream.is_user_hash(stream_hash):expanded_streams[redirect].append(stream_hash)ifstream_hashinself.agent.owned_streams_by_user_hash:expanded_owned_streams[redirect].append(stream_hash)elifStream.is_net_hash(stream_hash):streams=self.agent.known_streams[stream_hash]forstream_objinstreams.values():_stream_hash=DataProps.user_hash_from_net_hash(stream_hash,stream_obj.props.get_name())expanded_streams[redirect].append(_stream_hash)if_stream_hashinself.agent.owned_streams_by_user_hash:expanded_owned_streams[redirect].append(_stream_hash)returnexpanded_streams,expanded_owned_streams
Expands the resolved stream references of an interaction into user hashes. A user hash stays as it is. A net hash becomes the user hashes of all the streams of its group. It returns two dicts with the keys stdin, stdtar, stdext and stdunk: all the expanded user hashes and the ones among them that the agent owns. A net hash that the agent does not know raises KeyError.
defmatch_streams(self,expanded_streams:dict)->tuple[bool,dict,dict,dict,dict]:"""Assign expanded stream dicts to stdin, stdtar, or stdext based on processor compatibility. Attempts to match streams to the processor's input and output argument slots, following any redirection hints. Streams that do not fit a processor slot are placed in stdext. Args: expanded_streams: The output of ``expand_and_normalize_streams``; a dict keyed by redirection hint (``'stdin'``, ``'stdtar'``, ``'stdext'``, ``None``) containing lists of fully-populated stream dicts. Returns: A 5-tuple ``(valid, stdin_streams, stdtar_streams, stdext_streams, stdunk_streams)`` where ``valid`` is False if required processor inputs have no matching stream and no default value, and the remaining three elements are ``{user_hash: stream_obj}`` dicts for each category. """# Assigning streams to 'stdin' or 'stdext', following the given suggestions, when possible, and being a bit# heuristic for all the not-well-defined casesprocessor_will_be_used=len(expanded_streams['stdin'])>0orlen(expanded_streams["stdunk"])>0stdin_streams={}stdtar_streams={}stdext_streams={}owned_streams={}foruser_hashinexpanded_streams['stdext']:ifuser_hashnotinself.agent.known_streams_by_user_hash:returnFalse,{},{},{},{}stdext_streams[user_hash]=self.agent.known_streams_by_user_hash[user_hash]ifuser_hashinself.agent.owned_streams_by_user_hash:owned_streams[user_hash]=stdext_streams[user_hash]# We try to match the 'stdin' suggestions with the different input arguments of the processors.# We also consider the streams with no specific suggestions (lower priority).ifprocessor_will_be_used:sources=['stdin','stdunk']assertself.agent.proc_inputsisnotNonepos_stdin_streams=[None]*len(self.agent.proc_inputs)foriinrange(len(self.agent.proc_inputs)):found_match=-1forsourceinsources:forj,user_hashinenumerate(expanded_streams[source]):ifuser_hashnotinself.agent.known_streams_by_user_hash:returnFalse,{},{},{},{}stream_obj=self.agent.known_streams_by_user_hash[user_hash]net_hash=DataProps.build_net_hash(DataProps.peer_id_from_user_hash(user_hash),stream_obj.is_pubsub(),stream_obj.props.name_or_group())name=stream_obj.props.get_name()# If the current input stream is compatible with the i-th input slot...if(net_hash,name)inself.agent.compat_in_streams[i]:pos_stdin_streams[i]=user_hashfound_match=jbreakiffound_match>=0:delexpanded_streams[source][found_match]# Removing the stream from the suggestionsbreak# We ensured that all the not-filled-arguments of the processor have a default value, otherwise no waysforiinrange(len(self.agent.proc_inputs)):ifpos_stdin_streams[i]isNone:assertself.agent.proc_optional_inputsisnotNoneifnotself.agent.proc_optional_inputs[i]["has_default"]:returnFalse,{},{},{},{}else:stdin_streams["<default_input_pos_"+str(i)+">"]=(self.agent.proc_optional_inputs)[i]["default_value"]else:stdin_streams[pos_stdin_streams[i]]=self.agent.known_streams_by_user_hash[pos_stdin_streams[i]]ifpos_stdin_streams[i]inself.agent.owned_streams_by_user_hash:owned_streams[pos_stdin_streams[i]]=stdin_streams[pos_stdin_streams[i]]# Matching targetssources=['stdtar','stdunk']assertself.agent.proc_outputsisnotNonepos_stdtar_streams=[None]*len(self.agent.proc_outputs)foriinrange(len(self.agent.proc_outputs)):found_match=-1forsourceinsources:forj,user_hashinenumerate(expanded_streams[source]):ifuser_hashnotinself.agent.known_streams_by_user_hash:returnFalse,{},{},{},{}stream_obj=self.agent.known_streams_by_user_hash[user_hash]net_hash=DataProps.build_net_hash(DataProps.peer_id_from_user_hash(user_hash),stream_obj.is_pubsub(),stream_obj.props.get_group())name=stream_obj.props.get_name()# If the current input stream is compatible with the i-th input slot...if(net_hash,name)inself.agent.compat_out_streams[i]:pos_stdtar_streams[i]=user_hashfound_match=jbreakiffound_match>=0:delexpanded_streams[source][found_match]# Removing the stream from the suggestionsbreak# We ensured that the not-filled-arguments of the processor have a default value, otherwise no waysforiinrange(len(self.agent.proc_outputs)):ifpos_stdtar_streams[i]isnotNone:stdtar_streams[pos_stdtar_streams[i]]=self.agent.known_streams_by_user_hash[pos_stdtar_streams[i]]ifpos_stdtar_streams[i]inself.agent.owned_streams_by_user_hash:owned_streams[pos_stdtar_streams[i]]=stdtar_streams[pos_stdtar_streams[i]]# We add to 'stdext' all the streams that did not fit the processor (both coming from suggestions in 'stdin' or# not suggested at all)sources=['stdin','stdtar','stdunk']forsourceinsources:foruser_hashinexpanded_streams[source]:ifuser_hashnotinself.agent.known_streams_by_user_hash:returnFalse,{},{},{},{}stdext_streams[user_hash]=self.agent.known_streams_by_user_hash[user_hash]ifuser_hashinself.agent.owned_streams_by_user_hash:owned_streams[user_hash]=stdext_streams[user_hash]returnTrue,stdin_streams,stdtar_streams,stdext_streams,owned_streams
Assigns the expanded streams to the processor of the agent. It takes the first output of expand_and_normalize_streams and consumes it.
Every stdext stream goes to the extras.
When stdin or stdunk is not empty, each input of the processor takes the first stream of stdin (then of stdunk) compatible with that input. An input without a stream takes its default value. An input without a stream and without a default makes the match invalid.
For each output of the processor it takes the first stream of stdtar (then of stdunk) compatible with that output as its learning target.
Every stream left in stdin, stdtar or stdunk goes to the extras.
It returns (valid, stdin, stdtar, stdext, owned). The last four elements are dicts from user hash to stream object (or default value). A stream that the agent does not know makes the whole match invalid and returns empty dictionaries.
defcheck_if_doable(self,interaction:Interaction)->bool:"""Return True if the given interaction can be executed right now. An interaction is doable when it is not yet completed, the requester is a known agent, and either all involved streams have fresh data. Args: interaction: The interaction to evaluate. """requester_is_known=interaction.requesterinself.agent.all_agentsreturn(notinteraction.completedandrequester_is_knownand(interaction.get_new_stream_data_tags(all_fresh_or_fail=True)isnotNone))
Returns True when interaction is not completed, its requester is a known agent and every one of its streams has a fresh sample (see Interaction.get_new_stream_data_tags). The behavior asks it before running the action for that interaction.
@staticmethoddefcheck_consistency_between_action_kwargs_and_interaction_fields(interaction:Interaction)->bool:"""Checks that the action kwargs of an interaction contain no reserved name and agree with its fields. Args: interaction: The interaction to check. Returns: True if the kwargs are consistent, False otherwise (the error is logged). """fork,vininteraction.action_kwargs.items():ifkinCustom.RESERVED_IN_ACTION_KWARGS:log.error(f"Tried to register and interaction that includes a "f"private/not-allowed argument: {k} not allowed in action_kwargs")returnFalseifkinCustom.INTERACTION_FIELD_NAMESandv!=getattr(interaction,k):log.error(f"Tried to register and interaction that includes a "f"private/not-allowed argument: {k} echoed inconsistently,"f" {v} vs {getattr(interaction,k)}")returnFalsereturnTrue
Static method that validates action_kwargs before registration. It returns False with an error in the log in two cases: (1) a key is reserved to the framework (max_duration, retry_timeout, delay, action_kwargs, interaction) and (2) a key names a field of the interaction (streams, num_steps, target, timeout, copy_sys, forced_uuid, id, volatile, data_samples, callback, num_samples_to_stream) with a value different from that field. It returns True otherwise.
defget_last_registered(self)->Interaction|None:"""Return the most recently registered interaction, or None if none have been registered."""returnself.last_registered
defset_current_as_paused(self)->None:"""Set the current interaction as something that was started but now must be paused because some other interactions are handled."""ifself.currentisnotNone:self.current.mark_paused()
Marks the current interaction PAUSED if there is one. The behavior calls it when it leaves a multi-step action to serve something else.
defset_current(self,interaction:Interaction|None)->None:"""Set the given interaction as the currently executing one. This marks the interaction as running and configures the agent's stdin/stdout to point to the correct streams for this interaction. Args: interaction: The Interaction to set as current. """self.current=interactionfirst_time=interactionisnotNoneandnotinteraction.running# Default stream bindings (this also automatically switches from private to public and vice versa)self.agent.set_default_stream_binding()ifinteractionisnotNone:interaction.mark_running()iflen(interaction.stream_proxy)>0:# Restart buffered streams and activate them if they were offiffirst_time:forstreamininteraction.stream_proxy:ifisinstance(stream,BufferedStream):stream.restart(interaction.uuid)# Every interaction with some-streams-specified forces the interaction-described bindingsself.agent.stdin.bind(interaction.stdin_streams,uuid=interaction.uuid)self.agent.stdtar.bind(interaction.stdtar_streams,uuid=interaction.uuid)self.agent.stdext.bind(interaction.stdext_streams,uuid=interaction.uuid)self.agent.stdout.bind_uuid_only(interaction.uuid)
Makes interaction the current one. The behavior calls it right before running an action. It first restores the default bindings of the standard streams of the agent on the network where the agent behaves. With an interaction it marks it RUNNING. When the interaction has streams, the method restarts the buffered ones at the first call for that interaction. It binds stdin, stdtar and stdext of the agent to the streams of the interaction and stdout to its uuid. None only clears the current interaction and restores the defaults.
defhas_data(self,interaction:'Interaction')->bool:"""Return True if any owned stream has data available for the given interaction. Args: interaction: The interaction to check data availability for. """forstream_objinself.agent.owned_streams_by_user_hash.values():ifstream_obj.has_data(interaction.uuid):returnTruereturnFalse
Returns True when at least one owned stream of the agent holds data under the uuid of interaction.
defget_recipients(self,interaction:'Interaction')->list[str]:"""Return the list of peer IDs that should receive data generated by the interaction. For sent interactions the recipients are the interaction targets; for received interactions it is the original requester; for lazy interactions it is the interaction targets. Unknown (unregistered) interactions fall back to the interaction's target list. Args: interaction: The interaction whose recipients should be determined. Returns: A list of peer ID strings, filtering out any ``None`` entries. """ifself.is_known(interaction):ifself.is_sent(interaction):recipients=interaction.target# This is always a list, even when with 1 element onlyelifself.is_received(interaction):recipients=[interaction.requester]# This is always 1 element, we make it a listelifself.is_lazy(interaction):recipients=interaction.target# This is always a list, even when with 1 element onlyelse:raiseGenException("Unexpected case of a known interaction that is both not sent or received")else:# This is the case of a not-registered interaction.recipients=interaction.target# This is always a list, even when with 1 element onlyreturn[xforxinrecipientsifxisnotNone]
Returns the peer ids that receive the samples generated for interaction: the targets for a sent or lazy interaction, the requester for a received one and the targets for an interaction that the manager does not know. None entries are dropped. The agent calls it when it sends the samples of its streams.
asyncdefcomplete(self,interaction:'Interaction',reason:'CompletionReason',dest_state:str|None=None,target:str|None=None)->None:"""Mark an interaction as completed and move it to the recently-completed set, removing it from its action (async). Args: interaction: The interaction to complete. reason: The reason for completion. dest_state: The destination state reached, if any. target: The target agent who completed the interaction (Default: None). """ifinteractionisnotNoneandnotinteraction.completed:interaction.mark_completed(reason,dest_state=dest_state,target=target)interaction.clear_from_action()# We do not remove it from streams yet - it might be needed for sendingifinteraction.completed:ifself.sent.get(interaction.uuid)isinteraction:self.sent_recently_completed.add(interaction)delself.sent[interaction.uuid]ifself.received.get(interaction.uuid)isinteraction:self.received_recently_completed.add(interaction)delself.received[interaction.uuid]ifself.lazy.get(interaction.uuid)isinteraction:self.lazy_recently_completed.add(interaction)delself.lazy[interaction.uuid]# Running callback method, if anyifinteraction.callbackisnotNone:callback_method=getattr(self.agent,interaction.callback)self.agent.behav_lone_wolf.enable(False)self.agent.behav.enable(False)ifinteraction.requesterinself.agent.public_agents:self.agent.behav_lone_wolf.enable(True)else:ifself.agent.in_world():self.agent.behav.enable(True)awaitcallback_method(interaction=interaction)# "Calling callback!"self.agent.behav_lone_wolf.enable(False)self.agent.behav.enable(False)
Completes an interaction (async). It does nothing on None or on an interaction already completed.
Argument
Type
Default
Meaning
interaction
Interaction
required
The interaction.
reason
CompletionReason
required
Why it completed.
dest_state
str or None
None
The state reached.
target
str or None
None
Complete only the entry of this target.
It calls Interaction.mark_completed and removes the interaction from its action. When the whole interaction is now completed it moves it from its open group to the matching *_recently_completed set. When the interaction has a callback, the manager disables both behaviors of the agent and enables one of them for the duration of the call. The public behavior is enabled when the requester is in public_agents. Otherwise the world behavior is enabled when the agent is in a world. The manager then awaits getattr(agent, callback)(interaction=interaction) and disables both behaviors again. On an interaction sent by this agent the requester is the agent itself and never belongs to public_agents. Two consequences follow: (1) an agent in a world runs the callback with its world behavior enabled even for a request sent on the public network and (2) an agent outside any world runs it with no behavior enabled. The stream data stays until the drain.
asyncdefcomplete_current(self,dest_state:str,reason:'CompletionReason')->None:"""Mark the current interaction as completed (async). Args: dest_state: The destination state reached by completing this action. reason: The reason for completion. """ifself.currentisnotNone:awaitself.complete(self.current,dest_state=dest_state,reason=reason)self.current=None
Completes the current interaction with reason and dest_state (async) and clears current. The behavior calls it with CompletionReason.OK when an action completes and the machine moves to dest_state.
defdrain_completed(self)->list[Interaction]:"""Return and clear the list of recently completed interactions. Used by the agent's ``behave()`` loop to send status notifications. Returns: List of Interaction objects that were recently completed. """cur_time=clock.get_time()cur_clock_cycle=clock.get_cycle()drained=[]forrecently_completedin[self.sent_recently_completed,self.received_recently_completed,self.lazy_recently_completed]:to_remove=[]fori,interactioninenumerate(recently_completed):# Wait AT LEAST 1 clock cycle, to allow sending samples generated during the interaction# Of course, "disconnected"-agent-related interactions are immediately drainedif(interaction.completion_reason==CompletionReason.DISCONNECTEDor(interaction.cycle_completed<cur_clock_cycleand(cur_time-interaction.timestamp_completed)>Custom.DRAIN_TIMEOUT)):log.inter(f"Draining {interaction.to_code_str(True)} "f"(cycle_completed={interaction.cycle_completed})")to_remove.append(interaction)drained.append(interaction)forinteractioninto_remove:self.sent_recently_completed.discard(interaction)self.received_recently_completed.discard(interaction)self.lazy_recently_completed.discard(interaction)# Clearing from all the owned and not-owned streams (all), that might have been used for output purposes# by the current agent or by others.# In principle, only the processor streams should be involved, since it is the only one in which we plug# this interaction in this class.# However, the user might have added the interaction to other owned streams.ifnotself.is_known(interaction):# If, meanwhile, another interaction with the same UUID (e.g., None) was received,# do not clear it from the streamsself.clear_from_all_streams(interaction)returndrained
Returns the completed interactions ready for notification and removes them from the three *_recently_completed sets. An interaction is ready when it completed in an earlier clock cycle or with DISCONNECTED. The wait of at least one tick gives the samples produced by the action time to leave. A drained interaction that the manager no longer knows is detached from every stream. AgentBasics.behave calls it at every tick and sends the status of each drained interaction to its requester.
asyncdefcomplete_expired(self)->None:"""Remove expired (or no-action-based) interactions and return them for notification (async). Checks all received and sent interactions against the retry_timeout. Expired interactions are marked as COMPLETED with TIMEOUT reason and removed from the tracking dicts. """forinteractioninlist(self.sent.values())+list(self.received.values())+list(self.lazy.values()):ifinteraction.status==InteractionStatus.COMPLETED:continueelifinteraction.is_expired(Custom.DEFAULT_INTER_TIMEOUT)orinteraction.action_nameisNone:awaitself.complete(interaction,reason=CompletionReason.TIMEOUT)elifinteraction.volatileandself.is_sent(interaction):awaitself.complete(interaction,reason=CompletionReason.TIMEOUT)else:ifself.is_received(interaction)andinteraction.requesternotinself.agent.all_agents:awaitself.complete(interaction,reason=CompletionReason.DISCONNECTED)ifself.is_sent(interaction):fortargetininteraction.target:iftargetnotinself.agent.all_agents:awaitself.complete(interaction,reason=CompletionReason.DISCONNECTED,target=target)
Completes the open interactions that have to end (async). AgentBasics.behave calls it at every tick.
Condition
Reason
Older than its timeout (300 seconds at most, see Interaction.is_expired) or without an action name
TIMEOUT
Sent and volatile
TIMEOUT
Received from a requester that the agent no longer knows
defclear_expired_stream_data(self)->None:"""Purge stale buffered data from streams whose associated interaction is done or gone."""all_interactions=list(self.received.values())+list(self.sent.values())+list(self.lazy.values())forinteractioninall_interactions:assertinteractionisnotNoneforstreamininteraction.stream_proxy:# In case of data samples or default input values, skipifnotisinstance(stream,Stream):continue# We only consider streams whose interactions were either removed, or are already completed, or# were just created (artificial interaction, for example the ones created just to send a sample)_interaction=stream.get_interaction(interaction.uuid)if_interactionisNoneor_interaction.completedor_interaction.created:# This will also clear the associated (completed) interaction, if still therestream.clear_expired_data(Custom.DEFAULT_INTER_TIMEOUT)
For each open interaction, it asks every stream of the interaction to drop its data older than Custom.DEFAULT_INTER_TIMEOUT. The method asks only the streams whose interaction under that uuid is gone, completed or still in status CREATED. AgentBasics.behave calls it at every tick.
asyncdefupdate_sent_status(self,status_dict:dict)->None:"""Update a previously sent interaction's status from a received status message (async). Args: status_dict: Dict from Interaction.to_status_dict(). """sender=status_dict.get('status_generated_by')uuid=status_dict.get('uuid')# UUID can be None (meaning generic UUID, still valid!), recall thisifuuidinself.sent:# Collecting datainteraction=self.sent[uuid]interaction_status=InteractionStatus(status_dict['status'])ifstatus_dict.get('completion_reason'):completion_reason=CompletionReason(status_dict['completion_reason'])else:completion_reason=CompletionReason.OKinteraction_destination_state=status_dict.get('destination_state')# Recording data tagsdata_tags:dict[str,list[int]]|None=status_dict.get('data_tags',None)ifdata_tagsisnotNone:interaction.record_data_tags(data_tags,target=sender)# Mark the completion from the senderifinteraction_status==InteractionStatus.COMPLETED:awaitself.complete(interaction,dest_state=interaction_destination_state,reason=completion_reason,target=sender)
Applies a status message from a target to the sent interaction with the same uuid (async). It does nothing for an unknown uuid. It records the data tags of the message for that target and, when the status is COMPLETED, completes the entry of that target with the reason of the message (OK when missing) and its destination state. The node calls it for every status message.
defis_received(self,interaction:Interaction)->bool:"""Return True if the interaction was received from another agent (active or recently completed). Args: interaction: The interaction to check. """returninteraction.uuidinself.receivedorinteractioninself.received_recently_completed
Returns True when interaction is open in received or is in received_recently_completed.
defis_sent(self,interaction:Interaction)->bool:"""Return True if the interaction was sent by this agent (active or recently completed). Args: interaction: The interaction to check. """returninteraction.uuidinself.sentorinteractioninself.sent_recently_completed
Returns True when interaction is open in sent or is in sent_recently_completed.
defis_lazy(self,interaction:Interaction)->bool:"""Return True if the interaction was lazily generated within this agent (active or recently completed). Args: interaction: The interaction to check. """returninteraction.uuidinself.lazyorinteractioninself.lazy_recently_completed
Returns True when interaction is open in lazy or is in lazy_recently_completed.
defis_known(self,interaction:Interaction)->bool:"""Return True if the interaction is tracked in any of sent, received, or lazy dicts. Args: interaction: The interaction to check. """returnself.is_received(interaction)orself.is_sent(interaction)orself.is_lazy(interaction)
Returns True when one of is_received, is_sent and is_lazy is True.
defget_interaction(self,uuid:str|None,consider_completed_too:bool=False)->Interaction|None:"""Look up an interaction by UUID across the active tracking dicts. Args: uuid: The UUID string to look up. consider_completed_too: When True, also search the recently-completed sets and return the most recently completed match (there may be more than one with the same UUID). Returns: The matching Interaction, or None if not found. """ifuuidinself.received:returnself.received[uuid]elifuuidinself.sent:returnself.sent[uuid]elifuuidinself.lazy:returnself.lazy[uuid]else:ifconsider_completed_too:found_so_far:Interaction|None=Noneforinterinself.received_recently_completed:ifinter.uuid==uuid:iffound_so_farisNoneorfound_so_far.timestamp_completed<inter.timestamp_completed:found_so_far=interforinterinself.sent_recently_completed:ifinter.uuid==uuid:iffound_so_farisNoneorfound_so_far.timestamp_completed<inter.timestamp_completed:found_so_far=interforinterinself.lazy_recently_completed:ifinter.uuid==uuid:iffound_so_farisNoneorfound_so_far.timestamp_completed<inter.timestamp_completed:found_so_far=interreturnfound_so_far# It returns the last completed, there could be more than one with the same UUIDelse:returnNone
Looks up an interaction by uuid in received, then sent, then lazy. With consider_completed_too=True and no open match it searches the three completed sets and returns the match with the latest completion time. Several completed interactions can share a uuid. It returns None when nothing matches.
defadd_lazy_stream_to_interaction(self,stream_hash:str,interaction:Interaction)->None:"""Attach a stream (identified by hash) to an already-registered interaction as a lazy stream. Args: stream_hash: A user-level or net-level stream hash to resolve and attach. interaction: The interaction to attach the stream to. """user_hashes=self.__normalize_to_user_hashes(stream_hash)log.debug(f"[add_lazy_stream_to_interaction] stream_hash={stream_hash}, user_hashes={user_hashes}, "f"interaction={interaction}")foruser_hashinuser_hashes:stream_obj=self.agent.known_streams_by_user_hash[user_hash]stream_obj.add_interaction(interaction)interaction.add_lazy_stream(user_hash,stream_obj,is_owned=user_hashinself.agent.owned_streams_by_user_hash)
Attaches a stream to an interaction already registered. stream_hash can be a user hash or a net hash (all the streams of the group). Each stream records the interaction and the interaction receives the stream through Interaction.add_lazy_stream. The agent uses it to attach the buffered copy of a stream of another agent to the interaction that produced it.
asyncdefremove_interactions_of_agent(self,agent:str)->None:"""Complete and deregister all interactions that involve the given agent as requester or target (async). Args: agent: Peer ID of the agent being removed. """interaction_dicts=[self.sent,self.received,self.lazy]forinteraction_dictininteraction_dicts:foruuid,interinlist(interaction_dict.items()):# Do not remove list(...)ifinter.requester==agent:awaitself.complete(inter,reason=CompletionReason.DISCONNECTED)ifagentininter.target:awaitself.complete(inter,reason=CompletionReason.DISCONNECTED,target=agent)
Completes with DISCONNECTED every open interaction requested by agent and the entry of agent in every open interaction that targets it (async). AgentBasics.remove_agent calls it when a peer leaves.