Skip to main content

Python SDK for the TruthChain AI-validation API

Project description

TruthChain Python SDK

Validate AI outputs against any business rules in <100ms.

Installation

pip install truthchain

Requires Python 3.9+ and installs httpx automatically.

Note: You'll need a running TruthChain server. Pass its URL as base_url when creating your client (e.g. TruthChain(api_key="tc_...", base_url="https://your-server.com")).

Quick Start

1. Sign up (one-time)

from truthchain import signup

result = signup(
    name="Acme Corp",
    email="dev@acme.com",
    password="s3cretPW!",
    tier="free",                         # "free" | "startup" | "business" | "enterprise"
    base_url="http://localhost:8000",    # your TruthChain server
)
print(result.api_key)   # tc_...  ← save this securely!

2. Validate AI output

from truthchain import TruthChain

client = TruthChain(
    api_key="tc_...",
    base_url="http://localhost:8000",  # default
)

result = client.validate(
    output={
        "user_id": 12345,
        "hours": 8,
        "project_name": "Project-X",
    },
    rules=[
        {
            "type": "schema",
            "name": "output_structure",
            "schema": {
                "type": "object",
                "properties": {
                    "user_id":      {"type": "integer"},
                    "hours":        {"type": "number"},
                    "project_name": {"type": "string"},
                },
                "required": ["user_id", "hours", "project_name"],
            },
        },
        {
            "type": "range",
            "name": "hours_check",
            "field": "hours",
            "min": 0,
            "max": 24,
            "severity": "error",
        },
    ],
    context={"auto_correct": True},   # optional
)

print(result.status)          # "passed" | "failed" | "warning"
print(result.is_valid)        # True / False
print(result.violations)      # list of Violation objects
print(result.corrected_output) # auto-corrected dict (if auto_correct=True)
print(result.latency_ms)      # e.g. 12

3. Login (get a fresh API key)

from truthchain import login, TruthChain

auth = login("dev@acme.com", "s3cretPW!")
client = TruthChain(api_key=auth.api_key)

API Reference

TruthChain(api_key, base_url, timeout)

Validation

Method Returns Description
validate(output, rules, context) ValidationResult Validate an AI output

Analytics

Method Returns Description
get_analytics() AnalyticsOverview Full analytics overview
get_validation_stats() ValidationStats Aggregated stats

Billing

Method Returns Description
get_subscription() Subscription Current plan & usage
get_plans() List[BillingPlan] All available plans
upgrade(tier) Subscription Change subscription tier

API Key Management

Method Returns Description
list_api_keys() List[APIKey] List all keys
create_api_key(name) APIKey Create new key
rotate_api_key(key_id) APIKey Rotate key (revokes old)
revoke_api_key(key_id) None Revoke a key

Top-level helpers (no API key needed)

Function Returns Description
signup(name, email, password, tier) SignupResult Register new org
login(email, password) LoginResult Login, get fresh key

Async Usage

import asyncio
from truthchain import AsyncTruthChain

async def main():
    async with AsyncTruthChain(api_key="tc_...") as client:
        result = await client.validate(
            output={"score": 95},
            rules=[{"type": "range", "name": "score", "field": "score", "min": 0, "max": 100}],
        )
        print(result.status)

asyncio.run(main())

Error Handling

from truthchain import TruthChain
from truthchain.exceptions import (
    AuthenticationError,
    QuotaExceededError,
    RateLimitError,
    ValidationError,
)

client = TruthChain(api_key="tc_...")

try:
    result = client.validate(output={}, rules=[])
except AuthenticationError:
    print("Invalid or revoked API key")
except QuotaExceededError:
    print("Monthly quota exhausted — upgrade your plan")
except RateLimitError as e:
    print(f"Rate limited — retry after {e.retry_after}s")
except ValidationError as e:
    print(f"Bad request: {e.message}")

Rule Types

Type Required fields Description
schema schema (JSON Schema) Validate structure & types
range field, min, max Numeric range check
pattern field, pattern (regex) Regex match
required fields (list) Presence check
reference field, reference_type DB existence check

License

MIT

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

truthchain-1.0.1.tar.gz (11.5 kB view details)

Uploaded Source

Built Distribution

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

truthchain-1.0.1-py3-none-any.whl (11.1 kB view details)

Uploaded Python 3

File details

Details for the file truthchain-1.0.1.tar.gz.

File metadata

  • Download URL: truthchain-1.0.1.tar.gz
  • Upload date:
  • Size: 11.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.2

File hashes

Hashes for truthchain-1.0.1.tar.gz
Algorithm Hash digest
SHA256 55e61838e43fdfdcd3be2dd5808a080f0c70c483f79592141da19190cf67908f
MD5 5040997fe35157dfee9854bb9a6db1f3
BLAKE2b-256 fe4e12c7b356b5a085f53e480ae38ddbbe55128bacae4255c1cc2ab18e03128b

See more details on using hashes here.

File details

Details for the file truthchain-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: truthchain-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 11.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.14.2

File hashes

Hashes for truthchain-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 5af76caf0d0d202ead4c0a1cc9a30d8039f7ca990a175a5a1107ca1e664dc5d3
MD5 ff89326908ed53a0109c89384f6e5e72
BLAKE2b-256 6ed516d0d506a8c64c7c1d44a8f7a17d521a1ba3c89b2347a9931888c1bd34d5

See more details on using hashes here.

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