gentrail
Governance SDK for AI agents. It captures compliance-evidence-grade telemetry from an agent run and, when enabled, enforces policy inline before a tool call executes.
A Go SDK with the same span shape lives in ../go/ (go get github.com/aigentrail/sdk/go).
Strict tool-call quotas
Available in the 0.8.0 release set. See release preparation for package verification and rollout.
Use an agent-bound API key and opt into fail-closed enforcement:
from gentrail.enforcement import PolicyEnforcer, enforce
enforcer = PolicyEnforcer(endpoint, bound_agent_key, strict_admission=True)
allowed, message = enforce(
enforcer, "issue_refund", arguments,
agent_id="billing-agent", request_id=tool_call_id,
)
if not allowed:
raise RuntimeError(message)
result = issue_refund(**arguments)
AsyncPolicyEnforcer(..., strict_admission=True) with enforce_async has the
same behavior. PolicyEnforcer.from_env(strict_admission=True) reads the
existing endpoint and key variables. Pass this enforcer to
GentrailGovernanceHook(enforcer=...), enforcement_middleware(enforcer=...),
or enforcement_guardrail(enforcer=...); adapter sync/async conversion retains
its strict setting, deadlines, clock and identity generator.
Enforcement resolves approval first, then reserves and consumes once immediately before returning permission to run. Unknown outcomes, outages, malformed or expired receipts, foreign links, redirects and lost consume responses block the call. A repeated request ID cannot reuse a consumed grant. Consumption remains charged after a tool failure, host refusal or crash. Execution and reporting remain separate; never retry execution because result reporting failed.
Low-level decide and await_gate are policy reads and do not grant quota
execution authority. Use enforce or a framework adapter at the tool boundary.
The admission exchange uses the existing quota_v1 server controls, a shared
nine-second budget, at most three seconds per network operation and 64 KiB
receipt limits. It never retries consume. No quota means no reservation requests.
Constructors without strict opt-in retain their existing fail-open decision
behavior, while an admission resource always requires explicit strict support.
Quickstart
pip install "gentrail[strands]"
export GENTRAIL_API_KEY="sk-..."
import gentrail
from strands import Agent
g = gentrail.init()
agent = Agent(model=model, tools=tools, hooks=[g.hook()])
agent("Reconcile the Q3 invoices")
That is the whole integration. init() reads the environment, builds the
governance tracer and the policy enforcer, and hook() returns a Strands
HookProvider that captures prompts, chain-of-thought, and tool calls, ships
them over OTLP, registers the agent on its first invocation, and enforces
verdicts before a tool runs. Use one hook() per agent. Whatever is not
configured stays off: with no API key the agent still runs, capture-only.
OpenAI Agents SDK
pip install "gentrail[openai-agents]"
from agents import function_tool
from gentrail.openai_agents import enforcement_guardrail
@function_tool(tool_input_guardrails=[enforcement_guardrail()])
def run_sql(database: str, sql: str) -> str: ...
A tool input guardrail that asks the decide endpoint before the tool runs. BLOCK rejects the call with the policy message; GATE holds it until a human approves in the Gentrail dashboard.
LangChain / LangGraph
pip install "gentrail[langchain]"
from langchain.agents import create_agent
from gentrail.langchain import enforcement_middleware
agent = create_agent(
model=model,
tools=tools,
middleware=[enforcement_middleware(agent_id="reporter")],
)
Agent middleware wrapping every tool call, sync and async. Same verdicts: a
blocked or unapproved call becomes an error ToolMessage and the tool never
executes.
Bring your own telemetry
Frameworks that emit OpenTelemetry GenAI telemetry natively (Strands with
strands-agents[otel], Google ADK, Pydantic AI, LangChain with
LANGSMITH_OTEL_ENABLED, the Vercel AI SDK) do not need the SDK to build
spans: the Gentrail backend ingests gen_ai.*, ai.*, and OpenInference
telemetry directly. This is the recommended integration for those frameworks.
What the SDK still adds is client-side PII redaction and export to Gentrail:
import gentrail
gentrail.instrument()
instrument() attaches a GentrailSpanProcessor to your application's
TracerProvider (pass yours with instrument(provider=...); a fresh one is
installed only when none exists). The processor redacts PII from gen_ai.*,
ai.*, and OpenInference input/output attributes before any value leaves the
process, stamps aigentrail.redaction.applied on spans it changed, and ships
them to the Gentrail collector over OTLP. Spans without a GenAI signal (your
database and HTTP spans) are dropped rather than exported. Other exporters on
the provider keep the raw spans. Without GENTRAIL_API_KEY it returns None
and the app runs unchanged.
The governance tracer behind init() never touches your provider: it runs on
its own, so your spans cannot reach Gentrail through it, and its spans still
join your trace through the shared OpenTelemetry context.
Inline enforcement stays separate: add the enforcement adapter for your framework (above) to get BLOCK and GATE verdicts before a tool runs.
Configuration
All through environment variables:
GENTRAIL_API_KEY: enables OTLP export of governance spans.OTEL_EXPORTER_OTLP_ENDPOINT: collector base URL, defaulthttps://otel.gentrail.ai.OTEL_EXPORTER_OTLP_HEADERS: standard OTel header list; when set it replaces the SDK's defaultAuthorization: Bearer <GENTRAIL_API_KEY>header.GENTRAIL_DECIDE_ENDPOINT: enables inline enforcement (see below).GENTRAIL_REDACT_PII: set tofalseto disable client-side PII redaction.GENTRAIL_GATE_TIMEOUT_SECONDS: how long a gated tool call waits for human approval, default 120.
If your application already configures an OpenTelemetry TracerProvider, the
SDK attaches its exporter to it as an extra span processor instead of replacing
it; a fresh provider is installed only when none exists.
PII redaction
The SDK redacts PII from span input and output values before they leave the
process, scanning with RE2 (google-re2) so detection is linear-time in the
input, replacing each value with a typed placeholder: [EMAIL], [SSN],
[CREDIT_CARD], [IBAN], [PHONE], [AWS_KEY], or [SECRET]. Numbers are
validated (Luhn, SSN area rules, IBAN mod-97) so order ids and look-alikes
survive, and secrets are found with the vendored gitleaks default rules. The raw
value never reaches the collector while the data class stays visible for
governance. The detector matches Gentrail's server-side one, pinned by the
shared corpus in spec/pii_conformance.json. This applies to spans the SDK
builds and, via GentrailSpanProcessor, to gen_ai.*, ai.*, and
OpenInference attributes on spans your framework emits itself. On by default;
opt out with GENTRAIL_REDACT_PII=false or instrument(redact=False).
Inline enforcement (opt-in)
The async backend evaluator only sees a trace after a tool has already run, so it can detect but never prevent. Enforcement happens here, in the before-tool-call hook: the SDK asks the backend for a verdict on the proposed tool call and stops it before it executes.
It is opt-in and fails open. Set both environment variables to turn it on:
export GENTRAIL_DECIDE_ENDPOINT="https://your-dashboard.example"
export GENTRAIL_API_KEY="sk-..."
With these set, a BLOCK verdict cancels the tool call (the agent receives an
error tool result and the tool never runs). A GATE verdict also stops the call
pending human approval. A backend error never breaks the agent: the call is
allowed and enforcement is skipped for that step.
Advanced: raw capture surfaces
init() and hook() compose lower-level pieces that remain importable for
consumers that need them directly:
evidence_ledger.py: a local audit log ofDecisionJournals; the hook seals one per invocation. The integrity hash is SHA-256 over the journal's RFC 8785 canonical JSON, so the Go and JS SDKs produce the same hash for the same journal (spec/journal_vectors.json).init()gives each handle its own ledger athandle.ledger.otel_exporter.py:create_governance_tracer()/get_governance_tracer()build the OTLP pipeline without the rest of the SDK.tracer.httpx_transport()andtracer.async_httpx_transport()wrap an httpx client so every request is recorded as a model call with latency and status (requireshttpx).enforcement.py:PolicyEnforcerand its asyncio twinAsyncPolicyEnforcerare the raw decide/gate clients;enforce()/enforce_async()run one decide-and-gate cycle and return(allowed, message).
Develop
uv sync --extra strands
ruff check .
python3 tests/test_enforcement.py
python3 tests/test_init.py
python3 tests/test_parity_spec.py
Linking tool results to decisions
PolicyEnforcer.decide() and AsyncPolicyEnforcer.decide() return an explicit
outcome: verified, request_conflict, or unavailable. A transport failure
still follows the existing fail-open behavior, with outcome="unavailable".
BLOCK and unresolved GATE decisions retain their enforcement behavior.
A verified, attributed response can include an immutable DecisionReference in
verdict["observation_reference"] and a server-provided observations_url.
Pass that reference as decision_reference to GovernanceTracer.record_tool_call()
after the tool actually runs. Supply the full actual arguments as JSON; the
tracer hashes them before redaction and truncation. Changed arguments remain
visible to the backend as an identity mismatch. Invalid references are discarded
without changing permission; invalid recording input raises an error and leaves
an ordinary, unlinked span.
The Strands hook carries references automatically, keeps at most 128 pending calls, and skips cancelled calls. Evicted or missing references leave results unlinked. LangChain and OpenAI guardrails enforce permission; callers that record execution evidence use the tracer explicitly. References link producer reports and never grant permission or attest that a tool executed.
Metadata
Release files for gentrail 0.8.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| gentrail-0.8.0.tar.gz | 220.4 kB | With provenance | Details for gentrail-0.8.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| gentrail-0.8.0-py3-none-any.whl | Python 3 | none | any | Details for gentrail-0.8.0-py3-none-any.whl |
Total release size: 280.0 kB
Release files / gentrail-0.8.0.tar.gz
| Download URL | gentrail-0.8.0.tar.gz |
|---|---|
| Size | 220.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
3df649b2d66bda750a4ffc0fc55bdb8cc06f0cc8ee47b751ec28f27812770a3b
|
|
BLAKE2b-256 checksum How to use checksums |
0c071d73668a1a9bdbc6fa923ef797741c5cc9129a6df6847a39bf854add21e9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 18, 2026.
Transparency logRelease files / gentrail-0.8.0-py3-none-any.whl
| Download URL | gentrail-0.8.0-py3-none-any.whl |
|---|---|
| Size | 59.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
4d36429eda85c2a1a99c9e9ee133d40e9d3b41899783cfa4d25a8ea99c623c03
|
|
BLAKE2b-256 checksum How to use checksums |
7783ea37fcc898163b83665f96671587101a8542f8c6ad348ef8601d5fc37fcc
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 18, 2026.
Transparency logSecurity for gentrail 0.8.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.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for gentrail-0.8.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 18, 2026.
Transparency logA 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.