Skip to main content

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

pip install nkx-governor

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

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.

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:

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.

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

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)
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:

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

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

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.

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

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

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

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:

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.

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.

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

Metadata

Release files for nkx-governor 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for nkx-governor 0.2.0
File Size Uploaded Provenance Actions
nkx_governor-0.2.0.tar.gz 49.3 kB Without provenance Details for nkx_governor-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for nkx-governor 0.2.0
File Interpreter ABI Platform Actions
nkx_governor-0.2.0-py3-none-any.whl Python 3 none any Details for nkx_governor-0.2.0-py3-none-any.whl

Total release size: 80.5 kB

Release files / nkx_governor-0.2.0.tar.gz

Download URL nkx_governor-0.2.0.tar.gz
Size 49.3 kB
Tags Source
SHA-256 checksum
How to use checksums
815acf42c7c2d61b678e5449b065f523bba21d99009de820ebc0580e81849fad
BLAKE2b-256 checksum
How to use checksums
32b4e4f05b697fcefebf43d0014c3aa68d640c5211ef997c0cb0f57cf570298d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.15

Release files / nkx_governor-0.2.0-py3-none-any.whl

Download URL nkx_governor-0.2.0-py3-none-any.whl
Size 31.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3654c531de1fdec2bfce8c57048a7daf3d8a8e3dce1de1bceeac233eefbe1fd6
BLAKE2b-256 checksum
How to use checksums
594ad89af35b00cc407607e14ff24f735cc5bf2f6c149082e4977f403a610f20
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.11.15

Security for nkx-governor 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page