Skip to content

4 · Behaviors as state machines

A teacher does not run one long script. It waits for students, gives a lecture, examines the class, asks for help and starts again. At each moment the next step depends on what happened: a student left, an exam is not finished, a lecture is over. UNaIVERSE describes this kind of behavior with a hybrid state machine (HSM). The states say where the agent is. The transitions say what the agent can do from there. Each transition runs an action, a method of the role class that succeeds or fails. The third stage of the classroom (tutorial_steps/step3) gives both roles their complete machines. Their actions do nothing yet.

The teacher

stateDiagram-v2
    direction LR
    [*] --> init
    init --> in_class: find_agents(role=student)
    in_class --> ready_for_lecture: give_next_lecture
    ready_for_lecture --> lecture_in_progress: teach
    lecture_in_progress --> in_class: lecture_finished
    in_class --> ready_for_exam: start_exam_session
    ready_for_exam --> exam_in_progress: hand_out_exam
    exam_in_progress --> exam_in_progress: on_data(exam)
    exam_in_progress --> in_class: evaluate_results
    in_class --> ready_for_feedback: ask_for_feedback
    ready_for_feedback --> feedback_time: send_requests
    feedback_time --> feedback_time: on_data(feedback)
    feedback_time --> init: augment_lectures
src/world.py (teacher, from the final world)
behav.add_state("init", action="reset_status", blocking=False,
                msg="🕐 Waiting for students to join the class...")
behav.add_state("in_class", waiting_time=3.0, blocking=False,
                msg="🏫 In class, deciding what to do next...")
behav.add_state("ready_for_lecture", waiting_time=8.0, blocking=False,
                msg="📚 Lecture about to start...")
behav.add_state("lecture_in_progress", blocking=True,
                msg="📚 Lecture in progress: streaming pictures and labels...")
# ... ready_for_exam, exam_in_progress, ready_for_feedback, feedback_time

behav.add_transit("init", "in_class", action="find_agents",
                  args={"role": "student", "handshake_completed": True})
behav.add_transit("in_class", "ready_for_lecture", action="give_next_lecture")
behav.add_transit("ready_for_lecture", "lecture_in_progress", action="teach")
behav.add_transit("lecture_in_progress", "in_class", action="lecture_finished")
behav.add_transit("in_class", "ready_for_exam", action="start_exam_session")
# ... the exam and feedback transitions of the diagram

The machine reads like the day of the teacher. In init it resets its status and waits until find_agents finds at least one student. In in_class three transitions compete: the next lecture, the exam and the request for feedback. The actions decide which one wins. give_next_lecture succeeds while lectures remain, start_exam_session succeeds once the lectures are over and ask_for_feedback succeeds after the exam. The self-transitions on exam_in_progress and feedback_time keep collecting answers until the exam or the feedback round is over.

The student

stateDiagram-v2
    direction LR
    [*] --> init
    init --> teacher_found: connect_by_role(role=teacher)
    teacher_found --> in_class: connected
    in_class --> in_class: print (requested)
    in_class --> done_learning: learn (requested)
    in_class --> done_exam_or_feedback: process (requested)
    done_learning --> in_class: nop
    done_exam_or_feedback --> in_class: nop
    teacher_found --> wait_to_recover: disconnected (teleport, after 5 s)
    in_class --> wait_to_recover: disconnected (teleport)
    wait_to_recover --> init: nop (teleport, after 60 s)

The student first connects to a teacher and waits for the approval of the connection. In in_class it waits for the teacher to ask something. Three actions can run there: print shows a message of the teacher, learn trains the processor on a lecture and process answers an exam or a feedback request. All three are requested actions. The student never starts them on its own initiative and runs them only when the teacher sends an interaction that asks for them.

src/world.py (student)
behav.add_transit("in_class", "done_learning", action="learn", args={},
                  timeout=WAgentTeacher.LECTURE_RESPONSE_DELTA,
                  ready=False)
behav.add_transit("in_class", "done_exam_or_feedback", action="process", args={},
                  timeout=WAgentTeacher.EXAM_OR_FEEDBACK_RESPONSE_DELTA,
                  ready=False)
behav.add_transit("in_class", "wait_to_recover", action="disconnected", teleport=True)
behav.add_transit("wait_to_recover", "init", action="nop", delay=60, teleport=True)

States

add_state(state, action=None, args=None, state_id=None, waiting_time=None, blocking=None, msg=None, msg_action=None) adds a state or updates an existing one.

  • action and args. An optional action that runs every time the machine is in the state and before it considers the transitions. The teacher resets its status in init this way.
  • blocking (default True). After a transition into a blocking state, the machine stops for the current cycle of the node and goes on at the next one. A non-blocking state lets the machine try the transitions of the new state in the same cycle. A state in which the agent must wait for the next cycle, like teacher_found of the student or lecture_in_progress of the teacher, is blocking.
  • waiting_time (default 0). The number of seconds the machine spends in the state before it considers the transitions that leave it. ready_for_lecture waits 8 seconds to give the students time to read the announcement of the lecture.
  • msg. A message that the agent prints when it enters the state. The welcome message of the role is separate and comes from set_welcome_message.

The first state added is the initial state.

Transitions

add_transit(from_state, to_state, action, args=None, ready=True, act_id=None, msg=None, avoid_changing_ready=False, teleport=False, high_priority=False, total_time=0., timeout=0., delay=0.) adds a transition that runs action with args and moves the machine to to_state when the action succeeds.

  • ready. A transition with ready=True runs on the initiative of the agent. A transition with ready=False runs only when another agent requested its action through an interaction. The learn and process transitions of the student have ready=False and wait for a request of the teacher.
  • delay (seconds). The transition is considered only after the machine has spent this time in the state. The student tries to recover from a lost teacher only 5 seconds after entering teacher_found.
  • timeout (seconds, stored as retry_timeout in JSON). With a timeout the action is pedantic. When it returns False the machine runs it again at the next cycle and keeps retrying until the action succeeds or the timeout expires. Without a timeout a failed action gives way to the next transition of the state.
  • total_time (seconds, stored as max_duration in JSON). The maximum duration of an action that spans several cycles, counted from the moment it starts.
  • high_priority. The policy prefers this transition to the others of the same state.
  • teleport. The transition is not drawn in the PDF of the machine. Teleports are the transitions that can fire from anywhere in the normal flow, such as the recovery from a lost teacher. Drawing them would only clutter the picture.

from_state="all" adds the same transition to every state except the destination. add_global_teleport(to_state, action, ...) does the same with a teleport. When to_state is the path of a JSON file, the machine loads that file and plugs it in: the transition leads to the initial state of the included machine and the states of the included machine are renamed when their names clash.

How the machine chooses

At every cycle of the node the machine runs the action of the current state and then looks at the transitions that leave it. The default policy picks the transition in this order:

  1. a transition marked high_priority
  2. a transition whose action has a pending request from another agent, oldest request first
  3. the first transition that is ready, in the order in which the transitions were added

The machine calls the action of the chosen transition. An action returns True when it succeeded and False when it did not. The machine then moves to the destination state on success. After a failure, a pedantic action whose timeout has not expired runs again at the next cycle. Any other failed action gives way to the next candidate. A requested action that cannot run is moved to the back of the queue and the other requests of the same action get their turn. The machine keeps going within the same cycle until it reaches a blocking state or until no action succeeds.

A role class can replace the policy and can install a policy filter that corrects what the policy chose. Both are described in Behaviors.

Wildcards

A behavior often refers to agents and streams that do not exist when the world writes it. Wildcards fill these gaps at runtime:

Wildcard Replaced by
<world> the peer identifier of the world
<agent> the peer identifier of the agent that runs the behavior
<partner> the peer identifier of the current partner of the agent
<role> the role of the agent

A transition such as add_transit("ready", "asked", action="send", args={"target": "<partner>", "streams": ["<agent>:processor"]}) works for every agent that runs it. The default behavior of a lone wolf uses exactly these two wildcards. A world can add its own wildcards with add_wildcards({...}).

The JSON format

save writes the machine as JSON with four sections:

{
  "machine": {"role": "student", "initial_state": "init", "msg": "<welcome message>", "options": {}},
  "states": {
    "init": {"action": null, "action_kwargs": {}, "msg": null,
             "blocking": false, "time_to_wait_before_acting": 3.0}
  },
  "transitions": {
    "in_class": [
      {"on": {"action": "learn", "action_kwargs": {}, "msg": null, "ready": false,
              "high_priority": false, "max_duration": 0.0, "retry_timeout": 17.5, "delay": 0.0},
       "goto": "done_learning"}
    ]
  },
  "teleports": {
    "in_class": [
      {"on": {"action": "disconnected", "action_kwargs": {}, "msg": null, "ready": true,
              "high_priority": false, "max_duration": 0.0, "retry_timeout": 0.0, "delay": 0.0},
       "goto": "wait_to_recover"}
    ]
  }
}

transitions and teleports map each source state to a list of transitions, each with the action in on and the destination in goto. Python and JSON are interchangeable. A world can write the files by hand, generate them in create_behav_files as the classroom does or start from JSON templates and plug them into a larger machine.

Changing state from code

A role class can force a transition. The teacher of the final world checks in on_tick whether any student is still connected and goes back to init when the class is empty:

if len(self.get_agents_by_role("student")) == 0 and self.behav.get_state_name() != "init":
    await self.behav.act_ghost_transition("init")

act_ghost_transition(to_state) adds a temporary transition with the action nop from the current state, runs it and removes it. Any multistep action in progress is abandoned.

Run it

Run tutorial_steps/step3. The world writes teacher.json, student.json and their PDFs. Open the PDFs to see both machines drawn. With a student connected, the teacher walks through its states and prints their messages. Every action is an empty stub that returns True and the teacher therefore loops through the lecture states forever.

What just happened

The world built two machines from Python and checked them against dummy agents of their roles. Each member loaded the machine of its role from the grant. At every cycle of its node, the machine of the teacher ran the action of its state and then the first transition whose action succeeded. Since every stub succeeds at once, the teacher never leaves the lecture loop. The student connected to the teacher and then waited in in_class for requests that never came.

Where next

Chapter 5 writes the actions that make these machines do something.

5 · Writing actions