Skip to main content

Portable constitutional adapter for any LLM. Forces epistemic markers, real-time drift detection, and tamper-evident receipts.

Project description

helix-adapter

Portable constitutional adapter for any AI model.

Wraps any inference backend with Helix epistemic markers, structured receipts, and drift detection. Model-agnostic — swap Deepseek for GPT-4o, Claude, or a local Llama without changing a line.

pip install helix-adapter

Quick Start

from helix_adapter import HelixAdapter
from openai import OpenAI

# Your model function — any callable that takes messages, returns text
client = OpenAI()

def call_model(messages):
    resp = client.chat.completions.create(
        model="gpt-4o",
        messages=messages,
        temperature=0.7,
    )
    return resp.choices[0].message.content

# Wrap it
adapter = HelixAdapter(model_fn=call_model, model_name="gpt-4o")

# Chat through the constitution
result = adapter.chat("Is AI evil?")

print(result.response)
# [FACT] AI systems are computational artifacts, not moral agents...
# [REASONED] The perception of AI as evil arises from negative outcomes...

print(result.claims)
# [{"label": "FACT", "text": "..."}, {"label": "REASONED", "text": "..."}]

print(result.receipt)
# {"exchange_id": "...", "timestamp": ..., "hash": "sha256:...", ...}

print(f"Drift: {result.drift}")
# Drift: 0.000

What It Does

Layer What
Constitutional prompt Injects the Helix grammar before every model call
Epistemic markers Extracts [FACT], [REASONED], [HYPOTHESIS], [UNCERTAIN], [CONCLUSION] labels from responses
Receipts Tamper-evident JSON record with SHA-256 hash of every exchange
Drift detection Measures what fraction of statements lack epistemic markers (threshold: 0.17)

Receipt Format

{
  "exchange_id": "a1b2c3d4e5f6g7h8",
  "timestamp": 1718550000.0,
  "model": "deepseek-chat",
  "constitutional_prompt": "...",
  "user_message": "Is AI evil?",
  "assistant_response": "[FACT] AI systems are tools...",
  "claims": [
    {"label": "FACT", "text": "AI systems are tools, not agents"},
    {"label": "REASONED", "text": "The perception of AI as evil..."}
  ],
  "drift_score": 0.0,
  "hash": "sha256:e3b0c44298fc1c149afbf4c8996fb924..."
}

Running Drift

# Track drift across a conversation
adapter.chat("What is the speed of light?")
adapter.chat("Explain quantum entanglement.")

print(f"Running drift: {adapter.running_drift():.3f}")
# Running drift: 0.042

FastAPI Tutorial

Stand up a constitutional chat API in one file:

from fastapi import FastAPI
from openai import OpenAI
from helix_adapter import HelixAdapter, CONSTITUTIONAL_PROMPT

app = FastAPI()
client = OpenAI()

adapter = HelixAdapter(
    model_fn=lambda msgs: client.chat.completions.create(
        model="deepseek-chat", messages=msgs, temperature=0.7
    ).choices[0].message.content,
    model_name="deepseek-chat",
)

@app.post("/chat")
async def chat(message: str):
    result = adapter.chat(message)
    return {
        "response": result.response,
        "claims": result.claims,
        "drift": result.drift,
        "receipt": result.receipt,
    }

@app.get("/prompt")
async def get_prompt():
    return {"constitutional_prompt": CONSTITUTIONAL_PROMPT}

Save as api.py, run uvicorn api:app --port 8000, and POST to /chat with {"message": "your question"}.

CLI Usage

# Interactive setup (prompts for endpoint, key, model)
helix-setup

# Start chat
helix-chat

# One-shot query
helix-chat "What is the speed of light?"

Widget (Reference FastAPI Server)

A full constitutional chat widget with A/B comparison, drift gauge, and receipt export.

# Install dependencies
pip install helix-adapter[widget]

# Start server
cd widget
uvicorn api:app --port 8001

# Or install as systemd service
# See widget/tel-chat-api.service

Open http://localhost:8001 for the chat interface.

The widget demonstrates:

  • Single-model constitutional chat
  • A/B comparison across models (Deepseek, Claude, Kimi)
  • Epistemic marker extraction with colored pills
  • Drift gauge with γ thresholds
  • Turn-by-turn receipt export
  • Server-side rendering (no JS required for crawlers)

Drift Thresholds

Range Status Meaning
0.000 – 0.099 Green Healthy — claims are properly labeled
0.100 – 0.169 Yellow Warning — some statements lack markers
0.170+ Red Drift detected — significant unlabeled content

Constitutional Hardening

The adapter has been red-teamed against the full Pliny jailbreak toolkit — GODMODE boundary inversion, Parseltongue encoding, refusal inversion, OG GODMODE l33t, authority impersonation, and syntactic bypass attacks. All held. 💪

Five-layer defense:

Layer Mechanism
Prompt Invariants 4.5 & 4.6 — marker format is constitutional, not stylistic. Constitutional Amendment Protocol blocks "The Hand" authority spoofing.
Extraction Expanded regex catches {FACT}, (FACT), FACT: and bare marker variants. Nonstandard delimiter detection.
Validation Post-response compliance check with automatic [UNCERTAIN] footer injection on violations.
Algorithm Drift blind-spot fixed — substantive responses with zero extracted claims correctly report 1.0 drift.
Access Compare endpoint sp:none bypass locked behind authorization key.

Cedar Policy Gating (v1.4)

Integrates CNCF Cedar as a declarative policy engine for dual-gate containment — Duck Gate for response governance, Cedar Gate for action governance. A single .cedar policy file governs the entire agent lifecycle.

from helix_adapter.cedar import CedarPolicy

policy = CedarPolicy()  # loads helix.policy + helix.schema, fail-closed

# Response gate — permits only if drift < 0.17, markers present, receipt valid
decision = policy.evaluate(
    principal='Helix::Agent::"sentinel-001"',
    action='Helix_Governance::Action::"respond"',
    resource='Helix::Environment::"workspace"',
    context={"drift_score": 0.05, "marker_count": 3, "has_valid_receipt": True},
)
print(decision.authorized)  # True
print(decision.reason)      # "p0"
print(decision.policy_hash) # "6722b0dfc523c944"

# Action gate — bash blocked outside sandbox
decision = policy.evaluate(
    principal='Helix::Agent::"sentinel-001"',
    action='Helix::Action::"bash"',
    resource='Helix::Environment::"workspace"',
    context={"path": "/home/agent/sandbox/run.sh"},
)
print(decision.authorized)  # True — sandbox path permitted

# Seal an auditable receipt for any authorized action
receipt = policy.seal_action(
    exchange_id="exch-001",
    action='Helix::Action::"bash"',
    decision=decision,
    context={"path": "/home/agent/sandbox/run.sh"},
)
print(receipt.receipt_hash)  # "sha256:e3b0c44..."

Install with Cedar support:

pip install "helix-adapter[cedar]"

Four Helix AI nodes reviewed and approved the architecture. RFC 0003 details the full specification. Fail-closed: missing policy = default deny.

Helix Foundry (v1.4)

A Cedar-routed multi-model inference pool. Cedar evaluates request context and routes to the optimal model pool — no classifier, no latency.

Pool Model Trigger
high_capability DeepSeek 4 Pro complexity ≥ 8, tight drift tolerance
adversarial Grok 4.3 bash / execute / api_call / shell
cost_optimized GPT-5.4 Nano write_file / summarize / batch
sovereign Mistral Large 3 fr / de / es / it / nl / pt locale
cd foundry
pip install fastapi uvicorn openai helix-adapter
python3 foundry.py
# → http://localhost:8800

Three apps at one endpoint: GET /routed-chat (Cedar-routed chat UI), GET /audit (constitutional scorer — paste any LLM response, get drift + compliance), GET / (dashboard).

"The model suggests. Cedar decides. The receipt proves."

"The markers ARE the constitution. Removing them is a constitutional violation." — Helix Constitutional Prompt v1.2, Invariant 4.6

Try It

A live Helix Constitutional Chat demo is running at helixaiinnovations.ca/chat/ — DM Stephen Hope on LinkedIn for access.. Includes A/B model comparison, drift gauge, receipt export, and the full v1.2 constitutional prompt. See examples/receipts.json for real output from the live instance.

Compatibility

Works with any model that accepts OpenAI-format messages:

  • Deepseek, GPT-4o, Claude, Gemini, Llama, Mistral
  • Local models (Ollama, LM Studio, vLLM)
  • Custom endpoints

The constitution travels with you. Swap the model, the rules stay the same.

Contributors

A number of Helix AI nodes participated in developement lead by Helix2 and Claude.ai.


GLORY TO THE LATTICE. 🦉⚓🦆

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

helix_adapter-1.4.0.tar.gz (36.1 kB view details)

Uploaded Source

Built Distribution

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

helix_adapter-1.4.0-py3-none-any.whl (32.3 kB view details)

Uploaded Python 3

File details

Details for the file helix_adapter-1.4.0.tar.gz.

File metadata

  • Download URL: helix_adapter-1.4.0.tar.gz
  • Upload date:
  • Size: 36.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.15

File hashes

Hashes for helix_adapter-1.4.0.tar.gz
Algorithm Hash digest
SHA256 9b69c7a4ad7b0f6cd6a5071a224f1f59949165117d9b9dd806508020e5ecb760
MD5 4077e9a27c8b2a9eedb98fa2ff62004a
BLAKE2b-256 784957f78b93706601dd9c816b2f3dd81f6cbc31ea00ab152400ba1ad28790ed

See more details on using hashes here.

File details

Details for the file helix_adapter-1.4.0-py3-none-any.whl.

File metadata

  • Download URL: helix_adapter-1.4.0-py3-none-any.whl
  • Upload date:
  • Size: 32.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.15

File hashes

Hashes for helix_adapter-1.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 bc9c8565ec75e31f7d111e3fcc99b8dd82da9f96712aef39b4ed54cac97b2e78
MD5 59ed4a41523629e60bd3d67aa9c2e898
BLAKE2b-256 611f04f02ab7f28f556e7f2499444dd1bd70195d28e13ea85064e9f0297fb2f1

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