Skip to main content

Python SDK for TrustState compliance validation

Project description

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

truststate-0.2.0.tar.gz (16.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

truststate-0.2.0-py3-none-any.whl (15.1 kB view details)

Uploaded Python 3

File details

Details for the file truststate-0.2.0.tar.gz.

File metadata

  • Download URL: truststate-0.2.0.tar.gz
  • Upload date:
  • Size: 16.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for truststate-0.2.0.tar.gz
Algorithm Hash digest
SHA256 11e57e9389210a46482dc89d66cad262b1cf216b7a7faddd36dd67abd80080c6
MD5 d015ef8d44851aa49ed39abb30453ce2
BLAKE2b-256 faa81ddabb1eed6ecdbc3f38e941fdda423bb8b4a78c4b10999161c6c685a5d9

See more details on using hashes here.

Provenance

The following attestation bundles were made for truststate-0.2.0.tar.gz:

Publisher: publish.yml on TrustchainLabs/truststate-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file truststate-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: truststate-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 15.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for truststate-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8c08f7908a0475c1181290aa69c3d3c4864f19c207bf34c3426585c0b18e8843
MD5 47e766af5b336541845457cfed3124d4
BLAKE2b-256 1ea9cb904c364cceb6ce469a3315f75db9e10cd6148860e00c0e4dd2963bf77c

See more details on using hashes here.

Provenance

The following attestation bundles were made for truststate-0.2.0-py3-none-any.whl:

Publisher: publish.yml on TrustchainLabs/truststate-python

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page