Skip to main content

TrustState Python SDK

PyPI version Python License: MIT

Python SDK for the TrustState compliance API — validate, audit, and enforce compliance rules on any entity or data record. Built for financial services, AI governance, and regulated industries.

Install

pip install truststate

Requires Python 3.9+.

Quickstart

import asyncio
from truststate import TrustStateClient

client = TrustStateClient(api_key="ts_your_api_key")

async def main():
    result = await client.check(
        entity_type="SukukBond",
        data={
            "id": "BOND-001",
            "issuerId": "ISS-001",
            "currency": "MYR",
            "faceValue": 5_000_000,
            "maturityDate": "2030-06-01",
            "status": "DRAFT",
        },
    )

    if result.passed:
        print(f"✅ Passed — record ID: {result.record_id}")
    else:
        print(f"❌ Failed — {result.fail_reason} (step {result.failed_step})")

asyncio.run(main())

Batch Writes

Submit multiple records in a single API call. Useful for feed-based pipelines.

result = await client.check_batch(
    items=[
        {"entity_type": "SukukBond", "data": {"id": "BOND-001", ...}},
        {"entity_type": "SukukBond", "data": {"id": "BOND-002", ...}},
        {"entity_type": "SukukBond", "data": {"id": "BOND-003", ...}},
    ],
    feed_label="core-banking-feed",   # echoed on every item result
)

print(f"Accepted: {result.accepted}/{result.total}")
for item in result.results:
    print(f"  {item.entity_id}: {'✅' if item.passed else '❌'} {item.feed_label}")

BYOP Evidence (Oracle Data)

Attach oracle evidence to compliance checks — FX rates, KYC status, credit scores, sanctions screening.

# Fetch evidence from registered oracle providers
fx    = await client.fetch_fx_rate("MYR", "USD")
kyc   = await client.fetch_kyc_status("actor-jasim")
score = await client.fetch_credit_score("actor-jasim")

# Submit with evidence attached
result = await client.check_with_evidence(
    entity_type="SukukBond",
    data={"id": "BOND-001", "issuerId": "ISS-001", "currency": "MYR", "faceValue": 5_000_000},
    evidence=[fx, kyc, score],
)

Mock Mode

Test without making any API calls. Useful for unit tests and local development.

client = TrustStateClient(
    api_key="any",
    mock=True,
    mock_pass_rate=0.8,   # 80% of checks will pass
)

result = await client.check("SukukBond", {"id": "TEST-001", ...})
print(result.mock)   # True

Django / FastAPI Middleware

Automatically validate every incoming request body against TrustState policies.

# FastAPI
from truststate import TrustStateMiddleware

app.add_middleware(
    TrustStateMiddleware,
    api_key="ts_your_api_key",
    entity_type="AgentResponse",
)

# Django
MIDDLEWARE = [
    "truststate.middleware.TrustStateMiddleware",
    ...
]
TRUSTSTATE_API_KEY = "ts_your_api_key"
TRUSTSTATE_ENTITY_TYPE = "AgentResponse"

@compliant Decorator

Wrap any async function to automatically submit its return value for compliance checking.

from truststate import compliant, TrustStateClient

client = TrustStateClient(api_key="ts_your_api_key")

@compliant(client=client, entity_type="AgentResponse")
async def generate_response(prompt: str) -> dict:
    return {"text": "Hello!", "score": 0.95}

result = await generate_response("What is TrustState?")
# result is a ComplianceResult — .passed, .record_id, etc.

Configuration

Parameter Type Default Description
api_key str required Your TrustState API key
base_url str production URL Override the API base URL
default_schema_version str | None None Schema version (auto-resolved if omitted)
default_actor_id str "" Actor ID for the audit trail
mock bool False Enable mock mode (no HTTP calls)
mock_pass_rate float 1.0 Pass probability in mock mode (0.0–1.0)
timeout int 30 HTTP timeout in seconds

API Reference

check(entity_type, data, *, action, entity_id, schema_version, actor_id)

Submit a single record for compliance checking.

Returns: ComplianceResult

check_batch(items, *, default_schema_version, default_actor_id, feed_label)

Submit up to 500 records in a single call.

Returns: BatchResult

check_with_evidence(entity_type, data, evidence, *, action, entity_id, schema_version, actor_id)

Submit a record with oracle evidence attached.

Returns: ComplianceResult

fetch_fx_rate(from_currency, to_currency, *, provider_id, max_age_seconds)

fetch_kyc_status(subject_id, *, provider_id, max_age_seconds)

fetch_credit_score(subject_id, *, provider_id, max_age_seconds)

fetch_sanctions(subject_id, *, provider_id, max_age_seconds)

Fetch oracle evidence items from registered providers.

Returns: EvidenceItem

verify(record_id, bearer_token)

Retrieve an immutable compliance record from the ledger.

Returns: dict

ComplianceResult

Field Type Description
passed bool True if all checks passed
record_id str | None Immutable ledger record ID (only when passed)
request_id str Unique API request ID
entity_id str Entity ID that was submitted
fail_reason str | None Human-readable failure reason
failed_step int | None Step that failed (8=schema, 9=policy)
feed_label str | None Feed label from batch request
mock bool True if synthesised in mock mode

Requirements

  • Python 3.9+
  • httpx>=0.27

License

MIT © Trustchain Labs

Release files for truststate 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 truststate 0.2.0
File Size Uploaded
truststate-0.2.0.tar.gz 16.4 kB Details

Built distribution (wheel)

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

Total release size: 31.6 kB

Release files / truststate-0.2.0.tar.gz

Download URL truststate-0.2.0.tar.gz
Size 16.4 kB
Tags Source
SHA-256 checksum
How to use checksums
11e57e9389210a46482dc89d66cad262b1cf216b7a7faddd36dd67abd80080c6
BLAKE2b-256 checksum
How to use checksums
faa81ddabb1eed6ecdbc3f38e941fdda423bb8b4a78c4b10999161c6c685a5d9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

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 Mar 25, 2026.

Transparency log

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

Download URL truststate-0.2.0-py3-none-any.whl
Size 15.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8c08f7908a0475c1181290aa69c3d3c4864f19c207bf34c3426585c0b18e8843
BLAKE2b-256 checksum
How to use checksums
1ea9cb904c364cceb6ce469a3315f75db9e10cd6148860e00c0e4dd2963bf77c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.7

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 Mar 25, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files

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