Skip to content

Python API

This page is generated from the docstrings in the source. It covers the modules you use when you write tools, support agents and tests. The guides explain how the pieces fit together: see Tools, Support agent and the tutorials.

Tools

hani2.tools.base

The :class:Tool base class.

A tool is a small Python object that lives for one browser session. It receives the negotiation lifecycle callbacks and describes its UI declaratively with :mod:hani2.tools.ui components. HANI2 renders the view in one of three panes (upper, lower or side), re-rendering it whenever the tool calls :meth:Tool.refresh (which every lifecycle hook does by default).

Minimal tool::

from hani2.tools import Tool, ui

class OfferCounter(Tool):
    name = "Offer Counter"
    pane = "side"

    def view(self):
        n = len(self.trace())
        return [ui.stat("Offers so far", n)]

Register it in settings/env.json::

{"tools": {"extra": ["my_package.tools:OfferCounter"]}}

or ship it in a package with an entry point in the hani2.tools group.

Tool

Tool(session_state: dict[str, Any], enabled: bool | None = None, **params: Any)

Base class for all HANI2 tools.

Class attributes (all optional) describe how the tool is registered:

============== =========================================================== name Tab title (defaults to the class name). Must be unique. description One line shown in the tool picker / to the support agent. icon A lucide icon name (kebab case), e.g. "chart-line". pane Default pane: "upper", "lower" or "side". timing When the tool appears: "always" (page open), "load" (scenario loaded), "start" (negotiation started), "end" (negotiation finished) or "agent" (never on its own: only when a support agent adds it). permanent Always on: no enable switch, cannot be hidden. admin_only Only logged-in administrators get the tool. guest Whether guests / playground users get it (default True). enabled Default state of the user-facing enable switch. Disabled tools still show their tab, but :meth:view is not called until the user switches them on. order Sort key inside its pane (smaller first). agent_hint Extra advice for a support agent on when and how to use the tool (added to what it reads with read_tool). ============== ===========================================================

A support agent can read any tool (:meth:describe_for_agent) and use its inputs and buttons, so a tool written for people is usable by the agent without extra code.

may_see_opponent property

may_see_opponent: bool

Whether this participant may see the opponent's utilities: admins always; everyone when env.json → tools.show_opponent_utility is true.

view_lock property

view_lock: RLock

Held while the tool is rendered or read by a support agent, so the two never run :meth:view at the same time.

trace

trace() -> list

The mechanism's full_trace (empty before the negotiation starts).

context

context() -> dict[str, Any]

The live negotiation snapshot (same dict the support agent sees).

set_offer

set_offer(outcome: Outcome | dict[str, Any] | None) -> dict

Fill the human's counter-offer draft (does not send it).

describe_for_agent

describe_for_agent(max_chars: int = 4000) -> str

What this tool shows, as text for a support agent: its description, :attr:agent_hint, and its current view (numbers, table rows, chart summaries, and the inputs and buttons it can use). Override to give the agent a better summary than the generic one.

refresh

refresh() -> None

Ask HANI2 to re-render this tool.

init

init(session_state: dict[str, Any]) -> None

Called once when the tool is created.

scenario_loaded

scenario_loaded(session_state: dict[str, Any], scenario: Scenario) -> None

Called after a scenario is loaded.

negotiation_started

negotiation_started(session_state: dict[str, Any], nmi: SAONMI) -> None

Called when the negotiation starts.

negotiation_ended

negotiation_ended(session_state: dict[str, Any], nmi: SAONMI) -> None

Called when the negotiation ends.

action_requested

action_requested(session_state: dict[str, Any], nmi: SAONMI) -> None

Called whenever it becomes the human's turn.

action_to_execute

action_to_execute(session_state: dict[str, Any], nmi: SAONMI, action: SAOResponse) -> None

Called just before the human's action is executed.

action_executed

action_executed(session_state: dict[str, Any], nmi: SAONMI, action: SAOResponse) -> None

Called after the human's action is executed.

view

view() -> list[ui.Component]

Return the tool's UI as a list of :mod:hani2.tools.ui components.

on_input

on_input(name: str, value: Any) -> None

An input component changed. Default: store it and re-render.

on_action

on_action(action: str, payload: dict[str, Any]) -> None

A button was clicked or a table row selected.

render

render() -> list[ui.Component]

Called by HANI2; wraps :meth:view with error reporting.

OutcomeSelector

OutcomeSelector(session_state: dict[str, Any], enabled: bool | None = None, **params: Any)

Bases: Tool

A tool that proposes an outcome and fills the offer with it.

Override :meth:get_outcome; a Set Offer button is appended to :meth:selector_view automatically.

UI components

hani2.tools.ui

Declarative UI components for tools.

A tool's :meth:~hani2.tools.Tool.view returns a list of components built with these helpers. They are plain JSON-able dicts that the web frontend renders, so a tool author only ever writes Python.

Interactive components:

  • Inputs (select, multiselect, slider, number, checkbox, switch, radio, text, textarea) carry a name. When the user changes one, the tool's :meth:~hani2.tools.Tool.on_input is called with (name, value). The default implementation stores the value in self.values[name] and re-renders.
  • Buttons carry an action. Clicking calls :meth:~hani2.tools.Tool.on_action with (action, payload) where payload is the button's payload plus the current values of all inputs.
  • Tables may set on_select=<action>; clicking a row calls on_action with payload={"row": <row dict>, "index": <int>}.

Example::

from hani2.tools import Tool, ui

class Hello(Tool):
    name = "Hello"

    def view(self):
        return [
            ui.markdown("### Hello"),
            ui.slider("level", 0, 100, self.values.get("level", 50), label="Level"),
            ui.button("Shout", action="shout"),
        ]

    def on_action(self, action, payload):
        self.toast(f"Level is {self.values.get('level', 50)}")

jsonable

jsonable(x: Any) -> Any

Convert numpy / negmas values to JSON-friendly Python values.

markdown

markdown(text: str, *, size: str | None = None) -> Component

Markdown (GitHub flavoured; tables supported). size: sm | md | lg.

alert

alert(text: str, kind: str = 'info', title: str | None = None) -> Component

kind: info | success | warning | error | neutral (markdown text).

html

html(content: str) -> Component

Raw (sanitised) HTML. Prefer :func:markdown where possible.

progress

progress(value: float, label: str | None = None, kind: str | None = None) -> Component

value in [0, 1].

outcome

outcome(values: dict[str, Any], utility: float | None = None, label: str | None = None) -> Component

A compact outcome card (issue → value chips plus an optional utility).

plot

plot(fig: Any, *, height: int | None = None, key: str | None = None) -> Component

A Plotly figure (plotly.graph_objects.Figure or a figure dict).

table

table(rows: Iterable[dict[str, Any]] | Any, columns: Sequence[str] | None = None, *, on_select: str | None = None, page_size: int = 25, formats: dict[str, str] | None = None, selected: int | None = None, max_height: int | None = None, searchable: bool = False, sortable: bool = True, dense: bool = True) -> Component

A data table. rows may be a list of dicts or a pandas DataFrame.

formats maps a column to "percent", "float", "int" or "text".

button

button(label: str, action: str, *, payload: dict[str, Any] | None = None, variant: str = 'secondary', icon: str | None = None, disabled: bool = False, full: bool = False, tooltip: str | None = None) -> Component

variant: primary | secondary | success | danger | ghost. icon: a lucide icon name in kebab case (e.g. "sparkles").

radio

radio(name: str, options: Any, value: Any = None, *, label: str | None = None) -> Component

A segmented control.

grid

grid(*children: Component | None, cols: int = 2, gap: int = 3) -> Component

Responsive grid (collapses to one column on narrow panes).

Support agent runtime

hani2.support_agent.runtime

The Negotiation Support Agent runtime.

One :class:SupportAgent lives in each session (session_state["support_agent"]). It owns the conversation with its language model, the capability state, and the multi-turn tool-calling loop, and it can reach the participant at any moment (chat, notifications, the status board, highlights, notes, layout changes and custom panels).

All agent code runs in worker threads, so it may block (LLM calls, ask_user) without freezing the interface. Use :meth:SupportAgent.run_on_doc to read or change interface-owned state atomically.

Build your own agent by subclassing :class:SupportAgent and pointing support_agent_settings.json → agent_class at it ("my_module:MyAgent").

SupportAgent

SupportAgent(session_state: dict[str, Any], settings: dict)

Base Negotiation Support Agent.

Override any of these (all optional):

  • :meth:build_system_prompt — the agent's persona / instructions.
  • dispatcher_class / :meth:make_dispatcher — add or change the functions the language model may call.
  • :meth:handle_user_message — full control over a chat turn (e.g. a rule-based agent with no LLM at all).
  • :meth:on_event / :meth:proactive_note — react to negotiation events (negotiation_started, action_requested, negotiation_ended).
  • :meth:on_draft_changed — react while the human edits their offer.
  • :meth:on_panel_action — a button in one of your panels was clicked.
  • :meth:_complete — replace the LLM backend.

run_on_doc

run_on_doc(fn, timeout: float = 30.0)

Run fn atomically with respect to the interface state and return its result.

context

context() -> dict[str, Any]

The live negotiation snapshot (issues, offers, utilities, history…).

post

post(text: str, user: str | None = None) -> None

Post a chat message from the agent.

toast

toast(message: str, level: str = 'info') -> bool

A pop-up notification (needs the toast capability; falls back to chat).

show_on_board

show_on_board(text: str, append: bool = False) -> bool

Write markdown to the always-visible status board.

message_user

message_user(text: str, channel: str = 'chat') -> None

Tell the human something right now: chat, toast or board.

ask_user

ask_user(question: str, options: list[str] | None = None, timeout: float = 180.0) -> str | None

Ask the human a question and block until they answer (buttons or typed reply). Returns None on timeout, under autopilot, or if another question is pending.

highlight

highlight(target: str, message: str | None = None, style: str = 'pulse', duration: float | None = None) -> dict

Spotlight an element ("accept", "issue:Price", "tool:Utility Plot" …). Needs the highlight capability.

annotate

annotate(target: str, text: str | None, kind: str = 'info') -> dict

Attach a note to an element; text=None removes it. Needs annotate.

set_layout

set_layout(**changes: Any) -> dict

view (full | simple | focus), collapsed, sizes. Needs layout.

focus_tool

focus_tool(name: str) -> dict

Bring a tool to the front. Needs tool_visibility.

show_panel

show_panel(panel_id: str, title: str, components: list, placement: str = 'assistant') -> dict

Show a panel built from :mod:hani2.tools.ui components. Buttons and table selections in it call :meth:on_panel_action. Needs panels.

toolbox

toolbox() -> dict[str, type]

Tools the agent may add now, by name: its own :attr:tools, the toolbox setting, and registered tools the participant does not have yet. Admin-only, guest and tools.disabled rules apply.

available_tools

available_tools() -> list[dict[str, Any]]

[{name, description, pane}] of the tools :meth:add_tool accepts by name.

add_tool

add_tool(tool: Any, *, pane: str | None = None, at_front: bool = True, focus: bool = True) -> dict

Add a tool to the participant's screen now. tool is a name from :meth:available_tools, a Tool subclass or an instance. It stays for the rest of the session. Needs tool_add.

remove_tool

remove_tool(name: str) -> dict

Remove a tool that was added during the session. Needs tool_add.

read_tool

read_tool(name: str, max_chars: int = 4000) -> dict

What a tool currently shows, as text ({"ok", "tool", "text"}), including its inputs and buttons. Needs tool_use.

use_tool

use_tool(name: str, *, inputs: dict[str, Any] | None = None, action: str | None = None, payload: dict[str, Any] | None = None, row: int | None = None) -> dict

Operate a tool like the participant would: set its inputs (by input name), then press the button action (or select table row of the table whose selection action is action). Anything the tool then does to the offer, message, accept or end obeys the agent's own capabilities and autonomy. Returns what the tool shows afterwards. Needs tool_use.

handle_user_message

handle_user_message(text: str) -> None

The human sent a chat message (runs in a worker thread).

on_draft_changed

on_draft_changed(draft: dict[str, Any]) -> None

The human edited the counter-offer. Default: the reserved-value warning.

warn_if_draft_below_reserved

warn_if_draft_below_reserved() -> None

Warn (once until fixed) when the draft is worth less than the reserved value.

on_event

on_event(event_name: str, nmi=None) -> None

A negotiation lifecycle event: negotiation_started, action_requested or negotiation_ended.

proactive_note

proactive_note(event_name: str) -> str | None

The system note that seeds a proactive turn (None = stay silent).

on_panel_action

on_panel_action(panel_id: str, action: str, payload: dict[str, Any]) -> None

A button in one of your panels was clicked. Default: tell the LLM.

autopilot_step

autopilot_step(delay: float = 0.0) -> None

Called by the session on every human turn while this agent drives the autopilot. Waits for a previous turn to finish (skipping a turn would stall the round), then decides.

flatten_tool_messages

flatten_tool_messages(messages: list[dict]) -> list[dict]

Express tool calls and results as plain text (needed for Ollama models, whose chat transform drops tool_calls from assistant messages).

parse_text_tool_calls

parse_text_tool_calls(content: str) -> list[dict]

Recover tool calls a model wrote as text ([tool call: name({...})]).

Small local models sometimes imitate the flattened history format instead of emitting real tool calls; this turns them back into calls.

load_class

load_class(path: str) -> type

Load module:Class, module.Class or path/to/file.py:Class.

resolve_agent_class

resolve_agent_class(settings: dict) -> type[SupportAgent]

Resolve agent_class (module:Class, module.Class or path/to/file.py:Class); fall back to :class:SupportAgent (with a warning) if it cannot be loaded.

Support agent functions

hani2.support_agent.tools

The functions the support agent's language model may call.

Each function is gated by a :class:~hani2.support_agent.capabilities.Capability (or None for read-only helpers) and only advertised to the model while that capability is effective. Subclass :class:ToolDispatcher and override :meth:ToolDispatcher.register_extra_tools to add your own functions.

ToolDispatcher

ToolDispatcher(runtime)

register_extra_tools

register_extra_tools() -> None

Hook for ToolDispatcher subclasses to add custom functions.

Add entries to self._registry here::

self._registry["my_tool"] = (None, self._my_tool, self._schema_my_tool)

Use a Capability (or None for ungated read-only helpers) as the first element. Build schemas with the module-level _fn helper.

register

register(name, handler, schema, capability=None) -> None

Convenience for subclasses to register a custom tool.

make_function_schema

make_function_schema(name: str, description: str, properties: dict, required: list[str]) -> dict

Build an OpenAI/litellm function-tool schema. Public helper for custom ToolDispatcher subclasses registering extra tools.

Capabilities

hani2.support_agent.capabilities

Capabilities and autonomy for the Negotiation Support Agent.

Two layers gate what the agent may do:

  • the admin grant — the ceiling, configured in the settings;
  • the user preferences — the human negotiator may switch capabilities off and lower the autonomy level, but can never go beyond the admin grant.

The effective capability set is the intersection, and the effective autonomy is the lower of the two levels. Only effective capabilities are ever offered to the agent's language model as callable functions.

Capability

Bases: str, Enum

Individually grantable abilities. value matches the settings keys.

Autonomy

Bases: str, Enum

How far the agent may act on negotiation decisions.

SUGGEST — fill fields / highlight the recommended button; never execute an irreversible action. SEMI — send counter-offers itself; accept / end go through your confirmation dialog. FULL — execute anything in the effective capability set.

CapabilityState

CapabilityState(admin_capabilities: dict[str, bool], admin_autonomy: Autonomy | str, user_capabilities: dict[str, bool] | None = None, user_autonomy: Autonomy | str | None = None)

Resolves the effective capabilities/autonomy from admin grant ∩ user prefs.

autonomy property

autonomy: Autonomy

The lower (more restrictive) of the admin and user levels.

has

has(capability: Capability | str) -> bool

Effective = granted by the admin AND not switched off by the user.

Testing helpers

hani2.testing

Helpers to run negotiations headlessly — for tests of your agents and tools.

Example::

from hani2.testing import make_session

s = make_session(agent_class="my_agent:MyAgent", partner="BoulwareTBNegotiator")
s.start()
s.wait_for_turn()
s.send_counter("Here is my offer")
s.wait_for_turn()
s.accept()
s.wait_until_done()
print(s.result)

Everything is written under a temporary HANI2_HOME unless you pass one.

TestSession

TestSession(sid: str, user: str, *, mode: str = 'main', is_admin: bool = False, admin_mode: bool = False, query: dict[str, Any] | None = None, hub: Any = None, user_agent: str = '', display_name: str | None = None)

Bases: NegotiationSession

A :class:NegotiationSession with waiting helpers.

wait_for_turn

wait_for_turn(timeout: float = 30.0) -> bool

Wait until it is the human's turn (or the negotiation ended).

play_counters

play_counters(n: int, text: str | None = None) -> None

Send n counter-offers (the current draft) as the human.

make_session

make_session(*, user: str = 'tester', mode: str = 'main', partner: str | None = 'BoulwareTBNegotiator', agent_class: str | None = None, support_settings: dict[str, Any] | None = None, scenario_type: str | None = 'Trade', n_steps: int | None = 20, time_limit: float | None = None, is_admin: bool = False, home: str | None = None, query: dict[str, Any] | None = None, load: bool = True) -> TestSession

Create a headless session (and load a scenario).

agent_class / support_settings configure the support agent for this session only (they override support_agent_settings.json).

Recordings

hani2.recording.format

The recording file format (.hrec) and its reader.

A recording is a sequence of JSON objects, one per line, gzip-compressed once the recording is finished (<name>.hrec). While it is being written it is a plain, line-flushed JSON-lines file (<name>.hrec.jsonl) so an abandoned session still loads; the reader accepts both.

Line 1 is the header::

{"k": "header", "format": "hani2-recording", "version": 1, "id": ..., "t0": <epoch s>, ...}

Every other line is an event with t (seconds since t0) and k (kind):

======== =================================================================== out a message the server sent to the browser (m: its type, seq) — state messages are stored as a full keyframe (full) or as a delta (delta) against the previous state; tool views the same way (full / delta) per tool id; any other message as msg. in a message the browser sent (msg) — every click on a button that does something arrives here. tel a batch of client telemetry (sent: client epoch ms when the batch was sent, ev: [[client epoch ms, type, ...], ...]) — mouse moves, clicks, keys, scrolls, focus, visibility, viewport, local UI state, received message sequence numbers, checkpoints. ev a semantic event (offer made, tool opened, …) — type and the fields of :func:hani2.events.log_event. act an action executed on the participant's seat (actor: human, agent or autopilot; type: offer, accept, end or text). draft the counter-offer draft changed (by: human or agent). chat a message in the assistant chat. llm one language-model call (role, model, latency, tokens, cost, the new prompt messages and the response). fn a function the support agent called (name, args, result). scenario the scenario (issues, every ufun as a utility table, reserved values) — metrics are computed from the file alone. start / trace / result / questionnaire / end. ======== ===================================================================

Deltas (:func:diff / :func:patch) map a key to {"s": value} (set), {"a": [items]} (append to a list), {"d": 1} (delete) or {"o": delta} (a nested delta).

Recording dataclass

Recording(path: Path | None, header: dict, events: list[dict], _states: list[tuple[float, int, dict]] | None = None)

A loaded recording with helpers used by the metrics and the player.

offers

offers() -> list[dict]

Offers in order: {"t", "by": "human"|"agent", "offer", "step", "text"} (from the trace when there is one, else from the actions).

telemetry

telemetry() -> list[tuple[float, str, list]]

Client telemetry as (t, type, payload) on the recording clock.

states

states() -> list[tuple[float, int, dict]]

Every state the browser received: (t, seq, state).

diff

diff(old: Any, new: Any) -> dict | None

The delta that turns dict old into dict new (None if equal).

patch

patch(old: dict, delta: dict | None) -> dict

Apply a :func:diff delta; returns a new dict (old is not changed).

read_records

read_records(path: str | Path) -> list[dict]

Every record in a recording file (a broken last line is skipped).

iter_recordings

iter_recordings(root: str | Path) -> Iterator[Path]

Every recording file under root (a file or a directory, recursively).

Evaluation

hani2.evaluation

Evaluate recorded negotiations (.hrec files) with optional metrics.

Three kinds of metrics:

  • hard — computed from the log: outcome, optimality (Pareto / Nash / Kalai–Smorodinsky distances, welfare), length, LLM usage and cost, move types and theory of mind, timing, activity, use of the assistant and tools, engagement flags, assistant interaction quality.
  • soft — judged by a language model from the transcript (opt-in).
  • subjective — the participant's questionnaire answers (UEQ, TAM, …).

Use it from Python::

from hani2.evaluation import evaluate_paths, compare_rows
rows = evaluate_paths(["results/"], metrics=["outcome", "optimality", "system_use"])
groups = compare_rows(rows, by="opponent")

or from the command line (hani2 replay evaluate) or the replay tool.

EvalContext

EvalContext(rec: Recording)

Everything metrics need, derived once from a :class:Recording.

U cached property

U: ndarray

(n_parties, n_outcomes) utilities (NaN where unknown).

two_party cached property

two_party: ndarray

(2, n_outcomes): human, opponent(s) summed.

pareto cached property

pareto: ndarray

Indices of Pareto-optimal outcomes (human vs opponent utility).

ks_point cached property

ks_point: ndarray | None

Kalai–Smorodinsky: the Pareto point that best equalises normalised gains.

turn_starts cached property

turn_starts: list[float]

Times the participant's turn began (from the screen states when a browser was connected, else the partner's offers).

utils_of

utils_of(offer: Any) -> np.ndarray | None

Every party's utility for an outcome (None if not in the table).

metric

metric(name: str, *, kind: str, title: str, columns: list[Column], description: str = '', needs_llm: bool = False, default: bool = True, version: str = '1')

Register a metric (decorator).

evaluate_recording

evaluate_recording(rec: Recording, metrics: Iterable[str] | None = None, *, use_llm: bool = False, refresh: bool = False, options: dict | None = None, key: str | None = None) -> dict

Evaluate one recording: {"row": {...}, "details": {metric: ...}, "errors": {metric: msg}}.

pass_hat_k

pass_hat_k(n: int, c: int, k: int) -> float

pass^k: the chance that k trials drawn from n (c successful) all succeed — reliability across repeated sessions (Yao et al., τ-bench).

compare_rows

compare_rows(rows: list[dict], by: str = 'opponent', columns: list[dict] | None = None, success: str = 'agreement', success_threshold: float | None = None, max_k: int = 5) -> dict

Aggregate rows by a field: per group n, mean, std and a scenario-balanced mean (average within each scenario first), plus pass^k reliability (success = success column ≥ threshold, default: a deal).

hani2.evaluation.base

Metric registry and the per-recording evaluation context.

A metric is a function fn(ctx: EvalContext, options: dict) -> dict that returns column values (and optionally "_details"). Register one with :func:metric::

from hani2.evaluation import metric, Column

@metric("my_metric", kind="hard", title="My metric",
        columns=[Column("my_value", "My value", "What it measures", higher_is_better=True)])
def my_metric(ctx, options):
    return {"my_value": len(ctx.human_offers)}

kind is hard (computed from the log), soft (judged by a language model; needs_llm=True) or subjective (from the participant's questionnaire answers).

EvalContext

EvalContext(rec: Recording)

Everything metrics need, derived once from a :class:Recording.

U cached property

U: ndarray

(n_parties, n_outcomes) utilities (NaN where unknown).

two_party cached property

two_party: ndarray

(2, n_outcomes): human, opponent(s) summed.

pareto cached property

pareto: ndarray

Indices of Pareto-optimal outcomes (human vs opponent utility).

ks_point cached property

ks_point: ndarray | None

Kalai–Smorodinsky: the Pareto point that best equalises normalised gains.

turn_starts cached property

turn_starts: list[float]

Times the participant's turn began (from the screen states when a browser was connected, else the partner's offers).

utils_of

utils_of(offer: Any) -> np.ndarray | None

Every party's utility for an outcome (None if not in the table).

metric

metric(name: str, *, kind: str, title: str, columns: list[Column], description: str = '', needs_llm: bool = False, default: bool = True, version: str = '1')

Register a metric (decorator).