Metadata-Version: 2.4
Name: unifyapps-guardrails
Version: 0.2.0
Summary: Thin client for UnifyApps platform guardrails (config-driven controls/policies), traced to UnifyApps observability.
Author: UnifyApps
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/unify-apps/unifyapps-guardrails
Project-URL: Repository, https://github.com/unify-apps/unifyapps-guardrails
Keywords: unifyapps,guardrails,ai,governance,opentelemetry,llm
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: opentelemetry-api>=1.20.0
Dynamic: license-file

# unifyapps-guardrails

A thin client for **UnifyApps platform guardrails**. Checks are *not* run in this
process — they are config-driven `controls` (Denied Topics, Content Filter, PII,
Prompt Injection, Custom terms, Regex, Credentials, Blocked Tools, Custom LLM)
grouped into `policies` applied to an agent. This client calls the exported
`Governance | Inline Evaluate` endpoint, which resolves the agent's controls for a
given surface, runs only those, writes incidents itself, and returns one decision.

Add or remove a control in the UI and the same code enforces it — nothing about the
checks is hardcoded here. Every call emits an OpenTelemetry span so it nests inside
your existing UnifyApps trace.

## Install

```bash
pip install unifyapps-guardrails
```

Or, from a clone (editable):

```bash
pip install -e .
```

Stdlib + `opentelemetry-api` only — no models to download, no heavy deps.

## Configure

| Env var | Purpose |
|---|---|
| `UNIFYAPPS_GUARDRAILS_URL` | URL of the exported inline-evaluate callable, with the **agent id as its last path segment** (like the OTLP endpoint) |
| `UNIFYAPPS_GUARDRAILS_API_KEY` | optional; sent as `Authorization: Bearer <key>` |

## Usage

```python
from unifyapps.guardrails import GovernanceGuard

# agent id comes from UNIFYAPPS_GUARDRAILS_URL's path — nothing to pass here
guard = GovernanceGuard()

# Before the LLM sees the user's message
d = guard.check_user_input(user_text)
if d.block:
    return d.content          # refusal message — don't call the LLM
user_text = d.content         # masked/clean text to send to the LLM

# After the LLM answers, before the user sees it
d = guard.check_agent_output(reply)
return d.content              # block -> refusal; else masked/clean text

# Before a tool runs (Blocked Tools matches the name; PII/Regex/... mask the arguments)
d = guard.check_tool_input("charge_card", {"amount": 10, "card": "4111111111111111"})
if d.block:
    result = d.content        # tool refusal — don't call the tool
else:
    result = charge_card(**d.tool_value)   # masked arguments

# After the tool returns, before the LLM sees its result
d = guard.check_tool_output("charge_card", result)
result = d.content if d.block else d.tool_value
```

### The decision

`evaluate` / `check_user_input` / `check_agent_output` / `check_tool_input` / `check_tool_output` return a `GovernanceDecision`:

| Field | Meaning |
|---|---|
| `block` | `True` if the content must be withheld |
| `content` | the text to **use**: masked/clean when `block=False`, the refusal message when `block=True` |
| `raw` | the full endpoint payload |
| `tool_value` | tool checks only: the tool arguments / result to **use** when `block=False` (masked, or your original object when nothing was masked); `None` when `block=True` |

Surfaces (see `Surface`): `user_input`, `agent_output`, `tool_input`, `tool_output`. A
tool check runs even with empty arguments, since Blocked Tools matches on the name. Tool
values are sent as JSON (dates, decimals and other objects as text); a value JSON cannot
hold (a circular reference, non-string keys) is checked as its text. When the platform
masks a value, `tool_value` is its JSON form: dates, decimals and objects come back as
strings and dict keys as strings; when nothing was masked it is your own object. A message
that is not text (a list of content parts) is checked as its JSON text. The guard **fails
open** — on timeout or endpoint error it returns the original text (and tool value) with
`block=False`, so a guardrail outage never drops a turn.

### Observability

Each call is a `guardrail.evaluate` span. Inside a LangChain run (OpenInference
instrumentation) it is parented under the active run, so it travels in the agent's own
trace. A **blocked tool input** check outside the tool — the tool never runs — is recorded
as an OpenInference TOOL span (tool name, arguments, refusal), so the trace shows the
blocked call as a failed tool call. When the guard runs inside the tool, the framework's
own tool span records the call: raise on a block (see the LangGraph / OpenAI Agents
examples) so it shows as failed.

Mode is the agent's, not the code's: for an agent in **observe** mode the endpoint never
blocks or masks (every check returns the original value) and records nothing inline —
findings are flagged from the agent's traces instead. Running these guards against an
observe agent is safe but only adds latency.

## Endpoint contract

```
POST <UNIFYAPPS_GUARDRAILS_URL>          # .../<agent-id>  (id is the last path segment)
body  -> { content, inputType, caseId }
200   -> { block: bool, content: str }

# tool checks
body  -> { content, inputType, caseId, toolName, tool_input | tool_output }
200   -> { block: bool, content: str, toolInput, toolOutput }
```

The **agent id is the last path segment of the URL**, not a body field — same shape as
the OTLP collector endpoint, so it is never passed twice. It is both the policy lookup
key and the incident scope; the exported callable maps that path segment to its
`agentId` input. `inputType` is the surface (`user_input` / `agent_output` / `tool_input` / `tool_output`); for a tool check `content` is the tool value as JSON text. `caseId`
is any stable per-conversation id (the client defaults to a random uuid) so the
resolver takes the chat branch.

## Examples

Full input + output turns, one per framework, in [`examples/`](examples/):

| Framework | File |
|---|---|
| LangChain | [`examples/langchain_unify_guardrails.py`](examples/langchain_unify_guardrails.py) |
| LangGraph | [`examples/langgraph_unify_guardrails.py`](examples/langgraph_unify_guardrails.py) |
| OpenAI Agents SDK | [`examples/openai_agents_unify_guardrails.py`](examples/openai_agents_unify_guardrails.py) |

## License

[Apache 2.0](LICENSE).
