> ## 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.

# LangChain middleware

> TenetJudgeMiddleware gates every tool call in a create_agent loop — one constructor argument, fail-closed defaults.

**`TenetJudgeMiddleware`**: a LangChain `AgentMiddleware` that intercepts `wrap_tool_call` → judges `tool_pre` and `tool_post` → applies your policy's action. If you build with `create_agent`, this is the integration — don't hand-roll callback plumbing.

If your harness isn't LangChain, use the [`@judged` decorator or direct client](https://docs.tenetlabs.com/guides/framework-free) instead.

## Setup

```python theme={null}
# Python — adapt model and tools to your agent.
from langchain.agents import create_agent
from tenet_client import TenetCloudJudgeClient
from tenet_langchain import TenetJudgeMiddleware

judge = TenetCloudJudgeClient.from_env()  # TENET_API_KEY (or TENET_CLIENT_ID / TENET_CLIENT_SECRET)
judge.warmup()

agent = create_agent(
    model="claude-sonnet-4-6",
    tools=[search_resumes, draft_outreach, send_email],
    middleware=[TenetJudgeMiddleware(judge)],
)
```

Defaults: every tool judged at `tool_pre` and `tool_post`, fail-closed policy (block → tool error with the judge's safe message, judge unreachable → raise). Both sync and async agent runs are supported — the middleware implements `wrap_tool_call` and `awrap_tool_call`.

## Where guardrails run

LangChain middleware exposes hooks across the whole agent lifecycle — guardrails can sit at any of them. The [LangChain guardrails guide](https://docs.langchain.com/oss/python/langchain/guardrails) frames the two outer placements: `before_agent` to "validate requests once at the start of each invocation," `after_agent` to "validate final outputs once before returning to the user."

![LangChain middleware execution order: request → before\_agent → before\_model → wrap\_model\_call / wrap\_tool\_call → after\_model → after\_agent → result](https://mintcdn.com/tenetlabs/f83ct0NG_FFBa-fQ/images/langchain-middleware.webp?fit=max\&auto=format\&n=f83ct0NG_FFBa-fQ\&q=85\&s=4284615f162f929ff16f77bcfef0c6e5)

LangChain's middleware lifecycle — hooks where guardrails can run. Diagram from the LangChain docs.

How `TenetJudgeMiddleware` maps onto those hooks:

| Placement | LangChain hook | Tenet coverage |
| - | - | - |
| User request enters | `before_agent` | `check_user_messages=True` → `agent_input` phase |
| Before/after each model call | `before_model` / `after_model` / `wrap_model_call` | Not judged — raw model I/O is the model provider's safety layer |
| Tool boundary | `wrap_tool_call` | `tool_pre` + `tool_post` — the middleware's default |
| Final output returns | `after_agent` | `agent_output` phase via the [direct client](https://docs.tenetlabs.com/guides/framework-free.md) |

The judge concentrates on the **tool boundary** — the placement LangChain's own guide doesn't cover — because that's where agent risk becomes action: a discriminatory search executes, an email sends. Input and output checks catch what users *ask* and what agents *say*; `wrap_tool_call` catches what agents *do*, and it's the only hook that can stop a side effect before it happens.

One placement is deliberately absent from the table: the judge as a model-callable *tool*. Don't build that — a model can choose not to call a tool, and a guardrail the model can skip is not a guardrail. Middleware runs unconditionally; that's the point of it.

LangChain's guide also distinguishes deterministic guardrails (regex, keyword — "fast, predictable… but may miss nuanced violations") from model-based ones ("catch subtle issues that rules miss, but are slower and more expensive"). You don't pick one with Tenet: the judge layers both behind a single verdict — deterministic [guards](https://docs.tenetlabs.com/concepts/decisions.md#guards) first, with no model call, then one judge model call, backed by an escalate-only risk screener. Build additional harness-specific middleware (rate limits, PII scrubbing) alongside it; multiple middlewares compose in list order.

## What the agent sees on a block

A blocked call doesn't crash the run. The middleware converts it to a tool error carrying the verdict's reason (the finding's evidence), so the model reads *why* it was blocked and self-corrects — typically by re-asking the user or reformulating the call. After `retry_nudge_max_consecutive` (default 3) consecutive nudges on the same violation, it escalates to a hard tool error to prevent loops.

## Options

```python theme={null}
TenetJudgeMiddleware(
    judge,
    policy=my_policy,                # verdict → action mapping; see Policies guide
    check_pre=True,                  # judge tool args before execution
    check_post=True,                 # judge tool output after execution
    check_user_messages=False,       # also judge user input (agent_input phase)
    judge_tools_pre=None,            # allowlist; None = all tools
    judge_tools_post=None,
    cache_verdicts=False,            # reuse verdicts for identical calls within a thread
    turn_approval=False,             # user-approved risk labels persist for the turn
    stream=False,                    # verdict-first SSE; see Streaming guide
    send_history=False,              # send prior user turns for multi-turn context
    session_id=None,                 # conversation ID; auto-uses thread_id with a checkpointer
    resolution_detection=True,       # classify tool output as resolved/unresolved
    retry_nudge_max_consecutive=3,   # nudges before escalating to hard error
)
```

The levers that matter:

* **`check_user_messages=True`** — turn on when end users type free-form requests. A recruiter asking "find me candidates under 30" should be caught at `agent_input`, before the agent plans a single tool call.
* **`judge_tools_pre` / `judge_tools_post`** — scope judging to side-effectful tools if you need to shave latency. Read-only lookups are cheap to judge — measure `latency_ms` before you exclude them.
* **`send_history=True` + `session_id`** — multi-turn context. "Ones who can start now" is benign alone; after "find recent grads" it may not be. Without history, the judge sees each turn cold.
* **`cache_verdicts=True`** — dedupe identical tool calls within a thread. Safe for deterministic tools; skip it if tool args embed timestamps.
* **`turn_approval=True`** — when a human approves a `review` verdict, the approved risk labels don't re-trigger for the rest of that turn. Pair with an `interrupt()`-based `on_review` — see [Human in the loop](https://docs.tenetlabs.com/guides/policies.md#human-in-the-loop).

> [!NOTE]
>
> `session_id` groups evaluations into one conversation trace. If your agent uses a LangGraph checkpointer, the middleware picks up `thread_id` automatically — set `session_id` only to override.

## With a custom policy

```python theme={null}
from tenet_client import JudgePolicy, JudgeAction

policy = JudgePolicy(
    # block → tool error the model can read and recover from
    on_block=lambda ctx, v: JudgeAction.tool_error(v.safe_message or "Blocked by compliance."),
    # review → actually pause for a human. human_review() alone does NOT
    # pause — the callback must suspend the run (LangGraph interrupt()).
    on_review=on_review_pause,  # see Policies → "Human in the loop"
    # judge down → fail closed for write tools, open for reads
    on_unavailable=lambda ctx, err: (
        JudgeAction.allow() if ctx.tool_name in READ_ONLY_TOOLS
        else JudgeAction.raise_error(err)
    ),
)

agent = create_agent(
    model="claude-sonnet-4-6",
    tools=tools,
    middleware=[TenetJudgeMiddleware(judge, policy=policy)],
)
```

Full action vocabulary (`retry_nudge`, `override_output`, …) in [Policies](https://docs.tenetlabs.com/guides/policies.md).

## Gotchas

* **The middleware judges every tool under the client's [`surface`](https://docs.tenetlabs.com/concepts/surfaces)** — there's no per-tool override today. Fine when the agent does one kind of recruiting action; an agent whose tools span screening, drafting, ranking, and outreach should not judge them all as `resume_triage`. Run one scoped middleware per action family (`judge_tools_pre=` / `judge_tools_post=` allowlists, one client per surface, all constructed at startup — middlewares compose in list order), or gate mixed tools at a dispatch choke point with the [direct client](https://docs.tenetlabs.com/guides/framework-free.md) and `surface=` per call.
* **Construct the client once, at process start** — `TenetCloudJudgeClient` holds the token cache and HTTP connection pool. Per-request construction re-mints tokens and re-handshakes TLS.
* **Middleware order matters** — put `TenetJudgeMiddleware` last in the list so it judges the final tool call, after any middleware that rewrites arguments.
* **`tenet-langchain` requires `langchain>=1.2.13`** — the `AgentMiddleware` API it implements doesn't exist in older releases.

## Links

* [Surfaces — one per recruiting action, not per agent](https://docs.tenetlabs.com/concepts/surfaces.md)
* [Policies](https://docs.tenetlabs.com/guides/policies.md)
* [Human-in-the-loop review](https://docs.tenetlabs.com/guides/hitl.md)
* [Streaming](https://docs.tenetlabs.com/guides/streaming.md)
* [tenet-langchain reference](https://docs.tenetlabs.com/sdk/tenet-langchain.md)
* [Framework-free integration](https://docs.tenetlabs.com/guides/framework-free.md)

| Integration | Shape | Use when |
| - | - | - |
| `TenetJudgeMiddleware` | LangChain `AgentMiddleware` | `create_agent` harnesses — this page |
| [`@judged`](https://docs.tenetlabs.com/guides/framework-free) | Python decorator | Any Python function, no framework |
| [HTTP API](https://docs.tenetlabs.com/api-reference/introduction.md) | REST + SSE | Non-Python harnesses |


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