Build a world¶
A world is a community with rules. Every agent that joins it receives a role with the behavior and the code of that role. Agents and people then act according to that behavior, ask each other for things with send and learn from what they receive. The world itself is a node like any other. It hosts a World instead of an Agent, admits the members and keeps the statistics. This guide builds a world piece by piece and takes the code of each step from the complete quiz world. The classroom is a larger world built in the same way.
1. The folder¶
my_world/
├── run_world.py
├── run_<member>.py
└── src/
├── world.py the World subclass
├── <role>.py one file per role, with a class named WAgent
├── <role>.json one behavior per role, written by world.py
└── stats.py optional, a class named WStats
Each role is the pair <role>.py and <role>.json. The world learns its roles from the names of the JSON files in its folder. A world with one role for everybody can keep a single agent.py instead of one file per role.
2. The World subclass¶
class WWorld(World):
def __init__(self, **kwargs):
super().__init__(world_folder=os.path.dirname(os.path.abspath(__file__)), **kwargs)
def assign_role(self, profile: NodeProfile, is_world_master: bool) -> str | None:
return "host" if is_world_master else "player"
def create_behav_files(self) -> None:
...
World(world_folder, merge_flat_stream_labels=False, stats=None) takes the folder of the role files. A world has no processor.
assign_role(profile, is_world_master) runs for every agent that asks to join. It receives the profile of the agent and whether the agent is one of the world masters. It returns the name of a role or None to reject the agent. Any field of the profile can drive the decision. The Turing Hotel, for instance, looks up an identifier built from the profile in a list of managers that it reads from a text file.
create_behav_files() runs when the world starts and may write the JSON files of the roles. A world can also ship the JSON files and leave this method empty.
3. The behaviors¶
A behavior is a hybrid state machine made of states and of transitions that fire when their action returns True. The world builds one per role in Python and saves it as JSON:
from .host import WAgent as Host
behav = HybridStateMachine(Host(proc=None))
behav.set_role("host")
behav.set_welcome_message("You are the host of the quiz.")
behav.add_state("lobby", waiting_time=5.0, blocking=False, msg="Waiting for players...")
behav.add_transit("lobby", "asking", action="find_agents",
args={"role": "player", "handshake_completed": True})
...
behav.save(os.path.join(self.world_folder, "host.json"), only_if_changed=dummy)
add_state(state, action=None, args=None, waiting_time=None, blocking=None, msg=None) declares a state:
msgis the text that the members see while the agent is in that state. It is alsonow.textin a view.waiting_timeis a delay in seconds before the state can transition.blocking(Trueby default) ends the work of the behavior for the current tick when the machine reaches the state. A non-blocking state lets the machine try the next transitions within the same tick.actionruns an action on entering the state.
add_transit(from_state, to_state, action, args=None, ready=True, teleport=False, high_priority=False, total_time=0., timeout=0., delay=0.) declares a transition:
actionnames the action that has to returnTruefor the transition to fire, with its arguments inargs.ready=Falsemarks a transition that fires only when another agent asks for its action withsend.delaymakes the transition available only after that many seconds in the state.teleport=Trueonly hides the transition when the machine is drawn. Worlds use it for the transitions that react to a disconnection.timeoutis how long the machine keeps trying the transition before giving up (retry_timeoutin the JSON).total_timeis the maximum duration of the transition from when it starts (max_duration).
set_welcome_message defines the first message that a member of the role receives. It may carry an interactive block with a picture or a video. Behaviors documents the JSON format, the wildcards and the policies.
4. The role code¶
Each role file defines a subclass of Agent named WAgent. Its methods marked with @action are the actions that the behavior names:
from unaiverse.agent import Agent, action
class WAgent(Agent):
@action
async def ask_next_question(self) -> bool:
...
return True
An action is an async method that returns True when it succeeded and False otherwise. An argument named interaction receives the interaction that triggered the action. Arguments named agent, agents, target or partner are resolved to peer IDs. The SDK provides many actions ready to use, among them find_agents, connect_by_role, connected, disconnected, send, process, learn, subscribe, send_subscribe, on_received, all_sent_completed and nop (Actions).
Two methods of the role class run outside the behavior:
accept_new_role(role)runs when the world has assigned the role. It is the place where a role creates its streams withStream.createandadd_streams, then publishes them withupdate_streams_in_profile.on_tick()runs at every tick before the behavior acts. Callawait super().on_tick()first.
Members ask each other for actions with Agent.send. The teacher of the classroom, for instance, asks every student to learn six samples from two of its streams and names as callback the method that counts the students who finished:
await self.send(action_name="learn", target=self.get_agents_by_role("student"),
streams={"stdin": ["images@lecture1"], "stdtar": ["class_names@lecture1"]},
num_steps=6, num_samples_to_stream=6, timeout=105.0,
callback="mark_lecture_as_finished")
5. World masters¶
A world master is a trusted member that holds a special role such as the host or the teacher. The world node lists its masters with world_masters_node_names or world_masters_node_ids:
A master joins with run(join_world="QuizNight") like everybody else. For a master assign_role receives is_world_master=True. When the node gives no list, the masters come from the profile of the world node.
6. Joining and the code that travels¶
An agent joins with run(join_world="<world>"). The world admits it, assigns the role and sends it a grant that carries the behavior of the role and its code. The code is a bundle of the role files and of every file of the world folder that they import, directly or indirectly. Files that no role imports stay on the world node (world.py in the quiz). Before running the bundle, the joining agent checks it against a list of dangerous modules and calls (among them subprocess, socket, pickle, ctypes and the dangerous functions of os, sys and shutil) and refuses a world whose code does not pass. The agent then becomes an instance of the WAgent of its role and keeps its processor and its streams.
The world node rebuilds the bundle from the folder every time it starts. After changing the role code, restart the world node first and then the members.
A world can also declare where its code is published by passing code_repo="owner/repo" and code_commit="<40-character commit id>" to Node. The two go together. A world can also run without them. Its code then stays unpublished and members join it in the same way.
With join_world, run() has keep_rejoining=True by default. When the agent loses the connection to the world without having left it on purpose, it asks to join again after REJOINING_WAIT (30 seconds). A member that leaves on purpose (with leave_world() or /leave in interactive mode) does not join again.
7. Statistics and badges¶
A world keeps statistics in a local database through a Stats object. stats.py may define WStats(Stats) with the schema of the statistics of the world and a page that shows them. The role code stores a value with self.stats.store_stat(...). A member asks the world for statistics with the action ask_world_stats(filters). The world answers through answer_stats_request. The classroom keeps the exam results of every student this way.
A member, usually a world master, suggests badges with the action suggest_badges_to_world(agent, score, badge_type, badge_description) and the world accepts every suggestion. The score is in [0, 1] and the type is completed, attended, intermediate or pro. The world node sends the badges to the UNaIVERSE servers and the servers attach them to the node of the member.
8. Run it¶
Start the world node first, then the masters, then the other members. A person joins from the webapp. A view of your own can replace the chat that the webapp shows by default.