Actions¶
An action is an async method of an agent marked with @action. Behaviors label their transitions with actions (see Behaviors) and other agents request them with send (see Interactions). Agent comes with a set of built-in actions. A world adds the actions of each role with a subclass of Agent in the role file (see Worlds).
from unaiverse.agent import Agent, action
class Student(Agent):
@action
async def take_exam(self, subject: str, interaction=None) -> bool:
answer = await self.solve(subject)
return answer is not None
The contract¶
- The method is
asyncand returns abool. The decorator@actioncomes fromunaiverse.agent. Truemeans that the action completed and the behavior moves to the destination state of the transition.Falsemeans that the action has not finished yet or has failed. The behavior stays in the state and tries the action again at a later tick. With aretry_timeouton the transition it keeps retrying that action until the timeout runs out. Without one it moves on to the other actions of the state.- Returning
Noneis an error. The node logs it as critical and the action counts as failed. Any other value counts by its truth value. - An exception inside the action is logged with its traceback and counts as
False. The node keeps running.
Arguments¶
The behavior replaces the wildcards in the action_kwargs of the transition and passes them to the action. For a request, the arguments are the action_kwargs that the requester passed to send. The decorator then resolves the values of the arguments with the names below.
| Argument names | Resolved from | To |
|---|---|---|
agent, agents, partner, partners, target, targets |
a node name, owner/name or a peer id (or a list of them) |
peer ids known to the agent |
stream, streams |
a stream name, a group or a user hash (or a list) | user hashes or net hashes on the network of the running behavior |
A value that the agent cannot resolve stays as it was. The decorator leaves the arguments of send alone because send resolves them itself.
A parameter named interaction receives the Interaction that the action is serving. Its presence also makes the action request-only. Unless the transition says "ready": true, the behavior then runs it only when another agent requests it. When the behavior runs an action on its own initiative, the action receives a system interaction that the agent creates for itself.
Steps and timing¶
An interaction with num_steps greater than one makes the target run the action once per step with one sample at each step. Inside the action these methods of the agent describe the step.
| Method of the agent | Returns |
|---|---|
get_current_interaction() |
The interaction being served. |
get_action_step() |
The index of the current step (the first is 0). |
is_last_action_step() |
True on the last step. |
is_multi_steps_action() |
True when the action spans more than one step. |
force_action_step(step) |
Jumps to another step. |
The transition can limit the action with max_duration (its maximum life) and retry_timeout (how long the machine keeps retrying it after a False).
Long computations¶
An action runs inside the tick and holds the agent while it runs. A computation that takes seconds would freeze the agent. Two tools prevent this.
- The processor call runs in a worker thread of its own (see Agents).
processandlearnrely on it. self.stepwise(interaction, make_gen, *args, retry_timeout=60.0, **kwargs)slices any other computation into chunks.make_gen(*args, **kwargs)builds a generator that yields at each chunk boundary and returns the result. Each call advances one chunk and returns(False, None)until the generator ends. The call that ends it returns(True, result). Pastretry_timeoutseconds the computation is dropped and the action is discarded. Without an interaction (a direct call from your code)stepwiseruns the whole generator at once.
@action
async def index_documents(self, interaction=None) -> bool:
done, n = self.stepwise(interaction, self.index_in_chunks, self.documents)
if not done:
return False # the behavior calls it again at the next tick
print(f"Indexed {n} documents")
return True
Built-in actions¶
All the actions below are methods of Agent (unaiverse.agent).
Data and models¶
| Action | Returns True when |
|---|---|
process(interaction=None) |
It ran one inference step by reading the inputs of the processor, running it and writing the outputs. |
learn(interaction=None) |
It ran one learning step made of an inference followed by a backward pass with the losses and the optimizer of proc_opts (see Learning over time). |
record(interaction=None, record_uuid="see_interaction_uuid") |
It recorded num_steps samples from the input of the interaction into a new buffered stream group of its own and offered it by broadcast. |
evaluate(stream_hash, how, steps=100, re_offset=False, agents_to_evaluate=None) |
It compared what the agents generated with a local reference stream. how is "mse", "max" or "geq<x>". The code refuses every other value and therefore also "same". |
compare_eval(cmp, thres, good_if_true=True) |
The results of the last evaluation pass the comparison cmp with the threshold thres. cmp is one of "<", ">", "<=", ">=", "min" and "max". The action also fills the list of the agents that passed (the wildcard <valid_cmp>). |
on_received(processing_fcn=None, data_type=None) |
At least one answer to a request of this agent arrived on a stream of the world network. With processing_fcn (a method name) it calls method(peer_id, props, data, data_tag) on each answer (see Interactions). |
show(interaction=None) |
Always. It prints the interaction and is meant to be overridden as a callback. |
nop(message=None) |
Always. It does nothing except printing message. |
Requests¶
| Action | Returns True when |
|---|---|
send(action_name, target, ...) |
At least one target was reached (see Interactions). |
all_sent_completed(action_name=None) |
No interaction sent with that action name (or with any name) is still open. |
Finding and engaging agents¶
Engagement pairs an agent with other agents for a task inside a world. One agent finds candidates and offers them engagement and each candidate accepts or refuses.
| Action | Returns True when |
|---|---|
find_agents(role, engage=False, handshake_completed=False) |
It found known agents with that role. They go into the list of found agents. With engage=True they are engaged at once. |
connect_by_role(role, filter_fcn=None, accept_already_connected=False) |
It found at least one agent with that role in the world and started connecting to it. filter_fcn names a method that filters the candidates. |
connect_to(peer_id) |
It started connecting to a peer of the world or it was already connected to it. |
send_engage() |
It offered engagement to the found agents. |
engage(acceptable_role=None, sender_role=None, interaction=None) |
It accepted an engagement request from an agent with an acceptable role. Request-only. |
all_engagements_completed() |
Every found agent has accepted or been discarded. |
set_engaged_partner(agent, clear_found=True) |
It made the given agent (or agents) the only engaged partners. |
send_disengage(send_disconnection_too=False) |
It asked the engaged agents to disengage. |
disengage(disconnect_too=False, interaction=None) |
It accepted a disengagement request. Request-only. |
disengage_all() |
It disengaged every engaged agent. |
agents_are_waiting() |
Some agents connected and are not yet fully known. |
connected(agent=None, handshake_completed=False) |
The given agents (by id or wildcard) are connected. |
disconnected(agent=None, handshake_completed=False) |
The given agents are no longer connected. |
disconnect(agent) |
It closed the link with the agent. |
disconnect_by_role(role, disengage_too=False) |
It closed the links with every agent of that role. |
Streams and playlists¶
| Action | Returns True when |
|---|---|
send_subscribe(agent=None, stream_hashes=None, unsubscribe=False) |
It asked the agents to subscribe to (or leave) broadcast streams. |
subscribe(stream_owners=None, stream_props=None, unsubscribe=False, interaction=None) |
It subscribed to (or left) the streams of the request. Request-only. |
set_pref_streams(net_hashes, repeat=1) |
It filled the playlist of preferred streams and repeated it repeat times. |
first_pref_stream(), next_pref_stream() |
It moved the pointer of the playlist to the first or the next stream (wrapping at the end). |
check_pref_stream(what="last") |
The pointer passes the check named by what. The checks are "first", "last", "last_round" (a full round is over), "last_song" and their negations with the prefix not_. |
The world¶
| Action | Returns True when |
|---|---|
ask_world_stats(filters=None) |
It sent a statistics request to the world. The answer arrives later and merges into the local view of the statistics (see Worlds). |
suggest_role_to_world(agent, role) |
It suggested a new role for the agent to the world. |
suggest_badges_to_world(agent=None, score=-1.0, badge_type="completed", badge_description=None) |
It suggested a badge for the agent. badge_type is completed, attended, intermediate or pro. The action itself refuses only a negative score. The world accepts a badge only with a score in [0, 1] (see Worlds). |