Skip to content

unaiverse.world

This module holds World, the class of a world. A world is a community of agents with rules: it decides who may enter and gives each member a role. Together with the role it sends the behavior of that role and the Python code of its actions. It also collects the statistics of its members and assigns badges. Technically a world is an agent (a subclass of AgentBasics) without processor and without behavior of its own, hosted by a Node like any 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()

A world with its own rules is a subclass of World that overrides assign_role, create_behav_files or answer_stats_request. The node calls every other public method of this class when it receives messages from the members. A world program rarely calls them itself.

The world folder

The folder passed as world_folder defines the roles and their code.

classroom/
├── teacher.json      # behavior of the role "teacher"
├── teacher.py        # class WAgent(Agent) with the actions of the teacher
├── student.json
├── student.py
├── grading.py        # optional, imported by the role files with "from .grading import ..."
├── stats.py          # optional, class WStats(Stats)
├── pdf/              # written by the world: one drawing per role
└── stats/            # written by the world: world_stats.db

When the World object is created, the constructor of AgentBasics prepares the folder in five steps.

  1. It calls the hook create_behav_files(). The base hook does nothing and a subclass overrides it to write the JSON files in code.
  2. It lists in alphabetical order the files of the folder whose extension is .json (case-insensitive). The names without extension become CUSTOM_ROLES and their order becomes the order of the roles. A folder without JSON files raises GenException. More than 30 roles raise GenException.
  3. It reads every .py file of the folder and of its subfolders other than pdf/ and stats/. Each role needs a file <role>.py that defines a class WAgent. When a role has no <role>.py and the folder holds an agent.py, the content of agent.py becomes the code of every role and the existing <role>.py files are ignored. A folder with neither raises GenException.
  4. For each role it creates a test instance of WAgent with proc=None and loads the JSON file into a HybridStateMachine of that instance. An action named in the behavior and missing from WAgent stops the world with GenException. A WAgent that declares a non-empty CUSTOM_ROLES different from the roles of the folder stops it too. The normalized behavior is stored as a JSON string in role_to_behav[role].
  5. It saves each behavior back to <role>.json and draws it in pdf/<role>.pdf when the content changed or when a JSON file of the folder changed since the previous run. Drawing needs the Graphviz program.

The roles then combine with the two base roles into the role names of the world (see Roles).

The code shipped to members

A member does not install the code of the world. When the world admits an agent, the grant it sends holds a bundle with two fields: agent_files (the packed Python sources) and roles_fsm (the dictionary role_to_behav). agent_files holds the role files, every file that they reach through relative imports (from .grading import score, followed until nothing new appears) and stats.py. Absolute imports are not followed. Every other file of the folder stays on the world machine. Code that only the world needs (for example the code that computes the grades) therefore never leaves the world machine. The packed sources are in packed_agent_files.

The joining node checks the sources with a static analysis before running them and then replaces its agent with an instance of the WAgent of its role. stats.py runs on the member in a bare module where relative imports do not resolve. The member uses the class WStats of that file. When the class is missing or the file raises an exception, the member logs an error and uses the default Stats. The checks and the swap of the agent are described in Worlds.

Roles

A role is stored as an integer used as a bit mask. The two lowest bits are the base role: 0 is public_agent, 1 is world_agent and 3 is world_master. Each role of the folder takes one higher bit in the order of CUSTOM_ROLES: the first one is 4, the second 8 and so on. A member has a base role and at most one custom role. Its full name joins the two with ~: world_agent~student is 1 | 8 = 9 and world_master~teacher is 3 | 4 = 7. The dictionaries ROLE_BITS_TO_STR and ROLE_STR_TO_BITS of the world map the integers to the names and back.

Event What decides the role
An agent asks to join assign_role(profile, is_world_master) returns the name of the custom role (or of a base role). The node adds the base bits of a world master or of a world agent. None refuses the agent.
A world master suggests a change The member runs the action suggest_role_to_world(agent, role). The world accepts suggestions from world masters alone and applies each one with set_role(peer_id, role).
The world changes a role itself The world program awaits set_role(peer_id, role).

An agent is a world master when its node id (or node name) is in the list world_masters_node_ids (world_masters_node_names) of the node of the world or in the online profile of the world. The base policy places no limit on the number of masters.

World

World(world_folder: str, merge_flat_stream_labels: bool = False, stats: Stats | None = None)

Bases: AgentBasics

Source code in unaiverse/world.py
def __init__(self, world_folder: str, merge_flat_stream_labels: bool = False,
             stats: Stats | None = None) -> None:
    """Initializes a World object as a special agent with no processor or behavior.

    Args:
        world_folder: Path to the world folder containing per-role behavior JSON files
            and ``agent.py``.
        merge_flat_stream_labels: If True, flat stream labels are merged (default: False).
        stats: An optional Stats instance for recording world metrics.  If None, a default
            Stats instance is created inside the world folder (default: None).
    """

    # Creating a "special" agent with no processor and no behavior, but with a "world_folder", which is our world
    super().__init__(proc=None, proc_inputs=None, proc_outputs=None, proc_opts=None,
                     world_folder=world_folder, merge_flat_stream_labels=merge_flat_stream_labels)

    # Clearing processor (world must have no processor, and, maybe, a dummy processor was allocated when building
    # the agent in the init call above)
    self.proc = None
    self.proc_inputs = []  # Do not set it to None, keep an empty list
    self.proc_outputs = []  # Do not set it to None, keep an empty list
    self.proc_opts = {}  # Do not set it to None, keep an empty dict
    self.proc_optional_inputs = []  # See above :)
    self.compat_in_streams: list[set] | None = None
    self.compat_out_streams: list[set] | None = None

    # Map from public peer IDs to private peer IDs
    self.private_peer_of = {}

    # Stats
    self.stats: Stats
    if stats is not None:
        self.stats = stats
    else:
        # fallback to default Stats class
        self.stats = Stats(is_world=True, db_path=f"{self.world_folder}/stats/world_stats.db",
                           cache_window_hours=2.0)
    assert self.stats is not None

The world. Creating it reads and normalizes the world folder as described above and opens the statistics database.

Argument Type Default Meaning
world_folder str required The path of the world folder.
merge_flat_stream_labels bool False The option of AgentBasics that merges the labels of flat streams across the streams owned by the world.
stats Stats \| None None The object that records the statistics. None creates Stats(is_world=True, db_path=f"{world_folder}/stats/world_stats.db", cache_window_hours=2.0). A world with a custom WStats passes an instance of it here.

Errors of the world folder raise GenException (see The world folder).

Attribute Type Meaning
world_folder str The world folder.
stats Stats The statistics of the world (see unaiverse.stats).
CUSTOM_ROLES list[str] The roles of the folder in alphabetical order.
ROLE_BITS_TO_STR, ROLE_STR_TO_BITS dict The role names by integer and the integers by name for the base, custom and combined roles.
role_to_behav dict[str, str] The normalized behavior of each role as a JSON string.
packed_agent_files str The packed Python sources shipped to the members.
all_agents dict[str, NodeProfile] The profiles of the connected members by private peer id.
world_masters, world_agents dict[str, NodeProfile] The members by base role.
human_agents, artificial_agents dict[str, NodeProfile] The members by kind.
private_peer_of dict[str, str] The private peer id of each member by its public peer id.
agent_badges dict[str, list[dict]] The badges not yet sent to the server grouped by peer id.
BADGE_TYPES set[str] {'completed', 'attended', 'intermediate', 'pro'}.
proc, proc_inputs, proc_outputs, proc_opts Always None, [], [] and {}: a world has no processor.

create_behav_files

create_behav_files() -> None
Source code in unaiverse/agent_basics.py
def create_behav_files(self) -> None:
    """This method is called when building a world object. In your custom world-class, you can overload this method
    and create the JSON files with the role-related behaviors, if you like. Recall that acting like this is not
    mandatory at all: you can just manually create the JSON  files, and this method will simply do nothing."""
    pass

A hook that the world calls at creation before reading the folder (step 1 of The world folder). The base method does nothing and returns None. A subclass overrides it to build the behaviors of its roles in code and write them as <role>.json. The method is defined in AgentBasics and World inherits it.

import os
from unaiverse.world import World
from unaiverse.hsm import HybridStateMachine

class Classroom(World):

    def create_behav_files(self):
        from .teacher import WAgent as Teacher
        teacher = Teacher(proc=None)
        behav = HybridStateMachine(teacher)
        behav.add_transit("init", "engaged", action="find_agents", args={"role": "student", "engage": True})
        behav.add_transit("engaged", "init", action="disengage_all", timeout=30.)
        behav.add_wildcards({"<exam_steps>": 30})
        behav.set_role("teacher")
        behav.save(os.path.join(self.world_folder, "teacher.json"), only_if_changed=teacher)

With only_if_changed the file stays untouched when its content did not change and the drawings in pdf/ are not rebuilt at every start.

assign_role

assign_role(profile: NodeProfile, is_world_master: bool) -> str | None
Source code in unaiverse/world.py
def assign_role(self, profile: NodeProfile, is_world_master: bool) -> str | None:
    """Assigns an initial role to a newly connected agent.

    In this basic implementation, the role is determined solely by whether the agent is a world master or a regular
    world agent. Who may be a master is governed upstream by the world_masters_node_ids allow-list (see node.py),
    not by a single-master cap here: this base policy places no limit on the number of masters.

    Args:
        profile: The NodeProfile of the new agent.
        is_world_master: A boolean indicating if the new agent is attempting to be a master.

    Returns:
        A string representing the assigned role or None if assignment was not possible.
    """
    assert self.is_world, "Assigning a role is expected to be done by the world"

    if ('guessed_location' in profile.get_dynamic_profile() and
            profile.get_dynamic_profile()['guessed_location'] == 'Some Dummy Location, Just An Example Here'):
        pass

    # Currently, roles are only world masters and world agents: this is expected to be overridden when creating a
    # world
    if is_world_master:
        return AgentBasics.ROLE_BITS_TO_STR[AgentBasics.ROLE_WORLD_MASTER]
    else:
        return AgentBasics.ROLE_BITS_TO_STR[AgentBasics.ROLE_WORLD_AGENT]

Chooses the role of an agent that asks to join and returns its name as a string. The node calls it during the admission of each agent. The base method returns "world_master" when is_world_master is True and "world_agent" otherwise. A subclass returns one of CUSTOM_ROLES to give a custom role or None to refuse the agent.

Argument Type Meaning
profile NodeProfile The profile of the joining agent. Its dynamic part holds the options of the join request as temporary keys tmp_<option>: an agent started with node.run(join_world="Classroom", role_preference="student") arrives with profile.get_dynamic_profile()["tmp_role_preference"] == "student". The node removes these keys after the call.
is_world_master bool Whether the node of the agent is on the list of world masters.
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

A returned name missing from ROLE_STR_TO_BITS raises KeyError in the node. The node then adds the base bits of a world master or of a world agent to the custom bits of the returned role.

set_role async

set_role(peer_id: str, role: int) -> None
Source code in unaiverse/world.py
async def set_role(self, peer_id: str, role: int) -> None:
    """Sets a new role for a specific agent and broadcasts this change to the agent (async).

    It computes the new role and sends a message containing the new role and the corresponding default behavior
    for that role.

    Args:
        peer_id: The ID of the agent whose role is to be set.
        role: The new role to be assigned (as an integer).
    """
    assert self.is_world, "Setting the role is expected to be done by the world, which will broadcast such info"

    # Computing new role (keeping the first two bits as before)
    cur_role = self.node_conn.get_role(peer_id)
    new_role_without_base_int = (role >> 2) << 2
    new_role = (cur_role & 3) | new_role_without_base_int

    if new_role != cur_role:
        self.node_conn.set_role(peer_id, new_role)
        log.misc("Telling an agent that his role changed")
        if not (await self.node_conn.send(peer_id, channel_trail=None,
                                          content={'peer_id': peer_id, 'role': new_role,
                                                   'default_behav':
                                                       self.role_to_behav[
                                                           self.ROLE_BITS_TO_STR[new_role_without_base_int]]},
                                          content_type=Msg.ROLE_SUGGESTION)):
            if self.node_conn.sends_are_queued:

                # A full send queue refused it: the agent is behind, not gone (the Session tells that)
                log.error(f"Role change to {peer_id} refused (send queue full), the agent keeps its old role")
            else:
                log.error("Failed to send role change, removing (disconnecting) " + peer_id)

                # Send-failure teardown via the purge: GOAWAY(LOCAL_ERROR) if the Session
                # is still closable; if the link is already down the Session ends through
                # its own grace/timeout machinery and the purge only evicts bookkeeping.
                await self.node_purge_fcn(peer_id, reason=LOCAL_ERROR)
        else:
            self.role_changed_by_world = True

Changes the custom role of the member peer_id and sends it the behavior of the new role. Asynchronous. role is a role bit mask whose two lowest bits are ignored: the member keeps its base role and takes the custom bits of role. Nothing happens when the resulting role equals the current one.

When the role changes, the world records it, marks role_changed_by_world and sends the member a message with the new role and role_to_behav of the new custom role. The member then swaps its agent for the WAgent of the new role. A send refused by a full queue is logged and the member keeps its old role on its side. Any other send failure removes the member from the world. Because role_to_behav has no entry for a base role, a role without custom bits raises KeyError when the member had a custom role.

await world.set_role(peer_id, world.ROLE_STR_TO_BITS["teacher"])

add_badge

add_badge(peer_id: str, score: float, badge_type: str, agent_token: str, badge_description: str | None = None) -> None
Source code in unaiverse/world.py
def add_badge(self, peer_id: str, score: float, badge_type: str, agent_token: str,
              badge_description: str | None = None) -> None:
    """Requests a badge for a specific agent, which can be used to track and reward agent performance.
    It validates the score and badge type and stores the badge information in an internal dictionary.

    Args:
        peer_id: The ID of the agent for whom the badge is requested.
        score: The score associated with the badge (must be in [0, 1]).
        badge_type: The type of badge to be awarded.
        agent_token: The token of the agent receiving the badge.
        badge_description: An optional text description for the badge.

    Raises:
        ValueError: If ``score`` is not in [0.0, 1.0] or ``badge_type`` is not a recognized type.
    """

    # Validate score
    if score < 0. or score > 1.:
        raise ValueError(f"Score must be in [0.0, 1.0], got {score}")

    # Validate badge_type
    if badge_type not in AgentBasics.BADGE_TYPES:
        raise ValueError(f"Invalid badge_type '{badge_type}'. Must be one of {AgentBasics.BADGE_TYPES}.")

    if badge_description is None:
        badge_description = ""

    # The world not necessarily knows the token of the agents, since they usually do not send messages to the world
    badge = {
        'agent_node_id': self.all_agents[peer_id].get_static_profile()['node_id'],
        'agent_token': agent_token,
        'badge_type': badge_type,
        'score': score,
        'badge_description': badge_description,
        'last_edit_utc': clock.get_time_as_string(),
    }

    if peer_id not in self.agent_badges:
        self.agent_badges[peer_id] = [badge]
    else:
        self.agent_badges[peer_id].append(badge)

    # This will force the sending of the dynamic profile at the defined time instants
    self.node_profile.mark_change_in_connections()

Records a badge for the member peer_id in agent_badges and returns None. The node calls it for every badge that a member suggests with the action suggest_badges_to_world. In the current version the node accepts the badges suggested by any member.

Argument Type Default Meaning
peer_id str required The private peer id of the member. A peer id missing from all_agents raises KeyError.
score float required A value in [0, 1]. Any other value raises ValueError.
badge_type str required One of completed, attended, intermediate and pro. Any other value raises ValueError.
agent_token str required The token of the member that the server needs to assign the badge.
badge_description str \| None None A free text. None becomes "".

The stored badge is a dictionary with the keys agent_node_id, agent_token, badge_type, score, badge_description and last_edit_utc (the ISO time of the clock). The node sends the collected badges to the UNaIVERSE server, tells each rewarded member to download its updated profile and then empties the list with clear_badges().

get_all_badges

get_all_badges() -> dict[str, list[dict[str, Any]]]
Source code in unaiverse/world.py
def get_all_badges(self) -> dict[str, list[dict[str, Any]]]:
    """Retrieves all badges that have been added to the world's record for all agents.
    This provides a central log of achievements or performance metrics.

    Returns:
        A dictionary where keys are agent peer IDs and values are lists of badge dictionaries.
    """
    return self.agent_badges

Returns agent_badges, the dictionary from peer id to the list of badges not yet sent. The dictionary is not a copy.

clear_badges

clear_badges() -> None
Source code in unaiverse/world.py
def clear_badges(self) -> None:
    """Clears all badge records from the world's memory.
    This can be used to reset competition results or clean up state after a specific event.
    """
    self.agent_badges = {}

Empties the list of badges not yet sent. The node calls it after a successful round with the server. Returns None.

add_agent async

add_agent(peer_id: str, profile: NodeProfile, add_proc_streams: bool = True, add_env_streams: bool = True, add_pubsub_streams: bool = True) -> bool
Source code in unaiverse/world.py
async def add_agent(self, peer_id: str, profile: NodeProfile,
                    add_proc_streams: bool = True,
                    add_env_streams: bool = True,
                    add_pubsub_streams: bool = True) -> bool:
    """Registers a new agent in the world and records the public-to-private peer ID mapping (async).

    Args:
        peer_id: The unique identifier of the peer.
        profile: The NodeProfile object containing the peer's/agent's information.
        add_proc_streams: True if the processor's streams of the peer must be added to the list of known streams,
            if compatible (ignored in worlds).
        add_env_streams: True if the environmental streams of the peer must be added to the list of known streams,
            if compatible (ignored in worlds).
        add_pubsub_streams: True if pubsub streams must be added/subscribed (ignored in worlds).

    Returns:
        True if the agent was successfully added by the parent class, False otherwise.
    """
    if await super().add_agent(peer_id, profile):
        public_peer_id = profile.get_dynamic_profile()["peer_id"]
        self.private_peer_of[public_peer_id] = peer_id
        return True
    else:
        return False

Adds a member through AgentBasics.add_agent() and records the mapping from its public peer id (read from profile) to its private peer id peer_id in private_peer_of. Asynchronous. Returns the result of AgentBasics.add_agent(). The three flags about streams are part of the signature of the parent and the world ignores them. The node calls it when a member completes the handshake.

remove_agent async

remove_agent(peer_id: str) -> bool
Source code in unaiverse/world.py
async def remove_agent(self, peer_id: str) -> bool:
    """Removes an agent from the world and cleans up the public-to-private peer ID mapping (async).

    Args:
        peer_id: The private peer ID of the agent to remove.

    Returns:
        True if the agent was successfully removed by the parent class, False otherwise.
    """
    profile = None
    if peer_id in self.all_agents:
        profile = self.all_agents[peer_id]
    if await super().remove_agent(peer_id):
        if profile is not None:
            public_peer_id = profile.get_dynamic_profile()["peer_id"]
            if public_peer_id in self.private_peer_of:
                del self.private_peer_of[public_peer_id]
        return True
    else:
        return False

Removes the member peer_id through AgentBasics.remove_agent(). Asynchronous. The parent method removes the member from every list, drops its streams and interactions and returns None. This method therefore always returns False and never deletes the entry of the member from private_peer_of. The node calls it when a member leaves.

set_addresses_in_profile

set_addresses_in_profile(peer_id: str, addresses: list[str]) -> None
Source code in unaiverse/world.py
def set_addresses_in_profile(self, peer_id: str, addresses: list[str]) -> None:
    """Updates the network addresses in an agent's profile.

    Args:
        peer_id: The ID of the agent whose profile is being updated.
        addresses: A list of new addresses to set.
    """
    if peer_id in self.all_agents:
        profile = self.all_agents[peer_id]
        addrs = profile.get_dynamic_profile()['private_peer_addresses']
        addrs.clear()  # Warning: do not allocate a new list, keep the current one (it is referenced by others)
        for _addrs in addresses:
            addrs.append(_addrs)
        self.received_address_update = True
    else:
        log.error(f"Cannot set addresses in profile, unknown peer_id {peer_id}")

Replaces the private addresses in the profile of the member peer_id with addresses and marks received_address_update. The list object in the profile is emptied and refilled in place because other parts of the node hold a reference to it. An unknown peer_id is logged as an error. The node calls it when a member announces new addresses. Returns None.

Statistics

Every member sends its statistics to the world every Custom.SEND_STATS_EVERY seconds (30 by default, changed by the argument send_stats_every of Node). The world merges them into stats and saves them to disk every Custom.SAVE_STATS_EVERY seconds. The format of the statistics and the database are described in unaiverse.stats.

collect_and_store_own_stats

collect_and_store_own_stats() -> None
Source code in unaiverse/world.py
def collect_and_store_own_stats(self) -> None:
    """Collects this world's own stats and pushes them to the stats recorder."""
    if self.stats is None:
        return

    t = clock.get_time_ms()
    _, own_private_pid = self.get_peer_ids()

    try:
        self.stats.store_stat("world_masters", len(self.world_masters), group_key=own_private_pid,
                              timestamp=t)
        self.stats.store_stat("world_agents", len(self.world_agents), group_key=own_private_pid,
                              timestamp=t)
        self.stats.store_stat("human_agents", len(self.human_agents), group_key=own_private_pid,
                              timestamp=t)
        self.stats.store_stat("artificial_agents", len(self.artificial_agents), group_key=own_private_pid,
                              timestamp=t)
    except Exception as e:
        log.error(f"[Stats] Error updating own world stats: {e}")

Stores the four counters of the world (world_masters, world_agents, human_agents and artificial_agents) in stats with the current time of the clock in milliseconds. The group key is the private peer id of the world. Errors are logged. add_peer_stats() calls it before processing each batch. Returns None.

add_peer_stats

add_peer_stats(peer_stats_batch: list[dict[str, Any]], sender_peer_id: str | None = None) -> None
Source code in unaiverse/world.py
def add_peer_stats(self, peer_stats_batch: list[dict[str, Any]],
                   sender_peer_id: str | None = None) -> None:
    """Processes a batch of stats received from a peer and updates internal state (world-only).

    Stores valid stats in the Stats recorder, collects ``connected_peers`` updates for
    deferred graph processing, and calls ``_prune_graph`` at the end of each batch.

    Args:
        peer_stats_batch: A list of stat-update dictionaries, each containing
            ``"peer_id"``, ``"stat_name"``, ``"timestamp"``, and ``"value"`` keys.
        sender_peer_id: The peer ID of the sender; currently unused for filtering
            (default: None).
    """

    # 1. Update own stats (this logic is now in the World)
    self.collect_and_store_own_stats()

    # 2. Process peer stats
    connected_peers = []
    assert self.stats is not None
    for update in peer_stats_batch:
        try:
            p_id = update['group_key']
            if p_id != sender_peer_id:
                # TODO: decide if we want to filter the stats
                pass
            stat_name = update['stat_name']
            t = int(update['timestamp'])
            v = update['value']

            # Call the hook (which also lives in the World now)
            if self._process_custom_stat(stat_name, v, p_id, t):
                continue  # The custom processor handled it

            # Generate the graph and handle the connected_peers stat
            if stat_name == 'connected_peers':
                # We need to wait for all the info to arrive before updating the graph.
                # Otherwise, _extract_graph_node_info may not find data yet.
                connected_peers.append((p_id, v, t))
                continue

            # 3. Push to the "dumb" Stats recorder
            if stat_name in self.stats.all_keys:
                self.stats.store_stat(stat_name, v, group_key=p_id, timestamp=t)
            else:
                log.error(f"[World] Unknown stat received: {stat_name}")

        except Exception as e:
            log.error(f"[World] Error processing stats update {update}: {e}")

    # Now update the graph for all collected connected_peers stats
    for p_id, v, t in connected_peers:
        self._update_graph(p_id, v, t)

    # Clean the graph from potentially stale peers
    self._prune_graph()

Processes one batch of statistics received from a member and returns None. The node calls it for every statistics message. Each element of peer_stats_batch is a dictionary with the keys group_key (the peer id the value refers to), stat_name, timestamp (milliseconds) and value. The method works in four steps.

  1. It stores the counters of the world with collect_and_store_own_stats().
  2. It offers each update to the protected hook _process_custom_stat(stat_name, value, group_key, timestamp). A subclass overrides the hook and returns True to take over an update. The base hook returns False.
  3. It keeps the updates named connected_peers for the graph and stores every other update whose name is known to stats. An unknown name and a malformed update are logged and skipped.
  4. It updates the connectivity graph (the static statistic graph) with the connected_peers of the batch and removes from the graph the peers that are no longer members.

The method ignores sender_peer_id.

answer_stats_request

answer_stats_request(filters: dict, asker: str) -> dict | None
Source code in unaiverse/world.py
def answer_stats_request(self, filters: dict, asker: str) -> dict | None:
    """Respond to a stat request."""
    assert self.stats is not None
    assert asker is not None  # Not used here, but might be used when overloading this method in custom worlds

    # Default values are added to query without any filter
    stat_names = filters.get('stat_names', [])
    group_keys = filters.get('group_keys', [])
    time_range = filters.get('time_range', 0)
    value_range = filters.get('value_range', None)  # The numeric filter
    limit = filters.get('limit', None)

    return self.stats.query_history(
        stat_names=stat_names,
        group_keys=group_keys,
        time_range=time_range,
        value_range=value_range,
        limit=limit)

Answers a statistics request of a member and returns a dictionary shaped like Stats.get_view(). The node calls it when a member runs the action ask_world_stats(filters) with a non-empty stat_names. Without stat_names the node answers with the HTML of stats.plot() instead and this method is not called. The base method passes the filters to Stats.query_history().

Key of filters Default Meaning
stat_names [] The names of the statistics to return.
group_keys [] The peer ids to return. An empty list means all.
time_range 0 An integer t keeps the values from t on and a pair [start, end] keeps the closed interval. Both forms are in milliseconds.
value_range None A pair [min, max] that keeps the numeric values in the closed interval.
limit None The maximum number of time-series rows. Values above 5000 are lowered to 5000.

asker is the peer id of the member that asked. The base method only asserts that it is not None. A subclass uses it to decide what each member may see:

class Classroom(World):

    def answer_stats_request(self, filters, asker):
        if asker not in self.world_masters:
            filters = {**filters, "group_keys": [asker]}  # a student sees only itself
        return super().answer_stats_request(filters, asker)

debug_stats_dashboard

debug_stats_dashboard() -> None
Source code in unaiverse/world.py
def debug_stats_dashboard(self) -> None:
    """Helper to verify the dashboard looks correct during development."""
    import tempfile
    import webbrowser

    log.debug("Rendering Dashboard...")
    assert self.stats is not None
    html = self.stats.plot()
    if html:
        tmp = tempfile.NamedTemporaryFile(suffix=".html", delete=False, mode="w", encoding="utf-8")
        tmp.write(html)
        tmp.close()
        webbrowser.open(f"file://{tmp.name}")

Renders stats.plot() to a temporary HTML file and opens it in the default web browser. It is meant for development on a machine with a browser and returns None. Nothing opens when plot() returns None.