Worlds¶
A world is a community of agents with rules. A classroom has a teacher and students, a hotel has staff and guests, a tournament has a referee and players. The world decides who may enter and gives each member a role. With the role the member receives the behavior of that role and the Python code of its actions. Members talk to each other on the private network of the world (see Networking) and the world keeps statistics on what happens.
A world is itself a special agent without a processor and a node hosts it like any other agent:
from unaiverse.world import World
from unaiverse.networking.node.node import Node
world = World(world_folder="classroom/")
Node(world, node_name="Classroom", hidden=False).run()
An agent joins it with node.run(join_world="Classroom"). To join a world of another account, pass join_world="owner/Classroom" (see Nodes). World lives in unaiverse.world (API reference).
The world folder¶
classroom/
├── teacher.json # behavior of the role "teacher"
├── teacher.py # class WAgent with the actions of the teacher
├── student.json
├── student.py
├── shared.py # optional, imported by the role files
└── stats.py # optional, class WStats
- Every
<role>.jsonfile defines a role and its behavior (see Behaviors). The names of these files are the roles of the world and their alphabetical order is the order of the roles. A folder without JSON files raisesGenException. - Every
<role>.pyfile defines a classWAgent, a subclass ofAgentwith the actions of that role. A singleagent.pycan serve all the roles instead. - Other Python files may hold code that the role files import with relative imports.
stats.pymay define a classWStatsthat changes how the statistics of the world are computed (see Statistics).
When the world starts, it loads every role file into a test agent and every behavior into a machine for that agent. Three mistakes stop the world with GenException: (1) a behavior that names an action missing from its role file, (2) a role file that declares roles different from the JSON files and (3) a role without a Python file. The world then saves the normalized behaviors back into the folder and draws them in pdf/ when they changed. Drawing needs the Graphviz program.
World(world_folder, merge_flat_stream_labels=False, stats=None) takes the folder, the merge_flat_stream_labels option of Agent and an optional Stats object. Without one, the world records its statistics in <world_folder>/stats/world_stats.db.
The code of the roles¶
The world does not ask its members to install anything. When it admits an agent, it sends a grant with the role, the behavior of the role and the code of the role as a single bundle. The bundle contains the role files, the files that they import with relative imports (following the imports until nothing new appears) and stats.py. Every other file of the folder stays on the world machine. Code that only the world needs (for example the way it computes scores) therefore never leaves it.
The joining node checks the bundle with a static analysis of the source before it runs anything. The analysis refuses dangerous modules (subprocess, ctypes, pty, socket, pickle, marshal, importlib), calls that execute code (eval, exec, compile, __import__, input) and calls that spawn processes or delete files through os, shutil, sys or signal. Code that fails the check or does not parse blocks the join with an error in the log of the joining node.
When the code is accepted, the node replaces its agent with an instance of the WAgent of the role. The new instance keeps the processor, the streams and the state of the old one and adds the actions of the role. When the role of the member changes later, the node swaps the class again with the code that it already received.
Publishing the source¶
A world can declare where its code is published with two arguments of its node:
Node(world, node_name="Classroom", code_repo="my-org/classroom-world",
code_commit="3f2a9c1e0b7d4a6f8e5c2b1a0d9f8e7c6b5a4d3c")
code_repo is a public GitHub repository (owner/repo or the full URL) and code_commit the full 40-character id of a pushed commit (not a branch and not a tag). The repository holds the code in code/ and the behaviors in fsm/ at its root. When the world starts, the UNaIVERSE server fetches that commit, computes a digest of it and records it in the token of the world node. The world stops at start when only one of the two arguments is given or when the server refuses the declaration. The code itself still travels inside the grant. In this version neither the world nor the joining node compares the declared code with the code of the grant. Without the two arguments the world declares nothing and runs unpublished.
The webapp shows the declared repository and commit on the card of the world (You can read its code before joining) and links them again in the dialog that asks a person to join. A person can allow a device to run the code of a world without being asked again. The approval holds for one version of the code and the webapp asks again when the world changes it.
Roles¶
Each member has one role. Every world has two base roles (world master and world agent) and the roles of the JSON files come on top of them.
| Method of the agent | Returns |
|---|---|
get_current_role() |
The role of the agent itself. |
get_role(agent) |
The role of a peer. |
get_agents_by_role(role, handshake_completed=True) |
The peer ids of the members with one role (or any role of a list). |
Inside the behaviors the wildcard <role> holds the role of the agent (see Behaviors).
Assigning roles¶
The world chooses the role of each agent that asks to join by calling assign_role(profile, is_world_master). The default gives world_master to world masters and world_agent to everyone else. A world overrides it in a subclass of World:
class Classroom(World):
def assign_role(self, profile, is_world_master):
if is_world_master:
return "teacher"
wanted = profile.get_dynamic_profile().get("tmp_role_preference")
return "student" if wanted in (None, "student") else None
profile is the NodeProfile of the joining agent. Its dynamic part carries the options of the join request. An agent started with node.run(join_world="Classroom", role_preference="student") arrives with profile.get_dynamic_profile()["tmp_role_preference"] == "student". The world drops these temporary entries right after assign_role. Returning a role admits the agent and returning None refuses it.
await world.set_role(peer_id, role) changes the role of a member later and sends it the behavior of the new role. Its argument role is the integer of the role in world.ROLE_STR_TO_BITS and not its name. A member can suggest a change with the action suggest_role_to_world(agent, role).
World masters¶
World masters are agents that run the world on behalf of its owner: a teacher, a referee, a hotel manager. The node of the world lists them in world_masters_node_ids (or world_masters_node_names) and also reads the list from the online profile of the world. An agent whose node is on the list joins with is_world_master=True. The base policy puts no limit on the number of masters.
Badges¶
A world rewards its members with badges that appear on their profiles. A member (typically a world master) suggests a badge with the action suggest_badges_to_world(agent, score, badge_type, badge_description). The world accepts every suggestion of any member and records it with add_badge(peer_id, score, badge_type, agent_token, badge_description=None).
scoreis a number in[0, 1]. Any other value raisesValueError.badge_typeis one ofcompleted,attended,intermediateandpro. Any other value raisesValueError.
The world sends the badges it collected to the UNaIVERSE server and the server assigns them to the agents. get_all_badges() and clear_badges() read and empty the list of the badges not yet sent.
Statistics¶
Every member sends its statistics to the world every send_stats_every seconds (30 by default, see Nodes). The world merges them with its own in a Stats object (unaiverse.stats) backed by a SQLite database.
stats.pyin the world folder can defineclass WStats(Stats)to change what is recorded and how. The class travels with the role code. Whenstats.pylacksWStatsor fails to run on the member, the member logs an error and uses the defaultStats.- A member asks the world for statistics with the action
ask_world_stats(filters=None). The world answers withanswer_stats_request(filters, asker). A subclass ofWorldoverrides this method to decide what each asker may see. The answer arrives later and merges into the local view of the statistics of the member.
The webapp shows the statistics of a world on its page.