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.
Context
Most calls need three things: who receives the text, where it goes, and why. Say them once on the client, or on a
session, and only what changes on a call. With nothing said, the app's saved context is used.
from governor import GovernorClient, channel_for, recipient_from_email
client = GovernorClient(api_key=..., context={"to": "client", "why": "support"})
# Per message: what this one has (consent or approval), and anything that differs
client.evaluate.check(text, context_facts={"via": "email", "granted": ["finra_approval"]})
# Fill to and via from what you already have
client.evaluate.check(text, context_facts={
"to": recipient_from_email(message.to, ["acme.com"]), # "internal" on your domains, else "client"
"via": channel_for("gmail"), # "email"; Slack and Teams give "chat", a webhook "system"
})
| Key |
Means |
Values |
to |
Who receives it (recipient.type) |
internal, client, vendor, public |
via |
Where it goes (channel) |
email, chat, social_media, website, ad, document, system |
why |
Why personal data is used (privacy.purpose) |
service_delivery, marketing, hr, legal, support, treatment, payment, healthcare_operations, research |
granted |
What this message has; per message only |
patient_consent, finra_approval, contact_consent |
Any other field goes in the same dict by its long name, nested or dotted: {"to": "client", "privacy.lawfulBasis": "contract"}. The value types are Recipient, Channel, Purpose and Granted. When the client and a session say the
same field, the session wins; a call wins over both.
r = client.evaluate.query(text, context_facts={"to": "client"})
r.context_warnings # keys no pack reads, and the line to add when a rule held the message back because something
# was not said: 'Add "why" to the context, one of: ... (gdpr.c1_purpose_missing)'
client.evaluate.context_schema() # the fields the app's packs read: values, the question to ask, defaults
client.evaluate.context_profiles() # profiles an app can start from ("Support reply", ...)
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)