Skip to main content

Z3 SMT verification engine for LLM compliance

Project description

aare-core

Core verification engine for aare.ai - Z3 SMT solver for LLM compliance verification.

PyPI version

Overview

aare-core provides formal verification (Z3 SMT solver) to validate LLM outputs against structured constraints. The key innovation is the Formula Compiler - constraints are defined entirely in JSON, with no code changes needed.

JSON Formula → Formula Compiler → Z3 Expression → Formal Verification

This is the core library used by all cloud deployments:

Installation

pip install aare-core

Quick Start

As a Library

from aare_core import FormulaCompiler, LLMParser, SMTVerifier, OntologyLoader

# Load ontology (verification rules)
loader = OntologyLoader()
ontology = loader.load("example")

# Parse LLM output
parser = LLMParser()
data = parser.parse("The value is 50, option A is selected.", ontology)

# Verify against constraints
verifier = SMTVerifier()
result = verifier.verify(data, ontology)

print(result["verified"])  # True or False
print(result["violations"])  # List of constraint violations

With Docker (Self-hosted Server)

# Clone the repository
git clone https://github.com/aare-ai/aare-core.git
cd aare-core

# Start with Docker Compose
docker-compose up -d

# Verify it's running
curl http://localhost:8080/health

Run Server Directly

# Clone and install
git clone https://github.com/aare-ai/aare-core.git
cd aare-core
pip install -e .
pip install flask gunicorn

# Run
python app.py
# or with gunicorn
gunicorn --bind 0.0.0.0:8080 app:app

Architecture

┌─────────────────────────────────────────────────────────────────┐
│                     aare.ai Framework                            │
│  ┌─────────────────────────────────────────────────────────┐   │
│  │                    /verify endpoint                      │   │
│  │  ┌──────────┐  ┌──────────┐  ┌────────────────────┐     │   │
│  │  │   LLM    │→ │ Ontology │→ │   Z3 SMT Verifier  │     │   │
│  │  │  Parser  │  │  Loader  │  │  + Formula Compiler│     │   │
│  │  └──────────┘  └──────────┘  └────────────────────┘     │   │
│  └─────────────────────────────────────────────────────────┘   │
│                              ↓                                  │
│                    Local Filesystem                             │
│                   (./ontologies/*.json)                         │
└─────────────────────────────────────────────────────────────────┘

Formula Compiler

The formula compiler translates JSON constraint definitions into Z3 expressions. This enables:

  • No code changes to add new constraints
  • Domain-agnostic - works for any verification domain
  • Formally verified - mathematically provable correctness

Supported Operators

Category Operators
Logical and, or, not, implies, ite (if-then-else)
Comparison ==, !=, <, <=, >, >=
Arithmetic +, -, *, /, min, max
Constants true, false, numeric values

Formula Examples

// Simple comparison: value ≤ 100
{"<=": ["value", 100]}

// Negation: ¬prohibited
{"==": ["prohibited", false]}

// Implication: condition_a → condition_b
{"implies": [
  {"==": ["condition_a", true]},
  {"==": ["condition_b", true]}
]}

// Disjunction: option_a ∨ option_b
{"or": [
  {"==": ["option_a", true]},
  {"==": ["option_b", true]}
]}

// Complex: (dti ≤ 43) ∨ (compensating_factors ≥ 2)
{"or": [
  {"<=": ["dti", 43]},
  {">=": ["compensating_factors", 2]}
]}

// If-then-else: conditional value
{"ite": [{">": ["score", 700]}, "approved", "denied"]}

// Min/max: fee capped at lesser of $500 or 3% of loan
{"<=": ["fee", {"min": [500, {"*": ["loan", 0.03]}]}]}

API Reference

POST /verify

Verifies LLM output against compliance constraints.

curl -X POST http://localhost:8080/verify \
  -H "Content-Type: application/json" \
  -d '{
    "llm_output": "The value is 50, option A is selected.",
    "ontology": "example"
  }'

Response:

{
  "verified": true,
  "violations": [],
  "warnings": ["Variables defaulted (not found in input): ['variable_name']"],
  "parsed_data": {
    "value": 50,
    "option_a": true
  },
  "ontology": {
    "name": "example",
    "version": "1.0.0",
    "constraints_checked": 5
  },
  "proof": {
    "method": "Z3 SMT Solver",
    "version": "4.12.1"
  },
  "verification_id": "uuid",
  "execution_time_ms": 45,
  "timestamp": "2024-01-01T00:00:00Z"
}

Note: The warnings field appears when variables couldn't be extracted from the LLM output and were defaulted. This helps auditors understand verification scope.

GET /ontologies

List available ontologies.

curl http://localhost:8080/ontologies

GET /ontologies/{name}

Get a specific ontology definition.

curl http://localhost:8080/ontologies/example

GET /health

Health check endpoint.

curl http://localhost:8080/health

Creating Custom Ontologies

Create your own verification rules by adding JSON files to the ontologies/ directory.

Ontology Structure

{
  "name": "my-custom-ontology",
  "version": "1.0.0",
  "description": "Description of your ontology",
  "constraints": [
    {
      "id": "UNIQUE_CONSTRAINT_ID",
      "category": "Category Name",
      "description": "What this constraint checks",
      "formula_readable": "human-readable formula",
      "formula": {"<=": ["value", 100]},
      "variables": [
        {"name": "value", "type": "real"}
      ],
      "error_message": "Error shown when violated",
      "citation": "Reference to regulation/policy"
    }
  ],
  "extractors": {
    "value": {
      "type": "float",
      "pattern": "value[:\\s]*(\\d+(?:\\.\\d+)?)"
    }
  }
}

Variable Types

Type Z3 Type Use For
bool Bool True/false flags
int Int Whole numbers
real or float Real Decimal numbers

Extractor Types

Type Description Example
boolean True if any keyword found {"keywords": ["approved", "accepted"]}
int Extract integer from regex {"pattern": "score[:\\s]*(\\d+)"}
float Extract decimal number {"pattern": "(\\d+\\.\\d+)%"}
money Extract currency (handles k/m/b) {"pattern": "\\$([\\d,]+)k?"}
percentage Extract percentage {"pattern": "(\\d+(?:\\.\\d+)?)%"}

Configuration

Environment Variables

Variable Default Description
PORT 8080 HTTP port
ONTOLOGY_DIR ./ontologies Directory for custom ontologies
CORS_ORIGINS https://aare.ai,... Comma-separated allowed origins
DEBUG false Enable debug mode

Docker Compose Configuration

version: '3.8'

services:
  aare:
    image: ghcr.io/aare-ai/aare:latest
    ports:
      - "8080:8080"
    environment:
      - CORS_ORIGINS=https://your-domain.com
    volumes:
      - ./ontologies:/app/ontologies:ro
    restart: unless-stopped

Production Deployment

With Nginx (SSL)

server {
    listen 443 ssl;
    server_name api.yourdomain.com;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    location / {
        proxy_pass http://localhost:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

With Kubernetes

apiVersion: apps/v1
kind: Deployment
metadata:
  name: aare-ai
spec:
  replicas: 3
  selector:
    matchLabels:
      app: aare-ai
  template:
    metadata:
      labels:
        app: aare-ai
    spec:
      containers:
      - name: aare-ai
        image: ghcr.io/aare-ai/aare:latest
        ports:
        - containerPort: 8080
        env:
        - name: CORS_ORIGINS
          value: "https://your-domain.com"
        resources:
          requests:
            memory: "512Mi"
            cpu: "250m"
          limits:
            memory: "2Gi"
            cpu: "2"
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 10
          periodSeconds: 30
        readinessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 10

Integration Example

import requests

def verify_llm_output(llm_response: str, ontology: str = "example") -> dict:
    """Verify LLM output before returning to user"""
    result = requests.post(
        "http://localhost:8080/verify",
        json={
            "llm_output": llm_response,
            "ontology": ontology
        }
    ).json()

    if not result["verified"]:
        raise ComplianceError(
            f"Verification failed: {result['violations']}"
        )

    return result

# Usage
llm_output = my_llm.generate(prompt)
verification = verify_llm_output(llm_output)
if verification["verified"]:
    return llm_output

Running Tests

pip install -e ".[dev]"
pytest tests/ -v

License

MIT License - see LICENSE for details.

Support

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

aare_core-0.1.0.tar.gz (20.2 kB view details)

Uploaded Source

Built Distribution

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

aare_core-0.1.0-py3-none-any.whl (15.2 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for aare_core-0.1.0.tar.gz
Algorithm Hash digest
SHA256 7532b4514d0e8a32804f8aae8ebf773777c42928e7cf2ded8334c48fd60a02b3
MD5 7e41cb95b66e1158844621eed1690eef
BLAKE2b-256 1946a3ba6ef672b028d915c4cb46bfcf17b4e7460f4df137c8ffd73dba57583a

See more details on using hashes here.

File details

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

File metadata

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

File hashes

Hashes for aare_core-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 4ab823b1a915002825e91d906417546eb0f75dbf01c32d48069f013e99fbd7d5
MD5 cf3656ec0046b5c54f19123a7553a9ff
BLAKE2b-256 e48cc56a318384b6f818ef2116b756692de345a7db5ebe6739214c645d5f2572

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