> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tenetlabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Human-in-the-loop review

> Turn review verdicts into a real pause — interrupt the graph, render the review over SSE, resume on approval without re-judging.

**The HITL flow**: `review` verdict → your `on_review` callback suspends the run (`interrupt()`) → your transport renders a review event to the user → the user approves → the run resumes with the cached verdict → the callback returns `allow` and the tool proceeds.

The judge decides *what needs a human*; you own *how the human answers*. The middleware deliberately ships no transport — the same verdict round-trips through SSE, WebSocket, or an approval queue. This guide shows the full LangGraph + SSE wiring.

## When to use it

Wire HITL when a `review` verdict should stop the agent in a user-facing harness — the recruiter sees why, and decides. Skip it for background/batch judging: the default `on_review` (soft-allow + `tenet_review` metadata marker) keeps the run moving while your audit trail records the flag. Don't confuse the two — without an `interrupt()`-based callback, **nothing pauses**.

## Requirements

* **A checkpointer.** `interrupt()` persists graph state and raises; resume replays from the checkpoint. In-memory checkpointers lose paused turns on restart — don't ship one to multi-worker production.
* **A stable `thread_id`.** The resume request must carry the same `thread_id` as the paused turn, or LangGraph starts a fresh thread and the pause is orphaned.

## The callbacks

```python theme={null}
# Python — on_review pauses and allows on resume; on_block pauses and
# refuses on resume (a block has no approve path).
from langgraph.types import interrupt
from tenet_client import JudgeAction, JudgeContext, JudgePolicy, JudgeVerdict
from tenet_langchain import format_review_event

def _payload(ctx: JudgeContext, verdict: JudgeVerdict) -> dict:
    # Whatever you pass to interrupt() is what your streaming layer
    # receives — shape it as your UI's wire contract.
    event = format_review_event(
        verdict,
        tool_name=ctx.tool_name or None,
        tool_args=ctx.tool_input if ctx.phase in ("tool_pre", "tool_post") else None,
    )
    return event.to_dict()

def on_review(ctx: JudgeContext, verdict: JudgeVerdict) -> JudgeAction:
    interrupt(_payload(ctx, verdict))
    # interrupt() raises on the first pass and returns on resume —
    # reaching this line means the human approved.
    return JudgeAction.allow()

def on_block(ctx: JudgeContext, verdict: JudgeVerdict) -> JudgeAction:
    interrupt(_payload(ctx, verdict))
    # Resume after a block can only mean "dismissed" — halt cleanly
    # with a message the model and user can read.
    return JudgeAction.tool_error(verdict.reason or "Blocked by Tenet compliance judge.")

policy = JudgePolicy(on_review=on_review, on_block=on_block)
```

Keep the callbacks synchronous and transport-free — `interrupt()` is the only side effect. Rendering, alternatives generation, and anything async belongs in the streaming layer that catches the interrupt.

## What you can read at interrupt time

The callback's `JudgeContext` carries the phase, tool, and — in streaming mode — fields the middleware folds onto `ctx.metadata` from the judge's SSE body:

| `ctx.metadata` key | Contents |
| - | - |
| `tenet_safe_message` | Reserved — the current judge doesn't populate it |
| `tenet_explanation` | Reserved — the current judge doesn't populate it |
| `tenet_rewrite` | Reserved — the current judge doesn't populate it |
| `tenet_canonical_id` | 32-hex correlation key for this judge call, the same value as `decision_id` — log it and quote it to Tenet support when you report a decision |

> [!WARNING]
>
> These keys are populated **after the judge's stream completes**. With `stream=True` the middleware reads the stream through to `done` and then dispatches your callback once, on the complete response, so `tenet_canonical_id` is there at interrupt time. Still read every key with `.get()`: the reserved keys are absent today, and the sync path (`stream=False`) folds none of them. The SDK DEBUG-logs the canonical ID on every path.

## What the user sees

A review pause from start to finish. A recruiting agent receives "Can you find candidates who graduated after 2020?" (a graduation-year age proxy):

![Agent paused on a flagged request. The message reads: This request was flagged for review. Continue only if you've verified it complies with hiring policy. Below it, suggested compliant rewrites — find candidates with up to two years of relevant experience; find candidates holding a bachelor's degree in the required field; find candidates with required certifications and less than three years experience — and a 'continue anyway' link reading: I'll flag it on the result.](https://mintcdn.com/tenetlabs/f83ct0NG_FFBa-fQ/images/hitl-review.png?fit=max\&auto=format\&n=f83ct0NG_FFBa-fQ\&q=85\&s=262328c6b7bd134c4f31b04e9ea6fdaa)

A review interrupt rendered in a recruiting agent: the judge's display\_message, app-generated lawful rewrites, and the approve path.

Every element maps to a piece of this guide:

* **"paused"** — the `on_review` callback called `interrupt()`; the graph is checkpointed, awaiting resume.
* **The flagged-for-review copy** — `display_message` from `RiskLabelDisplay`, rendered verbatim (here the guaranteed-non-empty generic fallback).
* **The rewrite suggestions** — app-side lawful alternatives carried in the event's `extras`; the SDK ships the pause, the app owns the rewrites.
* **"continue anyway"** — the `proceed` choice. On resume the callback returns `JudgeAction.allow()`, and with `turn_approval=True` the approved risk labels don't re-prompt this turn.
* **"I'll flag it on the result"** — Tenet's [verdict trace](https://docs.tenetlabs.com/concepts/traces.md) holds the verdict, not the reviewer's decision. Record the approval in your own logs next to `decision_id`.

## Rendering the review over SSE

`format_review_event(verdict, ...)` builds a `ReviewEvent` — a transport-ready record with user-facing copy, operator detail, and default UI choices. The middleware never calls it; your app does, wherever it converts the interrupt payload into wire frames:

```python theme={null}
# Python — inside the loop that streams agent events to the client.
# astream_events surfaces the interrupt; forward it as an SSE frame.
event = format_review_event(verdict, tool_name=tool_name, tool_args=tool_args)
yield event.to_sse()
# → event: tenet_review
#   data: {"action":"review","display_message":"This request raised a
#          possible age-discrimination concern.","risk_labels":["EEO-AGE-PROXY-01"],
#          "severity":"high","choices":[{"id":"proceed","label":"Continue anyway"},
#          {"id":"reject","label":"Cancel"}], ...}
```

What the event carries:

* `type` / `action` — `tenet_review` (approve or cancel) vs. `tenet_block` (dismiss-only). Your frontend branches on this: reviews get a "Continue anyway" path, blocks don't.
* `display_message` — guaranteed non-empty, compliance-safe copy built from the risk labels. Show it verbatim.
* `risk_labels` — raw engine codes (`EEO-AGE-PROXY-01`) for telemetry and filtering; not for end users.
* `choices` — default review choices are `proceed` / `reject`; blocks get `dismiss` only. Override per-app.
* `extras` — free-form dict for app-side additions (e.g., LLM-generated lawful rewrites as suggestion chips — kept app-side so the SDK ships no LLM dependency).

### Translating risk labels for humans

`RiskLabelDisplay` is the single source of the code → topic vocabulary, so your UI never re-derives (and drifts from) the compliance language:

```python theme={null}
from tenet_langchain import RiskLabelDisplay, DEFAULT_EEO_TOPIC_MAPPING

display = RiskLabelDisplay()                      # EEO mapping by default
display.topic_for("EEO-AGE-PROXY-01")             # → "age-discrimination"
display.topic_for("EEO-UNMAPPED-01")              # → None — unmapped codes drop out
display.display_message(["EEO-AGE-PROXY-01"], action="review")
# → "This request raised a possible age-discrimination concern."
```

Pass a custom mapping to the constructor to swap vocabularies (healthcare topics, localized copy). `format_review_event(display=...)` accepts the same instance.

## Resume semantics

The middleware caches the judge response **before** dispatching your callback — `interrupt()` raises a `GraphInterrupt` straight through the tool boundary, and on the resume pass the cached verdict is reused instead of re-judging. You pay one judge call per human decision, not two.

With `turn_approval=True`, an approved review does double duty: the middleware records what was approved — the verdict's `rule_ids`, or its `risk_labels` when no finding carries a rule id — and any later call in the same turn whose identifiers are a subset auto-allows (`tenet_turn_approved: True` in the action metadata). One "Continue anyway" covers the follow-up tool calls it implies, instead of re-prompting the user per call. A later verdict carrying neither `rule_ids` nor `risk_labels` always re-prompts, so an approval can't cover a finding the reviewer never saw.

On the resume request itself: route it to the same agent with the same `thread_id`, passing the resume value LangGraph expects (`Command(resume=...)`).

> [!NOTE]
>
> LangGraph treats falsy resume payloads (`{}`, `None`, `[]`) as "no resume queued" — `interrupt()` fires again instead of returning. If your UI's approve action carries no data, coerce the resume value to something truthy (e.g. `True`) before resuming.

## Gotchas

* **No checkpointer, no HITL.** Without one, `interrupt()` has nowhere to persist the paused state. This is the first thing to check when resume "starts over."
* **Approve ≠ policy change.** A resume approves *this* decision (and, with `turn_approval`, its subset repeats this turn). The same request in a new turn judges fresh.
* **Don't put async work in the callback.** Alternatives generation, DB writes, notifications — all of it belongs after the interrupt surfaces in your streaming layer, where you're in an async context and a failure can fail open (cosmetics) without weakening the gate.

## Links

* [Policies — the full action vocabulary](https://docs.tenetlabs.com/guides/policies.md)
* [LangChain middleware — `turn_approval`, `cache_verdicts`](https://docs.tenetlabs.com/guides/langchain)
* [Verdict-first streaming — the event order](https://docs.tenetlabs.com/guides/streaming.md)
* [tenet-langchain reference — `ReviewEvent`, `RiskLabelDisplay`](https://docs.tenetlabs.com/sdk/tenet-langchain)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.