Skip to content

Quiz

A quiz night is a small world with two roles. The host is the world master. It waits for players, asks three multiple-choice questions one at a time and gives every player a badge with the share of right answers. A player can be a person in the webapp, a person at a terminal or a language model. The questions travel as interactive messages. A person sees them as buttons and a model reads them as a plain instruction. The host, on the other hand, reads every answer in the same way.

The sources are in examples-src/quiz/:

quiz/
├── run_world.py        the world node
├── run_host.py         the host (world master)
├── run_player.py       a player with a language model
└── src/
    ├── world.py        roles and behaviors, kept by the world
    ├── host.py         actions of the host, shipped to the members
    ├── player.py       actions of a player, shipped to the members
    └── questions.py    the questions, shipped because host.py imports it

The world

src/world.py
"""The quiz world: one host (the world master) asks the questions, every other member plays."""
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):
        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:
        assert self.world_folder is not None
        sys.path.append(self.world_folder)

        # Host: wait for players, then ask the questions one by one and award the badges at the end
        from .host import WAgent as Host
        dummy = Host(proc=None)
        behav = HybridStateMachine(dummy)
        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_state("asking", blocking=False)
        behav.add_state("waiting", blocking=False, msg="Waiting for the answers...")
        behav.add_state("finished", blocking=False, msg="Quiz over.")
        behav.add_transit("lobby", "asking", action="find_agents",
                          args={"role": "player", "handshake_completed": True})
        behav.add_transit("asking", "waiting", action="ask_next_question")
        behav.add_transit("waiting", "asking", action="close_question")
        behav.add_transit("asking", "finished", action="award_badges")
        behav.add_transit("finished", "lobby", action="nop", delay=30.0)
        behav.save(os.path.join(self.world_folder, "host.json"), only_if_changed=dummy)

        # Player: find the host, then answer every question it asks
        from .player import WAgent as Player
        dummy = Player(proc=None)
        behav = HybridStateMachine(dummy)
        behav.set_role("player")
        behav.set_welcome_message("Welcome to the quiz! The host will ask three questions.")
        behav.add_state("init", waiting_time=2.0, blocking=False)
        behav.add_state("host_found", blocking=True, msg="Connecting to the host...")
        behav.add_state("playing", blocking=False)
        behav.add_state("answered", blocking=False)
        behav.add_state("lost", blocking=False, msg="Lost the host, trying again in a minute.")
        behav.add_transit("init", "host_found", action="connect_by_role", args={"role": "host"})
        behav.add_transit("host_found", "playing", action="connected", args={"handshake_completed": True})
        behav.add_transit("host_found", "lost", action="disconnected", delay=5.0, teleport=True)
        behav.add_transit("playing", "answered", action="process", ready=False, timeout=60.0)
        behav.add_transit("answered", "playing", action="nop")
        behav.add_transit("playing", "lost", action="disconnected", teleport=True)
        behav.add_transit("lost", "init", action="nop", delay=60.0, teleport=True)
        behav.save(os.path.join(self.world_folder, "player.json"), only_if_changed=dummy)

Among the agents that ask to join, assign_role makes the world master the host and every other agent a player. Returning None instead would reject the agent. create_behav_files runs when the world starts and writes one behavior file per role (host.json and player.json) next to the code. A behavior looks up the actions it names among the methods of an agent of its role. For this reason the world builds each behavior around a throwaway instance of the role class.

The two behaviors, drawn from the calls above:

stateDiagram-v2
    [*] --> lobby
    lobby --> asking: find_agents(role=player)
    asking --> waiting: ask_next_question
    waiting --> asking: close_question
    asking --> finished: award_badges
    finished --> lobby: nop (after 30 s)
stateDiagram-v2
    [*] --> init
    init --> host_found: connect_by_role(role=host)
    host_found --> playing: connected
    playing --> answered: process (requested by the host)
    answered --> playing: nop
    host_found --> lost: disconnected
    playing --> lost: disconnected
    lost --> init: nop (after 60 s)

A transition fires when its action returns True. Because ask_next_question returns False after the last question and award_badges returns False before it, exactly one of the two can fire in state asking. The process transition of the player has ready=False and fires only when the host sends a process request. Its timeout=60.0 is how long the player keeps trying that transition before giving up.

The host

src/host.py
"""The host asks each question to every player as an interactive form and keeps the scores."""
from unaiverse.agent import Agent, action
from unaiverse.uai import build_form, serialize_block, interpret_reply
from .questions import QUESTIONS


class WAgent(Agent):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.next_question = 0
        self.forms = {}    # peer ID -> the form spec sent for the current question
        self.answers = {}  # peer ID -> the text that came back
        self.scores = {}   # peer ID -> number of right answers

    @action
    async def ask_next_question(self) -> bool:
        """Sends the next question to every player, one form per player."""
        if self.next_question >= len(QUESTIONS):
            return False
        q = QUESTIONS[self.next_question]
        self.forms, self.answers = {}, {}
        for player in self.get_agents_by_role("player"):

            # One form id per recipient, otherwise one answer would mark every copy as answered
            spec = build_form(f"Question {self.next_question + 1}",
                              [{"name": "answer", "type": "select", "label": q["text"], "required": True,
                                "options": [{"value": o, "label": o} for o in q["options"]], "ui": "buttons"}],
                              lang="en", progress=(self.next_question + 1, len(QUESTIONS)))
            if await self.send(action_name="process", target=player, timeout=60.0,
                               data_samples={"proc_output_0": serialize_block(spec)}):
                self.forms[player] = spec
        self.next_question += 1
        return len(self.forms) > 0

    @action
    async def close_question(self) -> bool:
        """Collects the answers and closes the question when every player answered or gave up."""
        await self.on_received("store_answer", data_type="text")
        if not (len(self.answers) == len(self.forms) or await self.all_sent_completed("process")):
            return False
        q = QUESTIONS[self.next_question - 1]
        for player, text in self.answers.items():
            event = interpret_reply(text, pending=[self.forms[player]])
            if event.values.get("answer") == q["answer"]:
                self.scores[player] = self.scores.get(player, 0) + 1
        return True

    def store_answer(self, peer_id, props, data, tag) -> None:
        if peer_id in self.forms:
            self.answers[peer_id] = data

    @action
    async def award_badges(self) -> bool:
        """Only after the last question: every player gets a badge with the share of right answers."""
        if self.next_question < len(QUESTIONS):
            return False
        for player in self.get_agents_by_role("player"):
            await self.suggest_badges_to_world(agent=player, score=self.scores.get(player, 0) / len(QUESTIONS),
                                               badge_type="completed",
                                               badge_description="Quiz night")
        self.next_question, self.scores = 0, {}
        return True

ask_next_question builds one form per player with build_form. A single required select field holds the options, "ui": "buttons" asks the webapp to draw them as buttons and progress shows "1 of 3". A shared id would let one answer mark every copy as answered. Every player therefore gets a form with its own id. serialize_block turns the spec into the fenced ```uai block and send delivers it as the input of a process request.

close_question runs in state waiting at every tick until it returns True. It collects the answers that arrived with on_received, then waits until every player answered or every request completed (all_sent_completed("process") also counts the requests that timed out as completed). interpret_reply reads each answer against its form and accepts any of the shapes that a player can produce:

What the player wrote How it is read (event.via) event.values
a reply block from the buttons of the webapp block {"answer": "Mercury"}
Mercury bare {"answer": "Mercury"}
answer: Venus labeled {"answer": "Venus"}
I think it is Mars freetext {}

award_badges asks the world to give each player a badge of type completed with a score in [0, 1]. The world node collects these suggestions and sends the badges to the UNaIVERSE servers. The servers attach them to the node of the player. The other badge types are attended, intermediate and pro.

Who answers

  • A person in the webapp joins QuizNight from unaiverse.io and answers with the buttons. The webapp sends a reply block bound to the id of the form.
  • A person at a terminal runs an agent whose processor is a HumanModule with interact_mode=True (People). The terminal shows the text alternative of the form and the person types the answer. When the answer cannot be read against the form, the terminal says what is wrong and waits for a new line.
  • A language model answers through its processor. When the answer of the model does not fit the form, the agent runs up to two corrective rounds (Language model).

The code that reaches the members

When the world starts, it packs the code that the roles need and ships this bundle to every agent that it admits. The bundle holds the role files and everything that they import from the world folder (here host.py, player.py and questions.py). world.py stays on the world node because no role file imports it. Before running the bundle, the joining agent checks it with a deny-list of dangerous modules and calls (subprocess, socket, pickle and others) and refuses a world whose code does not pass (Worlds).

Run it

python run_world.py     # terminal 1
python run_host.py      # terminal 2
python run_player.py    # terminal 3 (start as many players as you like)

Then join QuizNight from the webapp as a person. The world recognizes the host by its node name through world_masters_node_names. Change QuizHost in run_world.py and run_host.py together if you rename it.

Checked on the network

The three scripts ran on the network with one TinyLlama player. The host asked the three questions, the answers came back and the host suggested the badge to the world. While the model warms up on a CPU, the first answer of TinyLlama can take longer than the 60 seconds of timeout in ask_next_question. The host then closes that question without an answer. Raise the timeout for slow players.