Skip to main content

Professional Python SDK for Zero Point Logic Engine API

Project description

ZPL Engine Python SDK

Professional Python client library for the Zero Point Logic (ZPL) Engine API — a mathematical platform for AI Neutrality Index (AIN) analysis and stability calculations.

Python Version License: MIT

Features

  • Sync and Async clients — Both ZPLClient (requests) and AsyncZPLClient (httpx) for maximum flexibility
  • AI Neutrality Index (AIN) — Analyze bias and stability in any binary matrix data
  • Comprehensive error handling — Specialized exceptions for auth, quota, rate limits, validation
  • Retry logic — Exponential backoff for resilient network requests
  • Type hints — Full type safety with Python 3.9+ compatibility
  • Production-grade — Structure and quality comparable to OpenAI Python SDK
  • Rich utilities — Matrix conversion from prices, timeseries, pandas DataFrames
  • Detailed documentation — Docstrings, examples, and type information throughout

v2.0.0 — BREAKING + REQUIRED UPGRADE

v1.x sent {matrix, samples} to the engine, which the Rust API rejected with 400 Failed to deserialize: missing field 'bias'. Every single v1.x call failed on the wire. v2.0.0 fixes the body shape and is the first working release.

Upgrade immediately: pip install -U zeropointlogic

Public API surface (client.compute(matrix=..., samples=...)) is unchanged. Under the hood the SDK now derives d = len(matrix) and bias = sum_of_1s / (d * d) client-side, then posts {d, bias, samples} to the engine.

Step 1 — Get an API key (DO THIS FIRST)

This SDK is a thin HTTP client. It does NOT log you in, register an account, or mint a key for you. Calling client.compute(...) without a valid zpl_u_… user key returns 401 Unauthorized immediately.

You must obtain a key first, by ONE of these three paths:

1. Dashboard (recommended for server / app use)

  1. Visit https://zeropointlogic.io/auth/register and create an account. Free plan = 5,000 tokens/month, no credit card.
  2. Verify your email by clicking the link we send.
  3. Open https://zeropointlogic.io/dashboard/api-keys, click Create New Key, give it a name, hit Generate.
  4. Copy the plaintext key now — the dashboard shows it once. Format: zpl_u_ + 48 hex chars (54 chars total).

2. CLI (local dev)

npm install -g zpl-engine-cli
zpl login

Browser-based device flow; the key lands in ~/.zpl/config.toml. Export:

export ZPL_API_KEY="$(awk -F\" '/api_key/{print $2}' ~/.zpl/config.toml)"

3. MCP wizard (Claude Desktop / Cursor / Windsurf)

npx zpl-engine-mcp setup

Step 2 — Pass the key to the SDK

import os
from zeropointlogic import ZPLClient

# Preferred — env var for servers + CI
client = ZPLClient(api_key=os.environ["ZPL_API_KEY"])

# One-off scripts:
client = ZPLClient(api_key="zpl_u_…")

Treat zpl_u_… like an OpenAI / Stripe secret — never embed in client code, mobile binaries, or public Jupyter notebooks. Use a real secrets manager (AWS SM, Vault, Doppler, …) in production.

Installation

Basic Install

pip install zeropointlogic

With Async Support

pip install zeropointlogic[async]

With pandas Support

pip install zeropointlogic[pandas]

Development Install

git clone https://github.com/cicicalex/zpl-engine-sdk.git
cd zpl-engine-sdk/packages/python
pip install -e ".[dev]"

API key: this library does not run a browser login. Obtain a zpl_u_… key from the ZPL Main dashboard (API keys), or use zpl login (zpl-engine-cli) / npx zpl-engine-mcp setup (zpl-engine-mcp) for device-flow bootstrap, then set ZPL_API_KEY (or read from ~/.zpl/config.toml on your dev machine only).

Game backends (Unity, Godot, Unreal, …)

Use this SDK from Python workers (matchmaking, live ops, batch jobs). Game clients still should not hold long-lived keys; call the engine from your server. For multi-engine HTTP notes and the web demo catalog, see docs/games/README.md in this repository.

Quick Start

Basic Usage (Synchronous)

from zeropointlogic import ZPLClient, matrix_from_prices

# Initialize client
client = ZPLClient(api_key="zpl_xxx")

# Compute AIN for a binary matrix
matrix = [[0, 1, 0], [1, 0, 1], [0, 1, 0]]
result = client.compute(matrix=matrix, samples=1000)

print(f"AIN Score: {result.ain:.3f}")
print(f"Status: {result.status}")
print(f"Is neutral? {result.is_neutral()}")
print(f"Tokens remaining: {result.tokens_remaining}")

Context Manager

from zeropointlogic import ZPLClient

with ZPLClient(api_key="zpl_xxx") as client:
    result = client.compute(matrix=[[0, 1], [1, 0]], samples=500)
    print(f"Result: {result}")

Async Usage

import asyncio
from zeropointlogic import AsyncZPLClient

async def main():
    async with AsyncZPLClient(api_key="zpl_xxx") as client:
        result = await client.compute(matrix=[[0, 1], [1, 0]], samples=1000)
        print(f"AIN: {result.ain:.3f}")

asyncio.run(main())

Working with Prices

from zeropointlogic import ZPLClient, matrix_from_prices

# Convert price series to binary matrix
prices = [100, 105, 102, 110, 108, 115, 112]
matrix = matrix_from_prices(prices, window=3)

client = ZPLClient(api_key="zpl_xxx")
result = client.compute(matrix=matrix, samples=500)
print(f"Price distribution bias: {result.ain:.3f}")

Batch Processing

from zeropointlogic import ZPLClient

client = ZPLClient(api_key="zpl_xxx")

# Process multiple matrices
matrices = [
    [[0, 1], [1, 0]],
    [[1, 1], [0, 0]],
    [[0, 0], [1, 1]],
]

results = client.batch_compute(matrices, samples=500)

for i, result in enumerate(results):
    print(f"Matrix {i}: AIN={result.ain:.3f}, Status={result.status}")

API Usage Monitoring

from zeropointlogic import ZPLClient

client = ZPLClient(api_key="zpl_xxx")

# Get current usage
usage = client.get_usage()
print(f"Plan: {usage.plan}")
print(f"Usage: {usage.usage_percent:.1f}%")
print(f"Tokens remaining: {usage.tokens_remaining}")

# Get available plans
plans = client.get_plans()
for plan in plans:
    print(f"{plan.name}: {plan.tokens_per_month:,} tokens/mo")

# Check engine health
health = client.get_health()
print(f"Status: {health.status}")
print(f"Uptime: {health.uptime_percent:.2f}%")

Data Models

ComputeResult

result = client.compute(matrix, samples=1000)

# Properties
result.ain: float                    # AI Neutrality Index (0-1)
result.p_output: float              # Probability output
result.deviation: float             # Standard deviation
result.status: AIStatusType         # CERTIFIED_NEUTRAL | STABLE | MODERATE_BIAS | HIGH_BIAS | CRITICAL_BIAS
result.tokens_used: int             # Tokens consumed
result.tokens_remaining: int        # Tokens left
result.matrix_size: int             # N (for N×N matrix)
result.samples: int                 # Sample count used

# Methods
result.is_neutral(threshold=0.7)    # Check if AIN >= threshold
result.is_stable()                  # Check if status is neutral/stable
result.has_bias()                   # Check if status contains BIAS

UsageInfo

usage = client.get_usage()

usage.plan: str                     # Current plan name
usage.tokens_used: int              # Tokens used this period
usage.tokens_limit: int             # Total tokens available
usage.tokens_remaining: int         # Tokens left
usage.usage_percent: float          # Usage as percentage
usage.is_unlimited: bool            # True if plan is unlimited
usage.requests_made: int            # API requests made
usage.reset_date: str               # When tokens reset

PlanInfo

plans = client.get_plans()
plan = plans[0]

plan.name: str                      # Plan name
plan.tokens_per_month: int          # Monthly token allowance
plan.price_usd: float               # USD price
plan.price_eur: float               # EUR price
plan.features: list[str]            # Included features

plan.is_free()                      # Check if free tier

HealthStatus

health = client.get_health()

health.status: str                  # "up" | "degraded" | "down"
health.uptime_percent: float        # Uptime percentage
health.response_time_ms: float      # Avg response time
health.requests_per_second: float   # Current RPS
health.error_rate_percent: float    # Error rate
health.version: str                 # Engine version

health.is_healthy()                 # Check if up and >99% uptime

Utility Functions

Matrix Conversion

from zeropointlogic import (
    matrix_from_prices,
    matrix_from_timeseries,
    matrix_from_dataframe,
    normalize_matrix,
    create_random_matrix,
)

# From price series
prices = [100, 105, 102, 110]
matrix = matrix_from_prices(prices, window=2)

# From timeseries (with binning)
values = [1.2, 3.4, 2.1, 4.5, 3.2]
matrix = matrix_from_timeseries(values, bins=3, method="quantile")

# From pandas DataFrame
import pandas as pd
df = pd.DataFrame({"price": [100, 105, 102], "volume": [1000, 1500, 1200]})
matrix = matrix_from_dataframe(df, "price", "volume")

# Normalize existing matrix
matrix = normalize_matrix([[0, 2], [3, 1]])  # -> [[0, 1], [1, 1]]

# Create random matrix
matrix = create_random_matrix(size=5, density=0.5)

Interpretation

from zeropointlogic import interpret_ain, get_status_color

# Get human-readable AIN interpretation
short = interpret_ain(0.75, "short")       # "Excellent"
medium = interpret_ain(0.75, "medium")    # "Highly Neutral"
long = interpret_ain(0.75, "long")        # Full explanation

# Get status color for UI/visualization
color = get_status_color("STABLE")        # "green"

Validation

from zeropointlogic import validate_matrix, chunk_matrices

# Validate matrix format
is_valid, error_msg = validate_matrix([[0, 1], [1, 0]])
if is_valid:
    print("Matrix is valid")
else:
    print(f"Error: {error_msg}")

# Split matrices into chunks for batch processing
large_list = [matrix1, matrix2, matrix3, matrix4, matrix5]
chunks = chunk_matrices(large_list, chunk_size=2)
for chunk in chunks:
    results = client.batch_compute(chunk, samples=500)

Error Handling

from zeropointlogic import (
    ZPLClient,
    ZPLError,
    ZPLAuthError,
    ZPLQuotaError,
    ZPLRateLimitError,
    ZPLValidationError,
    ZPLNetworkError,
)

client = ZPLClient(api_key="zpl_xxx")

try:
    result = client.compute(matrix=[[0, 1], [1, 0]], samples=1000)
except ZPLAuthError:
    print("Invalid API key")
except ZPLQuotaError as e:
    print(f"Quota exceeded. Tokens remaining: {e.tokens_remaining}")
except ZPLRateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
except ZPLValidationError as e:
    print(f"Validation error: {e.message}")
except ZPLNetworkError:
    print("Network connection failed")
except ZPLError as e:
    print(f"API error: {e.message}")

Configuration

Custom Base URL

client = ZPLClient(
    api_key="zpl_xxx",
    base_url="https://engine.zeropointlogic.io"  # default
)

Timeout and Retries

client = ZPLClient(
    api_key="zpl_xxx",
    timeout=30,              # Request timeout in seconds (default 30)
    max_retries=3,           # Max retry attempts (default 3)
    backoff_factor=0.5       # Exponential backoff multiplier (default 0.5)
)

Examples

See the examples/ directory for complete examples:

  • crypto_bias.py — Analyze cryptocurrency price distributions
  • game_economy.py — Analyze game item balance and drop rates
  • forex_stability.py — Analyze forex pair stability and detect market regimes

Run examples:

export ZPL_API_KEY="zpl_your_key_here"
python examples/crypto_bias.py
python examples/game_economy.py
python examples/forex_stability.py

API Plans and Pricing

Plan Tokens/Month Price USD Price EUR
Free 100 $0 €0
Basic 10,000 $10 €9
Pro 50,000 $29 €27
GamePro 150,000 $69 €63
Studio 500,000 $149 €137
Agent 2,000,000 $199 €183
Enterprise 10,000,000 $499 €459
XL Unlimited $999 €919

1 token = 1 compute operation

API Endpoints

POST /compute

Analyze a binary matrix for AI Neutrality Index.

Request:

{
  "matrix": [[0, 1, 0], [1, 0, 1], [0, 1, 0]],
  "samples": 1000
}

Response:

{
  "ain": 0.73,
  "p_output": 0.51,
  "deviation": 0.12,
  "status": "STABLE",
  "tokens_used": 1,
  "tokens_remaining": 9999
}

GET /usage

Get current API usage for authenticated key.

Response:

{
  "plan": "pro",
  "tokens_used": 5000,
  "tokens_limit": 50000,
  "tokens_remaining": 45000,
  "reset_date": "2026-05-06",
  "requests_made": 150,
  "last_reset": "2026-04-06"
}

GET /plans

Get available pricing plans.

Response:

{
  "plans": [
    {
      "name": "Free",
      "tokens_per_month": 100,
      "price_usd": 0.0,
      "price_eur": 0.0,
      "features": ["API access", "5 requests/min"]
    }
  ]
}

GET /health

Check engine health and performance.

Response:

{
  "status": "up",
  "uptime_percent": 99.95,
  "response_time_ms": 45.2,
  "requests_per_second": 150.5,
  "error_rate_percent": 0.05,
  "version": "1.2.3"
}

Authentication

All API requests require authentication via the X-API-Key header:

X-API-Key: zpl_u_<48_hex_digits_from_dashboard>

Use a user API key (zpl_u_…) from the dashboard — not a service key (zpl_s_…, server-side only). The SDK sends this header on authenticated calls. Obtain a key at: https://zeropointlogic.io/dashboard/api-keys

Testing

Run the test suite:

# All tests
pytest

# With coverage
pytest --cov=zeropointlogic

# Specific test file
pytest tests/test_client.py

# Specific test
pytest tests/test_client.py::TestZPLClientCompute::test_compute_success

Development

Code Style

# Format with black
black zeropointlogic/

# Sort imports
isort zeropointlogic/

# Lint with flake8
flake8 zeropointlogic/

# Type checking
mypy zeropointlogic/

License

MIT License — See LICENSE file for details.

Support

Changelog

v1.0.0 (2026-04-06)

  • Initial release
  • Sync and async client implementations
  • Full API endpoint coverage
  • Comprehensive error handling
  • Rich utility functions
  • Production-grade documentation
  • Test suite with good coverage
  • Multiple usage examples

Contributing

Contributions welcome! Please:

  1. Fork the repository
  2. Create a feature branch
  3. Add tests for new functionality
  4. Run the test suite
  5. Submit a pull request

Acknowledgments

Built by Alex for the Zero Point Logic platform.

Inspired by the OpenAI Python SDK architecture for professional quality and usability.

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

zeropointlogic-2.0.6.tar.gz (36.0 kB view details)

Uploaded Source

Built Distribution

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

zeropointlogic-2.0.6-py3-none-any.whl (26.5 kB view details)

Uploaded Python 3

File details

Details for the file zeropointlogic-2.0.6.tar.gz.

File metadata

  • Download URL: zeropointlogic-2.0.6.tar.gz
  • Upload date:
  • Size: 36.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for zeropointlogic-2.0.6.tar.gz
Algorithm Hash digest
SHA256 0eaf832d46a193d7dd9fadb051e3959f7faedf135908d973323032b325ce3b50
MD5 3fa0c721e4ec577762deb1cbffb62d0a
BLAKE2b-256 99e407e6afc5f037fc15320c4d67c232404d92cde98fc4f628871864acd145a1

See more details on using hashes here.

File details

Details for the file zeropointlogic-2.0.6-py3-none-any.whl.

File metadata

  • Download URL: zeropointlogic-2.0.6-py3-none-any.whl
  • Upload date:
  • Size: 26.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for zeropointlogic-2.0.6-py3-none-any.whl
Algorithm Hash digest
SHA256 6091396c8a9197d9fcea7488c15b60b9939439ca88ad2d248819baa60a671e8f
MD5 f007ea0287d0314fa4e5a42ab084c307
BLAKE2b-256 de9dfe709b7a0385a04c317b9ce01ea0dff8e90c97bf51e370259ca871c9ab1f

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