Skip to content

Behaviors

An agent does not run a fixed loop. It follows a behavior, a state machine whose transitions are labeled by actions. At each tick the behavior looks at the transitions that leave the current state, picks one action whose conditions hold and runs it. When the action succeeds, the machine moves to the destination state. The machine is called hybrid because an action is Python code with its own state (it can last many ticks, wait for data or call other agents) and not a plain label.

Every agent has two behaviors. The public behavior drives it on the public network (as a lone wolf) and the world behavior drives it inside a world. A world gives each role its own behavior and sends it to the members when they join (see Worlds). The class is HybridStateMachine in unaiverse.hsm.hsm (API reference).

The webapp draws the behavior of each role of a world under Roles on the card of the world. Blocking states, autonomous transitions and transitions that wait for an interaction have their own marks. The Definition tab shows the JSON of the same behavior.

The behavior of the Guest role of TuringHotelItaly drawn as a diagram in the webapp

The webapp draws the behavior of the role Guest of TuringHotelItaly.

The default public behavior

An agent without a world loads unaiverse/utils/public.json. This behavior serves the requests of other agents and also lets the agent act on its own initiative:

stateDiagram-v2
    [*] --> ready
    ready --> generated: process (requested)
    generated --> ready: nop
    ready --> self_generated: process (ready)
    self_generated --> asked: send process to partner
    self_generated --> ready: nop
    asked --> ready: nop
  • In ready, a process request of another agent takes the machine to generated. The output of the processor goes back to the requester and nop returns to ready.
  • The same process with ready: true runs on the initiative of the agent. An agent whose processor produces something without any input (a generator, a sensor) runs it and reaches self_generated. From there it sends a process request with its last output to <partner> (the public peer that got in touch last) and goes to asked.

Because ready is blocking, the machine stops there at every tick and waits for the next one.

JSON format

A behavior file has four sections.

{
  "machine": {"role": "student", "initial_state": "waiting", "msg": "Welcome", "options": {}},
  "states": {
    "waiting": {"action": null, "action_kwargs": {}, "msg": null, "blocking": true, "time_to_wait_before_acting": 0.0}
  },
  "transitions": {
    "waiting": [
      {"on": {"action": "learn", "action_kwargs": {}, "msg": "Learning", "ready": false,
              "high_priority": false, "max_duration": 0.0, "retry_timeout": 0.0, "delay": 0.0},
       "goto": "learned"}
    ]
  },
  "teleports": {}
}
Key Meaning
machine.role The role that the machine implements (public for the public behavior).
machine.initial_state The state where the machine starts.
machine.msg A welcome message that a person sees when the machine starts.
machine.options Display options of the messages: highlight_blocking_states_in_messages, show_action_ticks_after_messages, show_action_request_after_messages.
states.<name>.action An optional action that runs in the state before the machine tries the transitions.
states.<name>.action_kwargs The arguments of that action.
states.<name>.msg A message shown to a person in this state.
states.<name>.blocking true makes the machine wait for the next tick after entering the state. false lets it try the transitions of the new state in the same tick.
states.<name>.time_to_wait_before_acting Seconds to spend in the state before trying its transitions.
transitions.<from> The list of transitions that leave the state <from>. Each has an on (the action) and a goto (the destination state). The state name all adds the transition to every state.
teleports Transitions with the same format that the drawings of the machine hide.

The options of a transition (on):

Option Default Meaning
action required The name of the action.
action_kwargs {} Its arguments. String values may contain wildcards.
msg null A message shown to a person when the action runs.
ready true true lets the machine run the action on its own initiative. false runs it only when another agent requests it. An action with a parameter named interaction is request-only unless the file says ready: true.
high_priority false The default policy prefers this transition over the others.
max_duration 0 The maximum life of the action in seconds since it started. 0 or less means no limit.
retry_timeout 0 How long the machine keeps retrying a failing action before giving up. 0 or less means no limit.
delay 0 Seconds that must pass after entering the state before this transition is considered.

The three time options also accept a wildcard string resolved at run time.

One step

act() runs at each tick of the node.

  1. It runs the action of the current state when the state has one.
  2. It collects the actions of the transitions that leave the state and are feasible now. An action is feasible when its delay has passed and someone requested it or it is ready.
  3. The policy picks one of them (see Policies) and the machine runs it.
  4. When the action returns True, the machine moves to the destination state. When it returns False, the machine stays in the state. With a retry_timeout it runs the same action again at the next tick until the timeout runs out. Without one it tries the next feasible action.
  5. If the new state is not blocking and the action ended, the machine goes back to step 1 in the same tick. It stops at a blocking state or when no feasible action succeeds.

An action that spans several steps (a multi-step action with num_steps samples, or a computation sliced with stepwise, see Actions) keeps the machine in the same state until its last step.

Wildcards

Strings of the form <name> in the arguments are replaced before the action runs.

Wildcard Becomes
<agent> The peer id of the agent itself.
<world> The peer id of the world node.
<role> The role of the agent.
<partner> In the public behavior, the public peer that last got in touch with the agent. Accepting a request from another public peer moves <partner> to that peer. The agent of a person does not change it because the interface of the person (the webapp or the terminal) points it at the peer the person writes to.

A world adds its own wildcards with agent.add_behav_wildcard(wildcard_from, wildcard_to). A behavior adds them with add_wildcards({...}) or update_wildcard(key, value). The machine also resolves node names into peer ids in the arguments named agent, agents, partner, partners, target and targets. In the arguments named stream and streams it resolves stream names into user hashes or net hashes.

Policies

The default policy (policy_default) serves requested actions first. It picks the first action with pending requests and serves its oldest request. When nothing is requested, it picks the first ready action in the order of the file. high_priority transitions come before all of them.

You change it in two ways.

  • await agent.set_policy(policy, public=False) replaces the policy. policy is a function (or the name of a method of the agent) that receives the list of feasible Action objects and returns a pair with the index of the chosen action and its interaction. It returns (-1, None) to choose nothing.
  • agent.set_policy_filter(filter_fcn, public=False) (or the policy_filter and policy_filter_lone_wolf arguments of Agent) adds a filter that receives the decision of the policy, the list of actions and a dictionary with the key agent and returns the final choice. A filter can delay, veto or redirect a decision without rewriting the policy.

PolicyFilterDelayAction(action_names, wait, add_random_up_to=0.) in unaiverse.utils.misc is a ready-made filter that delays the listed actions by wait seconds plus a random extra up to add_random_up_to.

Building a behavior in Python

You can write the file by hand or build the machine in code and save it.

from unaiverse.hsm.hsm import HybridStateMachine

hsm = HybridStateMachine(agent)
hsm.add_state("waiting", blocking=True, msg="Waiting for the teacher")
hsm.add_transit("waiting", "learned", action="learn", ready=False)
hsm.add_transit("learned", "waiting", action="nop")
hsm.set_role("student")
hsm.set_welcome_message("You are a student of this class.")
hsm.save("student.json")
Method Meaning
add_state(state, action=None, args=None, waiting_time=None, blocking=None, msg=None) Adds a state or updates an existing one. waiting_time is time_to_wait_before_acting.
add_transit(from_state, to_state, action, args=None, ready=True, msg=None, teleport=False, high_priority=False, total_time=0., timeout=0., delay=0.) Adds a transition. total_time is max_duration and timeout is retry_timeout. A to_state that is the path of another behavior file includes that machine.
add_teleport(...), add_global_teleport(to_state, action, ...) Adds a hidden transition from one state or from every state.
include(hsm) Merges another machine into this one.
set_role(role), set_welcome_message(msg) Set machine.role and machine.msg.
save(filename, only_if_changed=None) Writes the JSON file and returns True. With only_if_changed=agent it writes only when the content changed.
load(filename_or_json) Reads a file, an open file or a JSON string and returns the machine.
get_state_name(), set_state(state), reset_state() Read and change the current state.
save_pdf(filename) Draws the machine with Graphviz. The Graphviz program must be installed.
set_debug_messages_active(yes) Prints every step of the machine.