Skip to main content

Python SDK for Lawgorithm - AI Act Compliance Platform

Project description

Lawgorithm Python SDK

Official Python SDK for Lawgorithm - AI Act Compliance Platform.

PyPI version Python 3.10+ License: MIT

Installation

pip install lawgorithm

Quick Start

from lawgorithm import LawgorithmClient

# Initialize the client
client = LawgorithmClient(
    api_url="https://api.lawgorithm.io",
    api_token="your-api-token"
)

# List your AI systems
systems = client.list_systems()
for system in systems:
    print(f"{system.name}: {system.risk_level}")

# Run compliance check
result = client.check_compliance(
    repo="myorg/myrepo",
    commit="abc123",
    branch="main"
)

print(f"Compliance rate: {result.compliance_rate * 100:.1f}%")
if result.issues:
    for issue in result.issues:
        print(f"  [{issue.severity}] {issue.message}")

Features

AI System Management

# Create a new AI system
system = client.create_system(
    name="Credit Scoring Model",
    description="ML model for credit risk assessment",
    purpose="Automated credit decisions",
    domain="finance"
)

# Classify risk level using AI
system = client.classify_system(system.id)
print(f"Risk level: {system.risk_level}")  # e.g., "high"
print(f"Justification: {system.risk_justification}")

Compliance Checks (CI/CD)

# Standard check (returns result)
result = client.check_compliance(
    repo="myorg/myrepo",
    commit="abc123",
    strict=False
)

# Strict mode (raises exception on failure)
try:
    result = client.check_compliance(
        repo="myorg/myrepo",
        commit="abc123",
        strict=True
    )
except ComplianceError as e:
    print(f"Blocked: {e.message}")
    for issue in e.issues:
        print(f"  - {issue['message']}")
    sys.exit(1)

Post-Market Surveillance (AI Act Article 72)

# Create an incident
incident = client.create_incident(
    system_id=system.id,
    title="Bias detected in predictions",
    severity="high",
    category="bias_detected",
    description="Model shows 15% higher rejection rate for protected group"
)

# Notify competent authority
incident = client.notify_authority(incident.id)

# Get incident statistics
stats = client.get_incident_stats(system.id)
print(f"Total incidents: {stats.total}")
print(f"Authority notifications: {stats.authority_notifications}")

Compliance Dossier ("Le Dossier Vivant")

# Check dossier completeness
completeness = client.check_dossier_completeness(system.id)
print(f"Complete: {completeness.overall_complete}")
print(f"Progress: {completeness.completion_percentage:.1f}%")
print(f"Missing: {completeness.missing_obligations}")

# Export full dossier
dossier = client.export_dossier(system.id, format="markdown")
with open("compliance_dossier.md", "w") as f:
    f.write(dossier.content)

Attestations (Ed25519)

# Create a signed attestation
attestation = client.create_attestation(
    system_id=system.id,
    attestation_type="CONFORMITY_DECLARATION",
    statement="This system complies with AI Act requirements",
    private_key=my_private_key,  # Ed25519 private key (base64)
    attester_org="Acme Corp",
    attester_role="DPO"
)

# Verify attestation
result = client.verify_attestation(attestation.id)
print(f"Valid: {result['valid']}")

MLOps Integration

# Import MLflow run as evidence
result = client.import_mlflow_run(
    system_id=system.id,
    tracking_uri="http://mlflow.internal:5000",
    run_id="abc123def456"
)
print(f"Evidence created: {result['evidence_id']}")

# Import Weights & Biases run
result = client.import_wandb_run(
    system_id=system.id,
    entity="myteam",
    project="credit-model",
    run_id="xyz789",
    api_key="your-wandb-key"
)

Compliance State History

# Get compliance history
history = client.get_compliance_history(system.id, limit=10)
for state in history:
    print(f"{state.created_at}: {state.compliance_score:.1%} ({state.trigger})")

# Verify chain integrity (tamper detection)
result = client.verify_compliance_chain(system.id)
if result["valid"]:
    print("Chain integrity verified")
else:
    print(f"Chain broken at: {result['broken_at']}")

Context Manager

The client can be used as a context manager for automatic cleanup:

with LawgorithmClient(api_url="...", api_token="...") as client:
    systems = client.list_systems()
    # Connection is automatically closed

Error Handling

from lawgorithm import (
    LawgorithmClient,
    LawgorithmError,
    AuthenticationError,
    ComplianceError,
    NotFoundError,
    ValidationError,
)

try:
    result = client.check_compliance(strict=True)
except AuthenticationError:
    print("Invalid API token")
except NotFoundError:
    print("System not found")
except ComplianceError as e:
    print(f"Compliance failed: {len(e.issues)} issues")
except ValidationError as e:
    print(f"Invalid request: {e.errors}")
except LawgorithmError as e:
    print(f"API error [{e.status_code}]: {e.message}")

Environment Variables

You can configure the client via environment variables:

export LAWGORITHM_API_URL="https://api.lawgorithm.io"
export LAWGORITHM_API_TOKEN="your-api-token"
import os
from lawgorithm import LawgorithmClient

client = LawgorithmClient(
    api_url=os.environ.get("LAWGORITHM_API_URL", "http://localhost:8000/api"),
    api_token=os.environ.get("LAWGORITHM_API_TOKEN")
)

Requirements

  • Python 3.10+
  • httpx
  • pydantic

License

MIT License - see LICENSE for details.

Links

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

lawgorithm-0.1.0.tar.gz (10.4 kB view details)

Uploaded Source

Built Distribution

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

lawgorithm-0.1.0-py3-none-any.whl (11.0 kB view details)

Uploaded Python 3

File details

Details for the file lawgorithm-0.1.0.tar.gz.

File metadata

  • Download URL: lawgorithm-0.1.0.tar.gz
  • Upload date:
  • Size: 10.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.8

File hashes

Hashes for lawgorithm-0.1.0.tar.gz
Algorithm Hash digest
SHA256 09fc6a9d0fb77b1b577b272279a09a4b4cfc209225c8120fd1bf5f6572606e56
MD5 ac370746a890bcf16087914e48990458
BLAKE2b-256 6c495d18bd78a58082552be0147f526cc9bf87b2823f712b7043a193df4f5d35

See more details on using hashes here.

File details

Details for the file lawgorithm-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: lawgorithm-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 11.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.8

File hashes

Hashes for lawgorithm-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f25dc254c0e5f9cbf66b6eb498e3f7a9316248c3315eb47bbe1f54d28f904754
MD5 b7ed7c15c4e21f1d040772ca219a6a86
BLAKE2b-256 257cc609f6b1b65643af439fc87e9e497c15795933f90ffb7aad6e76b3a929a2

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