Metadata-Version: 2.4
Name: nkx-governor
Version: 0.2.0
Summary: Python client for the Governor policy compliance inference API
Author: NakodaX
License: MIT
Project-URL: Repository, https://github.com/nakodax/nkx-governor
Project-URL: Documentation, https://github.com/nakodax/nkx-governor#readme
Keywords: governor,nkx,inference,policy,compliance,api,client
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: httpx>=0.24.0
Requires-Dist: pydantic>=2.0.0
Provides-Extra: documents
Requires-Dist: pymupdf>=1.23.0; extra == "documents"
Requires-Dist: python-docx>=1.1.0; extra == "documents"
Requires-Dist: openpyxl>=3.1.0; extra == "documents"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"

# Governor Python SDK

**Official Python client for the Governor policy compliance API.** Evaluate natural-language content against your policies and get **ALLOW**, **MODIFY**, or **BLOCK** decisions with explanations.

---

## Features

- **Simple API** — Send only `query`, `metadata`, and `additional_metadata`; no extra parameters.
- **Structured metadata** — Use the `{"key": {"value": "val", "description": "des"}}` shape for clear, documented context.
- **Sync and async** — `GovernorClient` and `AsyncGovernorClient` with the same interface.
- **Typed models** — Pydantic request/response models for IDE support and validation.
- **LangSmith run tracking** — Attach a LangSmith `run_id` to any inference log for end-to-end LLM trace monitoring from the Governor dashboard.

---

## Installation

```bash
pip install nkx-governor
```

For document compliance checks (PDF/DOCX/CSV/XLSX), install the optional extra:

```bash
pip install "nkx-governor[documents]"
```

**Requirements:** Python 3.9+, `httpx`, `pydantic`. The `documents` extra adds
`pymupdf`, `python-docx`, and `openpyxl`.

---

## Document compliance check

Evaluate a whole document against your governance policies. Extraction runs **locally**
in the SDK — the SDK reads the file, splits it into page-aware chunks (PDF page numbers,
DOCX blocks, XLSX sheets, CSV row-blocks), and sends only the combined text to
`/v3/evaluate` in a **single call**. The raw file is never uploaded, so there is nothing
to store server-side.

```python
from governor import GovernorClient

client = GovernorClient(api_key="your-api-key")

# Accepts a path, raw bytes (with filename=...), or a file-like object.
result = client.evaluate.document("disclosure.pdf")

print(result.final_decision)          # ALLOW | ADJUST | BLOCK | CLARIFY
print(result.page_count, "pages analyzed")

for verdict in result.policy_verdicts:
    for v in verdict.violations:
        print(f"[{verdict.policy}] {v.reason} → {v.remedy}")

# result.page_manifest maps each page/section to its span in the evaluated text.
```

Supported types: `.pdf`, `.docx`, `.txt`, `.csv`, `.xlsx`. Unlike `evaluate.query()`,
`evaluate.document()` returns the result even on **BLOCK** so you can present the issues.

---

## Set the mode once

Give the client your app's mode (`"action"` or `"monitor"`) and use `evaluate.check()`. The
same line then waits and enforces in action, and does not wait in monitor:

```python
from governor import GovernorClient
from governor.exceptions import EvaluationBlockedError

client = GovernorClient(api_key="your-api-key", mode="action")   # or mode="monitor"

try:
    client.evaluate.check(prompt, callback=lambda r: print(r.final_decision))
    answer = call_your_llm(prompt)
except EvaluationBlockedError as e:
    answer = "Sorry, I can't help with that."   # e.response has the reasons
```

| Client `mode` | `check()` | `query()` / `document()` |
|---------------|-----------|--------------------------|
| `"action"` | sends `mode="action"`, waits, raises `EvaluationBlockedError` on BLOCK | send `mode="action"` unless the call passes its own `mode` |
| `"monitor"` | sends in the background (`submit()`), returns `None` at once, never raises | wait, as before |
| not set | waits; the app's mode on the server decides | as before |

The `callback` gets the response in both modes. `check_compliance` follows the client's mode
too: in monitor your function runs at once and the check goes out in the background. If a
client set to `"monitor"` talks to an app that the server runs in action mode, the SDK logs one
warning on the `governor` logger: set the client to `mode="action"` so verdicts are enforced.

With `AsyncGovernorClient`, `await client.evaluate.check(...)` in both modes; in monitor it
returns `None` without waiting for the check.

---

## Monitor without waiting

`evaluate.check()` on a client created with `mode="monitor"` uses `evaluate.submit()`. Call
`submit()` yourself when you want the handle back: it sends the message for checking in the
background and returns at once, so your LLM call never waits for Governor. It never raises:
errors, the time limit (`timeout`, default 10 s) and errors in your callback are logged and
kept on the returned handle. If too many checks are waiting, new ones are dropped and counted
in `client.evaluate.dropped`.

```python
from governor import GovernorClient

client = GovernorClient(api_key="your-api-key")

future = client.evaluate.submit(prompt, callback=lambda r: print(r.final_decision))
answer = call_your_llm(prompt)        # runs right away
response = future.result()            # optional: the verdict, when you want it
client.close()                        # at shutdown; does not wait
```

With `AsyncGovernorClient`, `submit()` (no `await`) returns an `asyncio.Task`; `await` it
later if you want the result, and call `await client.aclose()` at shutdown.

`submit()` cannot block anything, because your app has already moved on. For an app in
**action** mode, use `check()` on a client created with `mode="action"`, or `evaluate.query()`;
both wait and raise `EvaluationBlockedError` on BLOCK.

---

## Quick start

```python
from governor import GovernorClient

client = GovernorClient(api_key="your-api-key")

response = client.inference.query(
    "Can I share this document with external partners?",
    metadata={
        "consent": {"value": "yes", "description": "User gave consent"},
        "data_type": {"value": "PHI", "description": "Contains protected health info"},
    },
)

print(response)   # Complete Response
print(response.final_decision)   # ALLOW | MODIFY | BLOCK
print(response.explanation)      # Human-readable explanation
print(response.processing_time_seconds)
```

```python
client = GovernorClient(api_key="your-api-key", base_url="https://your-custom-api.com")
```

---

## API overview

### What you send (request)

Only four fields are accepted:

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| **query** | `str` | Yes | Natural language content to evaluate against your policies. |
| **metadata** | `dict` | No | Context for compliance. Shape: `{"key": {"value": "val", "description": "des"}}`. Used by the engine for the decision. |
| **additional_metadata** | `dict` | No | Stores optional user information (e.g., name, email) as key-value pairs, saved along with the inference log for auditing purposes. Example: {"user_name": "John Doe", "email": "john.doe@example.com"} |
| **explanation** | `bool` | No | If True, wait for explanation generation and include in response. Defaults to False. |

**Metadata shape** — Each key maps to an object with:

- **value** (str): The actual value (e.g. `"yes"`, `"PHI"`).
- **description** (str): Optional short description of the field.

Example:

```python
metadata = {
    "consent": {"value": "yes", "description": "User consent obtained"},
    "classification": {"value": "internal", "description": "Document classification"},
}
```

### What you get (response)

`InferenceResponse` includes:

| Field | Type | Description |
|-------|------|-------------|
| `log_id` | str \| None | ID of the inference log for fetching details later. |
| `query` | str | Echo of the query. |
| `final_decision` | str | `ALLOW`, `MODIFY`, or `BLOCK`. |
| `final_score` | float | Aggregate score (0–1). |
| `matched_policies` | list[str] | Policies that were evaluated. |
| `model_results` | list[RuleResult] | Per-rule decision, confidence, and probabilities. |
| `explanation` | str \| None | Human-readable explanation. |
| `make_it_compliant` | str \| None | Suggested changes to make the query compliant. |

---

## Usage

### Sync client

```python
from governor import GovernorClient, InferenceRequest

client = GovernorClient(api_key="your-api-key")

# Simple query
response = client.inference.query("Should I send this email to a competitor?")

# With metadata (authoritative context for the engine)
response = client.inference.query(
    "Share the report with the client.",
    metadata={
        "consent": {"value": "yes", "description": "Client consent on file"},
        "channel": {"value": "email", "description": "Delivery channel"},
    },
)

# With additional_metadata (stored with log only)
response = client.inference.query(
    "Upload to cloud storage.",
    additional_metadata={"user_name": "John Doe", "email": "john.doe@example.com"},
)

# Using the request model
req = InferenceRequest(
    query="Can I export this data?",
    metadata={"data_type": {"value": "PII", "description": "Personal data"}},
)
response = client.inference.run(req)

# Fetching full inference log details
if response.log_id:
    log_details = client.inference.get_log(response.log_id)
    print(log_details)
```

### Async client

```python
from governor import AsyncGovernorClient

async with AsyncGovernorClient(api_key="your-api-key") as client:
    response = await client.inference.query_async(
        "Can I share this document?",
        metadata={"consent": {"value": "yes", "description": "Consent given"}},
    )
    print(response.final_decision)

# Or with run_async
req = InferenceRequest(query="...", metadata={...})
response = await client.inference.run_async(req)

# Fetching full inference log details (async)
if response.log_id:
    log_details = await client.inference.get_log_async(response.log_id)
```

### Configuration

| Parameter | Description |
|-----------|-------------|
| `api_key` | **Required.** Your Governor API key (from the dashboard). |
| `base_url` | Override API base URL. Default: `https://governor-be.nakodax.com`. |
| `timeout` | Request timeout in seconds (default: `60.0`). |
| `headers` | Optional extra HTTP headers. |
| `mode` | `"action"`, `"monitor"` or `None` (default). See [Set the mode once](#set-the-mode-once). |

The client sends the API key in the `X-API-Key` header. No other auth is required.

---

## Exceptions

| Exception | When |
|-----------|------|
| **GovernorAuthError** | Invalid or expired API key (401). |
| **GovernorValidationError** | Bad request or invalid parameters (400). |
| **GovernorAPIError** | Other API errors (4xx/5xx). Has `status_code`, `detail`, `response_body`. |
| **ComplianceBlockedError** | Raised by :func:`check_compliance` when the decision is BLOCK. Has `response` (full :class:`InferenceResponse`). |

All extend **GovernorError** (with `message` and optional `status_code`).

```python
from governor import GovernorClient
from governor.exceptions import GovernorAuthError, GovernorAPIError

client = GovernorClient(api_key="your-api-key")
try:
    r = client.inference.query("Some query")
except GovernorAuthError as e:
    print("Auth failed:", e.message)
except GovernorAPIError as e:
    print("API error:", e.status_code, e.detail)
```

---

## LangSmith run tracking

Governor integrates with [LangSmith](https://smith.langchain.com/) to give you end-to-end visibility into your LLM executions directly from the Governor dashboard.

When you run an LLM call traced through LangSmith, you can attach the resulting `run_id` to the corresponding Governor inference log. The dashboard will then surface the full trace alongside the policy decision — inputs, outputs, token usage, latency, cost, and intermediate tool calls — without switching tabs or tools.

### Why use it

- Correlate policy decisions with the exact LLM call that triggered them.
- Debug blocked or modified responses by inspecting the full prompt and output.
- Monitor token usage and cost per inference from a single view.

### `update_log` parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `log_id` | `str` | Yes | ID of the Governor inference log. Returned as `response.log_id` after calling `client.inference.query(...)`. |
| `run_id` | `str` | Yes | LangSmith run ID (UUID) to attach to the log. Must be a valid UUID — validated client-side before the request is sent. |

### Example

```python
from governor import GovernorClient

client = GovernorClient(api_key="your-api-key")

# 1. Run policy inference and capture the log ID
response = client.inference.query("Can I share this document externally?")
log_id = response.log_id

# 2. Run your LLM call with LangSmith tracing and capture the run_id
#    (langsmith_run_id comes from your LangSmith callback/tracer)
langsmith_run_id = "9b7505cd-f111-4a34-8cc5-9006da96cbfc"

# 3. Attach the LangSmith run_id to the inference log
if log_id:
    updated = client.inference.update_log(
        log_id=log_id,
        run_id=langsmith_run_id,
    )
    print(updated)
```

The updated log is now visible in the **Inference Logs** section of the Governor dashboard with the full LangSmith trace attached.

### Async variant

```python
from governor import AsyncGovernorClient

async with AsyncGovernorClient(api_key="your-api-key") as client:
    response = await client.inference.query_async("Summarize this contract.")
    if response.log_id:
        updated = await client.inference.update_log_async(
            log_id=response.log_id,
            run_id="9b7505cd-f111-4a34-8cc5-9006da96cbfc",
        )
        print(updated)
```

### Validation

`update_log` and `update_log_async` validate `run_id` on the client before making any network call. An invalid UUID raises `ValueError` immediately:

```python
from governor import GovernorClient

client = GovernorClient(api_key="your-api-key")

try:
    client.inference.update_log(log_id="...", run_id="not-a-uuid")
except ValueError as e:
    print(e)  # run_id must be a valid UUID, got: 'not-a-uuid'
```

---

## Integration checklist

1. **Get an API key** from your Governor dashboard.
2. **Install** — `pip install nkx-governor`.
3. **Create client** — `GovernorClient(api_key="...")`.
4. **Call** — `client.inference.query(query, metadata=..., additional_metadata=...)`.
5. **Handle** — Use `response.final_decision`, `response.explanation`, and catch `GovernorAuthError` / `GovernorAPIError` as needed.

---

## Decorator: check compliance before calling your function

Use :func:`check_compliance` to run the inference API on a chosen argument before your function runs. If the decision is **BLOCK**, the decorator raises :exc:`ComplianceBlockedError` (or returns ``None``); otherwise it calls your function.

```python
from governor import GovernorClient, check_compliance

client = GovernorClient(api_key="your-api-key")

@check_compliance(client, query_arg="message")
def handle_user_message(message: str, user_id: str):
    # Only runs if compliance allows (ALLOW or MODIFY)
    return process(message, user_id)

# BLOCK → ComplianceBlockedError (with response.explanation, response.make_it_compliant)
# ALLOW / MODIFY → your function runs
handle_user_message("Can I share this file?", "u-123")
```

**Options:** ``query_arg`` (param name to check, default ``"query"``), ``on_block`` (``"raise"`` or ``"return_none"``), ``metadata``, ``pass_response`` (inject ``_governor_response`` into kwargs). Use :class:`AsyncGovernorClient` with async functions.

```python
from governor import AsyncGovernorClient, check_compliance

client = AsyncGovernorClient(api_key="your-api-key")

@check_compliance(client, query_arg="prompt")
async def run_llm(prompt: str):
    return await model.generate(prompt)
```

Catch blocks with :exc:`ComplianceBlockedError` and use ``e.response.explanation`` or ``e.response.make_it_compliant`` to show the user why it was blocked or how to fix it.

---

## Package structure

Each module has a single responsibility:

| Module | Purpose |
|--------|---------|
| `governor.constants` | Default base URL and API path. |
| `governor._http` | HTTP response helpers (e.g. error detail extraction). |
| `governor.models` | Request/response Pydantic models and metadata shape. |
| `governor.inference` | Inference API (sync/async): `query`, `run`, `get_log`, `update_log`, and async variants. |
| `governor.client` | Sync and async HTTP clients. |
| `governor.exceptions` | Auth, validation, and API exceptions. |

Import the public API from `governor`; use submodules only if you need constants or helpers.

---

## License

MIT
