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 ¶
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
¶
Whether this participant may see the opponent's utilities: admins
always; everyone when env.json → tools.show_opponent_utility is true.
view_lock
property
¶
Held while the tool is rendered or read by a support agent, so the
two never run :meth:view at the same time.
context ¶
The live negotiation snapshot (same dict the support agent sees).
set_offer ¶
Fill the human's counter-offer draft (does not send it).
describe_for_agent ¶
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.
scenario_loaded ¶
Called after a scenario is loaded.
negotiation_started ¶
Called when the negotiation starts.
negotiation_ended ¶
Called when the negotiation ends.
action_requested ¶
Called whenever it becomes the human's turn.
action_to_execute ¶
Called just before the human's action is executed.
action_executed ¶
Called after the human's action is executed.
view ¶
Return the tool's UI as a list of :mod:hani2.tools.ui components.
on_input ¶
An input component changed. Default: store it and re-render.
on_action ¶
A button was clicked or a table row selected.
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 aname. When the user changes one, the tool's :meth:~hani2.tools.Tool.on_inputis called with(name, value). The default implementation stores the value inself.values[name]and re-renders. - Buttons carry an
action. Clicking calls :meth:~hani2.tools.Tool.on_actionwith(action, payload)wherepayloadis the button'spayloadplus the current values of all inputs. - Tables may set
on_select=<action>; clicking a row callson_actionwithpayload={"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)}")
markdown ¶
Markdown (GitHub flavoured; tables supported). size: sm | md | lg.
alert ¶
kind: info | success | warning | error | neutral (markdown text).
progress ¶
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 ¶
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 ¶
A segmented control.
grid ¶
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 ¶
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 fn atomically with respect to the interface state and return its result.
context ¶
The live negotiation snapshot (issues, offers, utilities, history…).
toast ¶
A pop-up notification (needs the toast capability; falls back to chat).
show_on_board ¶
Write markdown to the always-visible status board.
message_user ¶
Tell the human something right now: chat, toast or board.
ask_user ¶
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 ¶
Attach a note to an element; text=None removes it. Needs annotate.
set_layout ¶
view (full | simple | focus), collapsed, sizes. Needs layout.
show_panel ¶
Show a panel built from :mod:hani2.tools.ui components. Buttons and
table selections in it call :meth:on_panel_action. Needs panels.
toolbox ¶
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 ¶
[{name, description, pane}] of the tools :meth:add_tool accepts by name.
add_tool ¶
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 a tool that was added during the session. Needs tool_add.
read_tool ¶
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 ¶
The human sent a chat message (runs in a worker thread).
on_draft_changed ¶
The human edited the counter-offer. Default: the reserved-value warning.
warn_if_draft_below_reserved ¶
Warn (once until fixed) when the draft is worth less than the reserved value.
on_event ¶
A negotiation lifecycle event: negotiation_started,
action_requested or negotiation_ended.
proactive_note ¶
The system note that seeds a proactive turn (None = stay silent).
on_panel_action ¶
A button in one of your panels was clicked. Default: tell the LLM.
autopilot_step ¶
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 ¶
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 ¶
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 module:Class, module.Class or path/to/file.py:Class.
resolve_agent_class ¶
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 ¶
register_extra_tools ¶
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 ¶
Convenience for subclasses to register a custom tool.
make_function_schema ¶
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 ¶
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.
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.
diff ¶
The delta that turns dict old into dict new (None if equal).
patch ¶
Apply a :func:diff delta; returns a new dict (old is not changed).
read_records ¶
Every record in a recording file (a broken last line is skipped).
iter_recordings ¶
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 ¶
Everything metrics need, derived once from a :class:Recording.
pareto
cached
property
¶
Indices of Pareto-optimal outcomes (human vs opponent utility).
ks_point
cached
property
¶
Kalai–Smorodinsky: the Pareto point that best equalises normalised gains.
turn_starts
cached
property
¶
Times the participant's turn began (from the screen states when a browser was connected, else the partner's offers).
utils_of ¶
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^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 ¶
Everything metrics need, derived once from a :class:Recording.
pareto
cached
property
¶
Indices of Pareto-optimal outcomes (human vs opponent utility).
ks_point
cached
property
¶
Kalai–Smorodinsky: the Pareto point that best equalises normalised gains.
turn_starts
cached
property
¶
Times the participant's turn began (from the screen states when a browser was connected, else the partner's offers).
utils_of ¶
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).