Metadata-Version: 2.5
Name: tenet-client
Version: 0.7.7
Summary: Tenet SDK — cloud judge client and local server client. Framework-agnostic.
Project-URL: Homepage, https://tenetlabs.com
Project-URL: Documentation, https://docs.tenetlabs.com/sdk/tenet-client
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: compliance,governance,judge,pii,redaction
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Requires-Python: <3.14,>=3.11
Requires-Dist: httpx>=0.24.0
Requires-Dist: pydantic>=2.0
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: ruff==0.15.12; extra == 'dev'
Description-Content-Type: text/markdown

# tenet-client

Pure-Python SDK for the Tenet cloud judge service and local Tenet server. No
framework dependencies — works inside LangChain, LlamaIndex, FastAPI,
plain scripts, anywhere.

For LangChain-specific middleware/callback adapters, install
[`tenet-langchain`](../tenet-langchain) instead — it depends on this
package and ships the LangChain integration classes.

## What's new in 0.7.7

- [`user_prompt=` and `candidate_content=`](#the-users-ask-user_prompt-and-candidate_content):
  the user's ask and candidate text as first-class arguments.
- [`decision_id` on the verdict and `is_degraded`](#support-correlation--decision_id--canonical_id),
  and [`on_timeout` dispatch](#failure-handling-timeouts-and-on_timeout).
- [Wall-clock `deadline` and `CircuitBreaker`](#deadlines-and-outages), including
  `record_breaker=False` for observing calls.
- [`check()`](#check-a-piece-of-text) and
  [per-finding `classify_findings`](#decide-per-finding).
- [Decision records and sinks](#record-every-decision).
- [`tenet_client.testing`](#testing-your-integration): a mock judge for your tests.

## Install

```bash
pip install tenet-client
```

## Quickstart — cloud judge

The cloud judge runs at `https://judge.tenetlabs.com/decide`.
Your customer credentials (M2M `client_id` / `client_secret`) are issued
by Tenet at provisioning time.

```python
from tenet_client import TenetCloudJudgeClient, JudgeUnavailableError

client = TenetCloudJudgeClient(
    client_id="<your-m2m-client-id>",
    client_secret="<your-m2m-client-secret>",
)

# Recommended: warm the client at process start so the first user-facing
# call doesn't pay the Auth0 token-mint cold path.
client.warmup()

try:
    verdict = client.evaluate(
        phase="tool_pre",
        tool_name="search_resumes",
        tool_input={"query": "5+ years Python experience"},
    )
    if verdict.decision == "block":
        # Integrator decides what to do — return an error to the agent,
        # surface a safe message to the user, log + halt, etc.
        ...
except JudgeUnavailableError as e:
    # Cloud judge unreachable. The SDK does NOT have a fail_open flag —
    # it's a policy decision. Catch and either retry, halt, or proceed
    # depending on your environment.
    ...
```

Or read credentials from env. `from_env()` requires `TENET_CLIENT_ID`
and `TENET_CLIENT_SECRET`; optional tuning vars are `TENET_JUDGE_ID`,
`TENET_JUDGE_TIMEOUT_SECONDS`, and `TENET_WORKFLOW` (see
[Workflow label](#workflow-label)). (`TENET_CLOUD_URL`, `TENET_AUTH0_AUDIENCE`,
and `TENET_AUTH0_ISSUER_URL` exist as escape hatches for dev / staging
but should not be set in production.)

```python
client = TenetCloudJudgeClient.from_env()
```

## Async

Every method has an `_async` counterpart:

```python
from contextlib import asynccontextmanager
from fastapi import FastAPI
from tenet_client import TenetCloudJudgeClient


@asynccontextmanager
async def lifespan(app: FastAPI):
    app.state.judge = TenetCloudJudgeClient.from_env()
    await app.state.judge.warmup_async()
    yield
    await app.state.judge.aclose()


app = FastAPI(lifespan=lifespan)


@app.post("/run-tool")
async def run_tool(req: ...):
    verdict = await app.state.judge.evaluate_async(
        phase="tool_pre", tool_name=..., tool_input=...,
    )
    ...
```

## Reading multi-verdict responses

The judge returns a per-domain `findings` list alongside the top-level
verdict. Simple callers can keep reading just the top level; callers who
need to dispatch on a specific domain (EEO, disclosure, prompt
injection, ...) read `findings`.

```python
verdict = client.evaluate(phase="tool_pre", tool_input={"q": "..."})

# 1) Top-level still works. Backwards-compat is a guarantee: existing
#    code reading `verdict.verdict` / `verdict.decision` keeps working.
if verdict.verdict == "route_to_human":
    ...

# 2) Per-domain detail — the EEO finding is always present (the engine
#    synthesizes one from the top-level on legacy responses).
eeo = verdict.eeo_finding
print(eeo.verdict, eeo.severity, eeo.rule_ids, eeo.evidence_span)

# Index by name when you care about a specific domain.
disclosure = verdict.findings_by_domain.get("disclosure")
if disclosure is not None:
    ...

# Convenience helpers read well in agent code.
if verdict.blocked_by_domain("eeo"):
    return safe_message
span = verdict.evidence_for("eeo")  # str | None
```

### Audit-only vs enforce

Every finding carries an `enforcement` field:

- **enforce** — this finding's verdict participated in the merged
  top-level verdict (`most-restrictive-wins` across all enforcing
  findings).
- **audit_only** — wire-visible for observability but never gates the
  top-level verdict. A new domain ships in audit-only until its
  promotion gate; an audit-only `block` does *not* block the caller.

`verdict.enforcing_findings` and `verdict.audit_only_findings`
partition the list. `blocked_by_domain(name)` returns `True` only for
an *enforcing* blocking finding — audit-only blockers return `False`
on purpose; that's the semantic difference.

### Which domains exist today

- **EEO** — live, `enforce`. Always `findings[0]`. Genuine EEO signals
  stay on `domain="eeo"`.
- **safety** — live. Deterministic safety guards (prompt injection +
  exfil detection) are attributed to `domain="safety"`. This finding
  carries a nested `sub_findings` list breaking the block down per
  detector — each `SubFinding` names its `sub_domain` (`"injection"` /
  `"exfil"`), the `rule_ids` that fired (e.g. `["SAFETY-EXFIL-01"]`),
  its `verdict`, and `enforcement`:

  ```python
  safety = verdict.findings_by_domain.get("safety")
  if safety is not None:
      for sf in safety.sub_findings:
          print(sf.sub_domain, sf.rule_ids, sf.verdict, sf.enforcement)
  ```

- Additional domains (disclosure, ...) append to `findings` as they
  ship, each starting in `audit_only` and graduating to `enforce` per
  its promotion gate.

Out-of-vocab verdicts normalize to `route_to_human` for the merged
top-level value; the per-finding `verdict` is preserved verbatim so an
audit can reconstruct what each detector actually returned.

## Streaming (verdict-first)

The judge exposes an SSE surface that emits the verdict ~4× sooner than the
full response. Two opt-in paths:

```python
judge = TenetCloudJudgeClient.from_env()  # or use_stream=True / TENET_USE_STREAM=1


async def decide(prompt: dict):
    # 1. Drop-in: route through the stream, identical return type.
    verdict = await judge.evaluate_stream_to_response(
        phase="tool_pre", tool_input=prompt
    )

    # 2. Verdict-first: act on the verdict event before the body streams in.
    async for event in judge.evaluate_stream(phase="tool_pre", tool_input=prompt):
        if event.event_type == "verdict":
            ...  # dispatch your routing decision at ~TTV

    return verdict
```

Streaming is async-only; the sync `evaluate()` stays on the non-streaming
route. The aggregated response additionally carries `canonical_id`,
`client_action`, `safe_message`, `explanation`, and `rewrite`.

When a per-domain finding tightens the merged verdict after the initial
`verdict` event, the server emits `verdict_revised` carrying the same
shape plus a `domain` field identifying which finding drove the
revision. The aggregator takes the latest revision as terminal; verdict-
first consumers can either ignore `verdict_revised` (act at the first
`verdict`) or re-dispatch on it. The `domain` key may be absent on
older deployments — tolerate it.

## Multi-turn history

Pass prior **recruiter** turns so the stateless judge sees the conversation
context (oldest first); they become extra `{"role": "user"}` messages ahead of
the latest turn. Never send assistant turns.

```python
async def decide_with_history(judge):
    return await judge.evaluate_async(
        phase="agent_input",
        tool_input="now only the recent grads",
        prior_user_turns=["find backend engineers", "ones who can start now"],
    )
```

## The user's ask: `user_prompt=` and `candidate_content=`

At a tool phase, pass what the user asked separately from the tool's arguments.
The judge reads the ask from `user_prompt=`; the arguments stay in `tool_input`:

```python
verdict = judge.evaluate(
    phase="tool_pre",
    tool_name="update_stage",
    tool_input={"candidate_id": "c-7", "stage": "rejected"},
    context={},
    user_prompt="Reject Pam",
)
```

`candidate_content=` is text written by the person the decision is about (never
the agent's reply, which is `agent_reply=`). Passing a different value than a
`recruiter_prompt` / `candidate_content` key inside `tool_input` raises
`ValueError`. See `docs/integration_contract.md` section 8.

## Session grouping

Pass a `session_id` — a conversation id — so the server groups every judge call
in one conversation into one session in Tenet's decision traces. Use
a stable id per conversation (e.g. your LangGraph `thread_id`):

```python
async def decide_in_conversation(judge, conversation_id: str):
    return await judge.evaluate_async(
        phase="agent_input",
        tool_input="now only the recent grads",
        session_id=conversation_id,
    )
```

The server tenant-namespaces and length-caps the id, so send it raw; omit it
(don't send empty) for an ungrouped, standalone trace. Works on the sync,
async, and streaming paths.

## Workflow label

If several of your integrations call the judge (e.g. a batch `apply-summary`
job and a `recruiter-agent` chat agent), name each one with `workflow` so the
Tenet traces page can filter per workflow instead of mixing them together. Set
it once on the client (or via `TENET_WORKFLOW`) and override per call if one
client serves several workflows:

```python
judge = TenetCloudJudgeClient.from_env()  # TENET_WORKFLOW=apply-summary
judge.evaluate(phase="agent_input", tool_input="...", workflow="recruiter-agent")
```

It is a trace label only: it never affects the verdict and is unrelated to
`surface`. Use a lowercase slug (letters, digits, `.`, `_`, `-`; at most 64
chars). Anything else raises `ValueError` at construction or call time, before
any request is sent. Omit it and the call is recorded as unlabeled.

## Support correlation — `decision_id` / `canonical_id`

Every response carries `resp.decision_id` (0.7.0+) — the engine's 32-hex key
for that one decision, on both the non-streaming (`evaluate`,
`evaluate_async`) and streaming paths. Quote it when reporting a specific
decision to Tenet:

```python
resp = judge.evaluate(phase="tool_post", tool_output=summary)
log.info("tenet decision", extra={"decision_id": resp.decision_id})
```

It is read from the `/decide` body's `decision_id`, falling back to the
`X-Tenet-Canonical-Id` response header; it is `None` only against an older
server that sends neither. Streamed decisions also carry the same value as
`canonical_id`. Log it on every call; never show it to the end user.

Policy callbacks receive a `JudgeVerdict`, not the response, so the verdict
carries the same keys: `verdict.decision_id` and `verdict.canonical_id`
(`None` when the engine sent none). Log `verdict.decision_id` from
`on_block` / `on_review` and you have the id support asks for.

### Did the judge actually judge? `is_degraded`

When the engine cannot reason about the content (for example a tripped
breaker answers `route_to_human`), the response says so with `degraded` or
`route_reason == "infra_degraded"`. `resp.is_degraded` and
`verdict.is_degraded` fold both into one check. Treat a degraded answer as
"no answer", not as a finding about the content.

### Failure handling: timeouts and `on_timeout`

A timeout raises `JudgeTimeoutError`, a subclass of `JudgeUnavailableError`,
so existing `except JudgeUnavailableError` blocks keep working. With
`evaluate_phase` / `evaluate_phase_async` (and `@judged` given a `policy`),
a timeout reaches `JudgePolicy.on_timeout` and every other judge failure
reaches `on_unavailable`. If you never set `on_timeout`, timeouts go to
`on_unavailable`, so failing open with only `on_unavailable=...` still
covers timeouts. Set `on_timeout` only when timeouts need different
behaviour.

`judge.workflow` and `judge.judge_id` expose the client's configuration
read-only.

## Deadlines and outages

`timeout` bounds each HTTP operation (the token mint, the request, each stream
read), so one call can take about twice that or more. `deadline` bounds the
whole call in wall-clock seconds: set it on the client (`deadline=2.0`, or
`TENET_JUDGE_DEADLINE_SECONDS`) or per call (`judge.evaluate(..., deadline=1.0)`;
the per-call value wins). Exceeding it raises `JudgeTimeoutError`, so it reaches
`on_timeout`. On `evaluate_stream` the deadline runs from the first call to
exhaustion, but only the client's own waits are bounded: a consumer that is slow
between events is never cancelled, and the next read raises. Unset means no
deadline.

A `CircuitBreaker` makes a sustained outage cost one probe per cooldown instead
of a full timeout per call:

```python
from tenet_client import CircuitBreaker, JudgeAction, JudgePolicy, TenetCloudJudgeClient

judge = TenetCloudJudgeClient(
    api_key="sk_tenet_...",
    deadline=2.0,
    breaker=CircuitBreaker(failure_threshold=3, cooldown_s=60.0),
)
policy = JudgePolicy(on_unavailable=lambda ctx, err: JudgeAction.allow())  # fail open
verdict, action = judge.evaluate_phase(policy=policy, phase="agent_input", tool_input="...")
```

After three consecutive failures the breaker opens and calls raise
`JudgeCircuitOpenError` (a `JudgeUnavailableError`, so `on_unavailable` handles
it) without touching the network. After the cooldown one call is let through as
a probe; its success closes the breaker, its failure reopens it. A timeout, a
5xx, a 408 or 429, or a network error counts as a failure, and so does a response with `is_degraded`, which is
still returned to you. A timeout from a per-call `deadline` shorter than the
client's own says nothing about the judge and is not counted. The breaker is
process-local; one instance can be shared by several clients to trip them
together.

An HTTP 4xx other than 408 and 429 (a malformed request, a rejected key) is a
bug on your side, not a sick judge, so it neither opens the breaker nor closes
it; a probe that ends that way frees the slot and the breaker stays open for the
next probe. `JudgeUnavailableError.status_code` carries the HTTP status when
there was one. If the stream's verdict already arrived, a deadline that expires
afterwards still raises `JudgeTimeoutError` but is not counted as a failure.

Calls that only observe (a shadow check next to enforcing calls on the same
client) pass `record_breaker=False`: they reach the network only while the
breaker is closed, are rejected with `JudgeCircuitOpenError` while it is open or
half-open (they never take the probe slot), and record neither a success nor a
failure, so a fault seen only by observers cannot fail a real call.

## Check a piece of text

`check()` judges one phase and returns a `JudgeOutcome` instead of raising. It
is for code that just needs "may I send this?":

```python
from tenet_client import VerdictCache

cache = VerdictCache()  # share one so a resumed tool does not pay twice
out = client.check(
    phase="tool_pre",
    tool_name="send_email",
    tool_input={"body": draft},
    context={},
    session_id=thread_id,
    fail_mode="closed",     # or "open": an outage may proceed
    cache=cache,
)
if out.proceeds:            # allow, or unavailable under fail_mode="open"
    send(draft, note=out.caveat)
elif out.kind == "review":  # ask a human; out.reason and out.rule_ids say why
    ...
else:                       # "block", or "unavailable" while failing closed
    ...
```

Any judge failure (timeout, open breaker, HTTP error, anything unexpected)
becomes `kind="unavailable"`; a wrong argument still raises. If the engine
answers without judging (`out.degraded`), the default treats it as unavailable
so `fail_mode` applies. Pass `degraded_as="verdict"` to map the engine's
fallback verdict instead, usually `review`, which asks a human rather than
sending unreviewed (open) or refusing with no override (closed). Degraded and
unavailable outcomes are never cached. `check_async` is the async twin.

## Decide per finding

The merged top-level verdict can be driven by a domain you do not act on (a `pii`
finding on a hiring flow), and `audit_only` findings never gated anything.
`classify_findings` reads the individual findings instead and maps them onto
your own tier names:

```python
from tenet_client import classify_findings

resp = client.evaluate(phase="agent_output", agent_reply=draft)
tier = classify_findings(
    resp,
    tiers={"retry": "medium", "fail": "high"},  # highest tier reached wins
    domains=["eeo"],                            # None counts every domain
)  # "fail", "retry", "accept", or "unavailable" for a degraded answer
```

An unknown severity string ranks above `critical` (and logs a warning), so a
vocabulary change in the engine lands in your strictest tier rather than passing.
`summarize_findings` returns the counted findings, the top one, its `rule_ids`
and `evidence_span`, and `at_least("high")`.

## Record every decision

A `DecisionRecord` is one normalized line per judge decision (decision, native
verdict, outcome, severity, `rule_ids`, `decision_id`, trace and session ids).
A sink is any `Callable[[DecisionRecord], None]`; a sink that raises is logged
and never reaches your call.

```python
import logging
from tenet_client.observability import langfuse_score_sink, logging_sink

sinks = [
    logging_sink(logging.getLogger("app.judge")),   # event "tenet_judge_decision"
    langfuse_score_sink(langfuse),                  # categorical score on the record's trace
]
```

The Langfuse sink writes a `tenet_judge` score whose value is the outcome and
whose comment is the record as JSON. It needs only an object with
`create_score`, so Langfuse is not a dependency, and it skips records that have
no trace id.

Pass them to `check` as `on_decision=sinks`: one record per call that reached the
judge (a cache hit emits none).

## Testing your integration

`tenet_client.testing` gives you a real client over an in-memory transport: no
network, no credentials, the token handshake answered for you. Build bodies with
`decide_response` / `finding`, and test your own policy callbacks through
`evaluate_phase`:

```python
from tenet_client import JudgeAction, JudgePolicy
from tenet_client.testing import decide_response, mock_judge_client

def test_review_is_held_and_logged():
    logged = []

    def on_review(ctx, verdict):
        logged.append(verdict.decision_id)
        return JudgeAction.tool_error("held for review")

    judge = mock_judge_client(
        decide_response("route_to_human", rule_ids=["EEO-AGE-01"], decision_id="d" * 32)
    )
    _, action = judge.evaluate_phase(
        policy=JudgePolicy(on_review=on_review), phase="agent_input", tool_input="..."
    )
    assert action.kind == "tool_error" and logged == ["d" * 32]
```

`responses` can also be a sequence (answered in order, the last repeats) or a
callable that receives each parsed request body. Other options: `captured=[]`
collects every request body, `status=503` and `raises=httpx.ReadTimeout("slow")`
simulate outages, `delay_s=` simulates a slow judge, and `use_stream=True` is
served as a verdict-first stream.

## `@judged` — gate any function

```python
from tenet_client import TenetCloudJudgeClient, JudgeBlocked, judged

judge = TenetCloudJudgeClient.from_env()
judge.warmup()

@judged(judge, fail_open=False)
def search_resumes(query: str) -> list[dict]:
    return _real_search(query)

try:
    hits = search_resumes("5+ years Python")
except JudgeBlocked as e:
    # e.reason / e.phase / e.tool_name / e.judge_id available
    ...
```

The decorator gates the function at `tool_pre` (before the body runs)
and `tool_post` (after it returns). Works on sync and async functions —
the wrapper auto-detects via `inspect.iscoroutinefunction`.

## Integration recipes

For LangChain agents, install [`tenet-langchain`](../tenet-langchain) —
it ships `CloudJudgeMiddleware`, the `wrap()` one-call helper, and
re-exports `@judged`. For other frameworks (LlamaIndex, FastAPI, raw
loops), see [the framework-free integration guide](https://docs.tenetlabs.com/guides/framework-free)
for copy-pasteable wiring patterns.

## License

Apache-2.0.
