Skip to content

11 · Build your first world

The classroom of the previous chapters has three lectures, an exam, a feedback stage, forms for people and statistics. This chapter builds a smaller world from an empty folder with the same machinery: a flashcards world. A tutor owns a deck of labeled pictures. Its learners train their models on the deck while the tutor shows it. The tutor then quizzes them on the same deck and tells each learner its score. The loop starts again whenever learners are present.

The code below uses only calls that the classroom already makes. When something behaves differently from what you expect, compare it with the corresponding file of unaiverse-examples/worlds/collas_tutorial/tutorial_steps/step4.

1. The folder

flashcards/
├── run_world.py
├── run_tutor.py
├── run_learner.py
├── deck/                 # 001_Apple.jpg, 002_Pear.jpg, ... (the class follows the "_")
└── src/
    ├── __init__.py
    ├── world.py
    ├── tutor.py
    ├── learner.py
    └── stats.py

src/__init__.py imports the modules of the folder, as in the classroom:

src/__init__.py
from . import stats
from . import learner, tutor
from . import world

As in chapter 2, src/stats.py holds an empty WStats for now.

2. The roles

src/learner.py
import random
from unaiverse.utils.logger import log
from unaiverse.agent import Agent, action
from unaiverse.interaction import Interaction


class WAgent(Agent):
    """Learner: shows the notices of the tutor; learn and process are built in."""

    @action
    async def print(self, msg: str, interaction: Interaction | None = None):
        if interaction is None:
            return False
        log.user(msg)
        return True

    @staticmethod
    def one_at_random(addresses: list[list[str]], peer_ids: list[str]):
        """Picks one tutor when several exist (used by connect_by_role)."""
        if addresses is None or len(addresses) == 0:
            return addresses, peer_ids
        p = random.randrange(len(peer_ids))
        return [addresses[p]], [peer_ids[p]]
src/tutor.py
import os
from unaiverse.agent import Agent, action
from unaiverse.interaction import Interaction
from unaiverse.streams import Stream, ImageFileStream, StringStream


class WAgent(Agent):
    """Tutor: shows the deck, quizzes the learners and tells them their scores."""

    CARDS = 4                          # cards per lesson and per quiz
    DELTA = 5.0                        # seconds between two cards
    RESPONSE = 2.5 * DELTA             # time allowed for one step
    MAX_DURATION = RESPONSE * CARDS    # lifetime of a lesson or a quiz

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.lesson_over = False
        self.quiz_over = False
        self.learners: set[str] = set()
        self.sent: dict[int, str] = {}                  # tag -> true class
        self.answers: dict[int, dict[str, str]] = {}    # tag -> {learner: answer}
        self.last_sent_at = -1.

    def accept_new_role(self, role: int):
        super().accept_new_role(role)
        folder = os.environ["DECK_PATH"]
        files = sorted(f for f in os.listdir(folder) if f.lower().endswith(".jpg"))
        names = [f.rsplit("_", 1)[1].split(".")[0] for f in files]
        self.add_streams([
            Stream.create(stream=ImageFileStream(folder, files, circular=True),
                          group="deck", name="images", pubsub=False, public=False, delta=self.DELTA),
            Stream.create(stream=StringStream(names, circular=True),
                          group="deck", name="class_names", pubsub=False, public=False, delta=self.DELTA)])
        self.update_streams_in_profile()

The tutor reads its deck from the folder named by the environment variable DECK_PATH on its own machine and turns it into a group of two streams. The pictures go out one every 5 seconds.

3. The actions of the tutor

src/tutor.py (continued)
    @action
    async def reset(self) -> bool:
        self.lesson_over = self.quiz_over = False
        self.learners, self.sent, self.answers = set(), {}, {}
        self.last_sent_at = -1.
        return True

    @action
    async def teach(self) -> bool:
        """Asks every learner to learn from the deck."""
        return await self.send(action_name="learn",
                               target=self.get_agents_by_role("learner"),
                               from_state="in_class",
                               streams={"stdin": ["images@deck"], "stdtar": ["class_names@deck"]},
                               num_steps=self.CARDS, num_samples_to_stream=self.CARDS,
                               timeout=self.MAX_DURATION,
                               callback="lesson_done")

    @action
    async def lesson_done(self, interaction: Interaction | None = None) -> bool:
        if interaction is None or not interaction.is_completed():
            return False
        self.lesson_over = True
        return True

    @action
    async def quiz(self) -> bool:
        """Once the lesson is over, asks every learner to classify the deck."""
        if not self.lesson_over:
            return False
        await self.send(action_name="process",
                        target=self.get_agents_by_role("learner"),
                        from_state="in_class",
                        streams={"stdin": ["images@deck"], "stdext": ["class_names@deck"]},
                        num_steps=self.CARDS, num_samples_to_stream=self.CARDS,
                        timeout=self.MAX_DURATION,
                        callback="quiz_done")
        sent = self.get_last_sent_interaction()
        self.learners = set(sent.target) if sent else set()
        return len(self.learners) > 0

    @action
    async def quiz_done(self, interaction: Interaction | None = None) -> bool:
        if interaction is None or not interaction.is_completed():
            return False
        self.quiz_over = True
        return True

    @action
    async def collect(self) -> bool:
        """Records the true class of each card that leaves and the answers that come back."""
        interaction = self.get_last_sent_interaction()
        if interaction is None:
            return False
        uuid = interaction.uuid
        moved = False

        names = self.get_stream("deck", data_type="text")
        tag = names.get_tag(uuid=uuid) if names is not None else None
        if tag is not None and len(self.sent) < self.CARDS:
            truth = names.get("collect_sent", uuid=uuid)
            if truth is not None:
                self.sent[tag] = truth
                moved = True

        for learner in self.learners:
            stream = self.get_stream("processor", learner, data_type="text")
            if stream is None:
                continue
            answer = stream.get("collect_received", uuid=uuid)
            if answer is not None:
                self.answers.setdefault(stream.get_tag(uuid=uuid), {})[learner] = answer
                moved = True

        if moved:
            self.last_sent_at = self.clock.get_time()
        return moved or (self.clock.get_time() - self.last_sent_at) < self.RESPONSE

    @action
    async def score(self) -> bool:
        """Once the quiz is over, tells every learner its score."""
        if not self.quiz_over:
            return False
        for learner in self.learners:
            right = sum(1 for tag, truth in self.sent.items()
                        if self.answers.get(tag, {}).get(learner, "").strip().lower() == truth.lower())
            await self.send(action_name="print",
                            action_kwargs={"msg": f"🃏 Your quiz score: {right}/{len(self.sent)}"},
                            from_state="in_class", target=learner, volatile=True)
        return True

Each action follows the rules of chapter 5. quiz and score return False until their flag (lesson_over or quiz_over) becomes True. Until then the tutor stays in its current state and tries them again at the next cycle. collect returns True while cards leave or answers arrive and for RESPONSE seconds after the last card or answer. Each of its two readers ("collect_sent" and "collect_received") receives a sample only once.

4. The world and its behaviors

src/world.py
import os
import sys
from unaiverse.world import World
from unaiverse.hsm import HybridStateMachine


class WWorld(World):

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

    def assign_role(self, profile, is_world_master):
        return "tutor" if is_world_master else "learner"

    def create_behav_files(self):
        sys.path.append(self.world_folder)

        from .tutor import WAgent as Tutor
        dummy = Tutor(proc=None)
        b = HybridStateMachine(dummy)
        b.set_role("tutor")
        b.set_welcome_message("🃏 Flashcards: you are the tutor")
        b.add_state("wait", action="reset", blocking=False, msg="Waiting for learners...")
        b.add_state("ready", waiting_time=5.0, blocking=False, msg="A lesson is about to start...")
        b.add_state("teaching", blocking=True, msg="Showing the deck...")
        b.add_state("quizzing", blocking=True, msg="Quiz in progress...")
        b.add_transit("wait", "ready", action="find_agents",
                      args={"role": "learner", "handshake_completed": True})
        b.add_transit("ready", "teaching", action="teach")
        b.add_transit("teaching", "quizzing", action="quiz")
        b.add_transit("quizzing", "quizzing", action="collect")
        b.add_transit("quizzing", "wait", action="score")
        b.save(os.path.join(self.world_folder, "tutor.json"), only_if_changed=dummy)

        from .learner import WAgent as Learner
        dummy = Learner(proc=None)
        b = HybridStateMachine(dummy)
        b.set_role("learner")
        b.set_welcome_message("🃏 Flashcards: you are a learner")
        b.add_state("init", waiting_time=3.0, blocking=False)
        b.add_state("tutor_found", blocking=True, msg="Connected, waiting for the tutor...")
        b.add_state("in_class", blocking=False)
        b.add_state("done", blocking=False)
        b.add_state("wait_to_recover", blocking=False, msg="Lost the tutor, trying again in a minute")
        b.add_transit("init", "tutor_found", action="connect_by_role",
                      args={"role": "tutor", "filter_fcn": "one_at_random"})
        b.add_transit("tutor_found", "in_class", action="connected", args={"handshake_completed": True})
        b.add_transit("tutor_found", "wait_to_recover", action="disconnected", delay=5.0, teleport=True)
        b.add_transit("in_class", "in_class", action="print", args={}, ready=False)
        b.add_transit("in_class", "done", action="learn", args={}, timeout=Tutor.RESPONSE, ready=False)
        b.add_transit("in_class", "done", action="process", args={}, timeout=Tutor.RESPONSE, ready=False)
        b.add_transit("in_class", "wait_to_recover", action="disconnected", teleport=True)
        b.add_transit("done", "in_class", action="nop", args={})
        b.add_transit("wait_to_recover", "init", action="nop", delay=60, teleport=True)
        b.save(os.path.join(self.world_folder, "learner.json"), only_if_changed=dummy)
stateDiagram-v2
    direction LR
    [*] --> wait
    wait --> ready: find_agents(role=learner)
    ready --> teaching: teach
    teaching --> quizzing: quiz
    quizzing --> quizzing: collect
    quizzing --> wait: score

Every transition of the tutor runs on its own initiative. In in_class the learner waits for requests and its print, learn and process transitions run only when the tutor asks for them. A state may have two transitions to the same destination as long as their actions differ. Both learn and process therefore lead to done.

The actions of the tutor send their requests with from_state="in_class" because the learners serve requests in that state.

5. The run scripts

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

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

if __name__ == "__main__":
    os.environ["DECK_PATH"] = os.path.join(os.path.dirname(os.path.abspath(__file__)), "deck")
    Node(node_name="FlashcardsTutor", hosted=Agent(proc=None), hidden=True,
         clock_delta=1. / 10.).run(join_world="Flashcards")

For run_learner.py, use the student of Your agent joins a world with join_world="Flashcards". Its output stream turns class names into indices for learn and predictions into class names for process.

Start the world, then the tutor, then one or more learners, each in its own terminal. The tutor waits for a learner, shows the deck, quizzes the class and sends each learner its score. The scores grow over the rounds as the learners train on the deck.

6. Make it yours

The flashcards world is a starting point. A few changes take it closer to the classroom:

  • Several decks. Create one stream group per deck in accept_new_role and teach them in turn as give_next_lecture does.
  • People as learners. Rewrite the class names of the quiz into a form in hook_before_sending_sample and read the reply blocks in collect (chapter 7).
  • Statistics. Declare a stat in WStats and store one record per learner in score (chapter 10).
  • Badges. Suggest a badge to the world from score with suggest_badges_to_world when a learner answers every card correctly (chapter 9).

Where next

Chapter 12 collects the mistakes that are easy to make when building a world and a checklist to run before publishing one.

12 · Patterns, pitfalls and checklist