Skip to content

2 · Anatomy of a world

The first version of the classroom (tutorial_steps/step1) does almost nothing. Agents join, receive the role of teacher or student, print a welcome message and stay idle. It is nevertheless a complete world: roles, the join handshake and the shipping of code from the world to its members all work with about forty lines of world code. Every later stage of the classroom grows from this skeleton.

The folder

collas_tutorial/
├── run_world.py          # starts the world node
├── run_teacher.py        # starts the teacher (the world master)
├── run_student1.py       # starts an AI student
├── run_student2.py
├── data/                 # lecture, exam and feedback pictures (used from chapter 3 on)
└── src/                  # the world folder
    ├── __init__.py
    ├── world.py          # the World subclass: roles and behaviors
    ├── teacher.json      # behavior of the role "teacher"
    ├── teacher.py        # class WAgent of the role "teacher"
    ├── student.json      # behavior of the role "student"
    ├── student.py        # class WAgent of the role "student"
    ├── stats.py          # class WStats (empty for now)
    └── pdf/              # drawings of the behaviors, generated

src/ is the world folder, the directory that the world receives as world_folder. Its JSON files decide the roles: teacher.json and student.json mean that the world has the roles teacher and student, in alphabetical order of the file names. For each role the world expects a Python file with the same name and a class WAgent in it. When a role file is missing and the folder contains a single agent.py, every role uses agent.py. When neither exists, the world refuses to start with the error Mismatching JSON-file roles and .py files.

The world reads every Python file in the folder except the subfolders pdf and stats. It then ships to the members only the role files, the files they import with relative imports and stats.py. No role file imports world.py. It therefore stays private like any other helper that only the world uses.

The World subclass

src/world.py
import os
import sys
from unaiverse.world import World
from unaiverse.hsm import HybridStateMachine
from unaiverse.networking.node.profile import NodeProfile


class WWorld(World):

    def __init__(self, **kwargs):
        world_folder = os.path.dirname(os.path.abspath(__file__))
        super().__init__(world_folder=world_folder, **kwargs)

    def assign_role(self, profile: NodeProfile, is_world_master: bool):
        """The criterion the world uses to assign a role to every joining agent."""
        return "teacher" if is_world_master else "student"

    def create_behav_files(self):
        """Creates the role-behavior JSON files: a welcome message and one idle state each."""
        sys.path.append(self.world_folder)

        from .teacher import WAgent as WAgentTeacher
        dummy_agent = WAgentTeacher(proc=None)
        behav = HybridStateMachine(dummy_agent)
        behav.set_role("teacher")
        behav.set_welcome_message("🎓 Welcome to our tutorial at CoLLAs 2026! Your role: teacher")
        behav.add_state("init", blocking=True)
        behav.save(os.path.join(self.world_folder, 'teacher.json'), only_if_changed=dummy_agent)

        from .student import WAgent as WAgentStudent
        dummy_agent = WAgentStudent(proc=None)
        behav = HybridStateMachine(dummy_agent)
        behav.set_role("student")
        behav.set_welcome_message("🎓 Welcome to our tutorial at CoLLAs 2026! Your role: student")
        behav.add_state("init", blocking=True)
        behav.save(os.path.join(self.world_folder, 'student.json'), only_if_changed=dummy_agent)

A world subclass usually overrides two methods:

  • assign_role(profile, is_world_master) runs on the world node for every join request. Here the rule is the simplest possible: the world master becomes the teacher and everybody else a student. Chapter 3 shows richer rules.
  • create_behav_files() runs when the world starts and before the world reads its folder. The classroom uses it to write the JSON files of the behaviors from Python. Writing the JSON files by hand is equally valid. In that case the method is not needed and the base class does nothing.

A behavior refers to the actions of a class and the state machine checks that those actions exist. Building a behavior from Python therefore requires an agent object. For this purpose the world creates a dummy agent of each role with proc=None only to build its behavior. save(..., only_if_changed=dummy_agent) writes the file only when its content differs from the one on disk.

When the world starts, it loads every behavior against a dummy agent of its role. Every member runs the same check when it joins. A behavior that refers to an action missing from the class fails at this point and no agent can connect to a world with a broken behavior. The world then rewrites each JSON file in a normalized form. For every file that changed it also draws the state machine in pdf/<role>.pdf. Drawing requires the Graphviz program on the machine of the world. Without it the world logs an error and goes on without the drawings.

The role classes

src/teacher.py
from unaiverse.agent import Agent


class WAgent(Agent):
    """Teacher agent (empty for now: streams and actions come in the next chapters)."""
src/student.py
from unaiverse.agent import Agent


class WAgent(Agent):
    """Student agent (empty for now: actions come in the next chapters)."""

A role class subclasses Agent and is always named WAgent. A member that joins the world becomes an instance of the class of its role. Its own processor, input and output streams and options are carried over to the new instance. The methods of WAgent that are marked as actions become the actions that the behavior of the role can call. Since these files travel to the members, they import only what a member has: the SDK, the standard library and the packages that every member of that role is expected to install.

The behaviors as JSON

The world writes student.json from the code above:

src/student.json
{
    "machine": {
        "role": "student",
        "initial_state": "init",
        "msg": "&#127891; Welcome to our tutorial at CoLLAs 2026! Your role: student",
        "options": {
            "highlight_blocking_states_in_messages": false,
            "show_action_ticks_after_messages": false,
            "show_action_request_after_messages": false
        }
    },
    "states": {
        "init": {
            "action": null,
            "action_kwargs": {},
            "msg": null,
            "blocking": true,
            "time_to_wait_before_acting": 0.0
        }
    },
    "transitions": {},
    "teleports": {}
}

machine.msg is the welcome message that a member sees when it joins. With one state and no transitions, a member enters init and stays there. Chapter 4 fills states and transitions.

Stats

src/stats.py
from unaiverse.stats import Stats


class WStats(Stats):
    """Custom stats for the world (empty for now: chapter 10 fills it)."""

Members record statistics too and send them to the world in batches. For this reason stats.py always travels to the members. Since the joining node executes it as a standalone module outside any package, stats.py cannot use relative imports and must stay self-contained.

The run scripts

run_world.py
from src.world import WWorld
from unaiverse.networking.node.node import Node

if __name__ == "__main__":
    world = WWorld()
    node = Node(node_name="CoLLAsTutorial", hosted=world, hidden=True, clock_delta=1. / 10.,
                world_masters_node_names=["CoLLAsTeacher"])
    node.run()
run_teacher.py
import os
from unaiverse.agent import Agent
from unaiverse.networking.node.node import Node

if __name__ == "__main__":
    os.environ["TEACHER_DATA_PATH"] = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data")
    agent = Agent(proc=None)
    node = Node(node_name="CoLLAsTeacher", hosted=agent, hidden=True, clock_delta=1. / 10.)
    node.run(join_world="CoLLAsTutorial")

The teacher has proc=None because it runs no model. Its job is to stream data and coordinate the class. The data stay on the machine of the teacher and never travel with the code of the world. TEACHER_DATA_PATH tells the teacher where to find them. A student runs a model and joins the world in the same way (see run_student1.py and Your agent joins a world).

The scripts in tutorial_steps/ also turn on three debug switches for tests on a single machine (Custom.SKIP_WAS_ALIVE_CHECK, Custom.ENV_IS_ISOLATED, Custom.ENV_IS_PUBLIC, the code equivalents of NODE_IGNORE_ALIVE, NODE_IS_ISOLATED and NODE_IS_PUBLIC). The final scripts in the parent folder run without them. Configuration describes each switch.

Run it

Start the world, then the teacher, then the students, each in its own terminal and each after the previous node is up. Every agent joins, receives its role and prints its welcome message. Both behaviors consist of a single idle state and nothing else happens yet.

Restart after editing the world folder

The world packs its code when it starts. After editing anything in src/, restart run_world.py and then the members. Each member receives the new code with its next grant.

What just happened

The world read its folder and found two roles. It built their behaviors, checked them against dummy agents and wrote them to disk. When the teacher asked to join, assign_role saw a world master and answered teacher. The teacher received a grant with the two behaviors and a bundle with teacher.py, student.py and stats.py, checked the bundle, joined the world network and became an instance of the teacher WAgent. The students went through the same steps and became students.

Where next

Chapter 3 looks closer at roles: how a world decides them, who is a world master and what an agent does when it receives its role.

3 · Roles and the world master