Skip to main content

Deterministic Neuro-Symbolic Guardrails for Enterprise AI.

Project description

PyPI Version Tests Python License Z3

AxiomGuard

Mathematical Logic Guardrails for LLMs
Deterministic hallucination detection & self-correction for RAG pipelines.
Powered by Z3 Theorem Prover. Provider-agnostic. Zero false positives.

Why AxiomGuard?InstallationQuickstartSelf-CorrectionLLM BackendsAPI ReferenceArchitectureContributing


Why AxiomGuard?

Standard RAG pipelines retrieve context using vector similarity — but vectors encode similarity, not truth:

"The company is in Bangkok"     →  vector A
"The company is in Chiang Mai"  →  vector B

cosine_similarity(A, B) = 0.96  ← Almost identical — but logically contradictory!

AxiomGuard adds a mathematically rigorous verification layer that catches what vectors miss.

Feature AxiomGuard Prompt-based checks Embedding filters
Deterministic (zero false positives) Yes No No
Explainable (proof trace, not vibes) Yes No No
Self-correcting (auto-fix hallucinations) Yes No No
Zero token cost for verification Yes No Yes
Latency ~10ms 500ms+ ~10ms
Provider-agnostic Yes Varies N/A

When AxiomGuard says it's a hallucination, it's a mathematical proof — not a guess.


Installation

pip install axiomguard

With LLM backends:

pip install "axiomguard[anthropic]"   # Claude
pip install "axiomguard[openai]"      # GPT-4o
pip install "axiomguard[all]"         # Everything + vector DBs

Quickstart

1. Verify a Response (3 lines)

from axiomguard import verify

result = verify("The company is in Chiang Mai", ["The company is in Bangkok"])
print(result.is_hallucinating)  # True
print(result.reason)            # Z3 proved contradiction (UNSAT): ...

2. YAML Rules + Knowledge Base

Create company.axiom.yml:

axiomguard: "0.3"
domain: company_facts

entities:
  - name: company
    aliases: ["firm", "org"]

rules:
  - name: hq_location
    type: unique
    entity: company
    relation: location
    value: Bangkok
    severity: error
    message: "HQ is Bangkok  not negotiable."

  - name: ceo_identity
    type: unique
    entity: company
    relation: ceo
    value: Somchai
    severity: error
    message: "CEO is Somchai."
from axiomguard import KnowledgeBase, verify_with_kb

kb = KnowledgeBase("company.axiom.yml")
result = verify_with_kb("The CEO is John and the company is in Chiang Mai", kb)
print(result.is_hallucinating)   # True
print(result.violated_rules)     # [hq_location, ceo_identity]

3. Self-Correction Loop (Auto-Fix Hallucinations)

from axiomguard import KnowledgeBase, generate_with_guard

kb = KnowledgeBase("company.axiom.yml")

result = generate_with_guard(
    prompt="Tell me about the company",
    kb=kb,
    llm_generate=my_llm_function,  # any (str) -> str callable
    max_retries=2,
)

print(result.status)    # "verified" | "corrected" | "failed"
print(result.response)  # The verified (or best-effort) response
print(result.attempts)  # How many tries it took

Detects hallucination → builds correction prompt with Z3 proof → regenerates → re-verifies. 88% cumulative fix rate after 2 retries at ~$0.02/correction.


Self-Correction Loop

AxiomGuard v0.5.0 evolves from a static guardrail into a self-healing agent:

User Prompt + KnowledgeBase
    │
    ▼
┌──────────────┐
│ LLM Generate │  attempt 1
└──────┬───────┘
       │
       ▼
┌──────────────┐
│ Extract Claims│  multi-claim SRO extraction
└──────┬───────┘
       │
       ▼
┌──────────────┐
│ Z3 Verify    │  YAML rules + axiom facts
└──────┬───────┘
       │
  ┌────┴────┐
  │         │
 SAT      UNSAT
  │         │
  ▼         ▼
DONE   Build Correction Prompt
       (include Z3 proof trace)
              │
              ▼
         Retry (max 2)

Three-layer fail-safe: max_retries + timeout_seconds + optional max_tokens_budget.


LLM Backends

AxiomGuard is provider-agnostic. The Z3 engine is always the same — only the NL-to-Logic translator changes.

Anthropic (Claude)

import axiomguard
from axiomguard.backends.anthropic_llm import anthropic_translator

axiomguard.set_llm_backend(anthropic_translator)
result = axiomguard.verify("The company is in Chiang Mai", ["The company is in Bangkok"])

OpenAI (GPT-4o)

import axiomguard
from axiomguard.backends.openai_llm import openai_translator

axiomguard.set_llm_backend(openai_translator)

Local LLMs (Ollama / vLLM)

from axiomguard.backends.generic_http_llm import create_http_translator

axiomguard.set_llm_backend(create_http_translator(model="llama3.1"))

Custom Backend

def my_backend(text: str) -> dict:
    return {"subject": "company", "relation": "location", "object": "Bangkok"}

axiomguard.set_llm_backend(my_backend)

API Reference

Core Verification

Function Description
verify(response, axioms) Verify against inline axiom strings
verify_with_kb(response, kb) Verify against a KnowledgeBase
verify_chunks(chunks, kb) Verify & annotate RAG chunks
generate_with_guard(prompt, kb, llm_generate) Self-correcting generation loop
extract_claims(text) Extract SRO triples from text
translate_to_logic(text) Single NL → SRO triple

Configuration

Function Description
set_llm_backend(backend) Swap NL-to-Logic provider
set_entity_resolver(resolver) Custom entity normalization
set_knowledge_base(kb) Set default KnowledgeBase
load_rules(path) Load .axiom.yml rules

Data Models

Class Description
Claim Subject-Relation-Object triple (Pydantic validated)
VerificationResult Z3 proof output: is_hallucinating, reason, violated_rules
CorrectionResult Self-correction output: status, response, attempts, history
KnowledgeBase YAML rule loader & manager

Architecture

axiomguard/
├── __init__.py              # Public API (clean re-exports)
├── core.py                  # Orchestration: extraction → resolution → Z3
├── z3_engine.py             # Z3 SMT solver: formal contradiction proofs
├── models.py                # Claim, VerificationResult, CorrectionResult
├── knowledge_base.py        # YAML rule loading & KnowledgeBase
├── parser.py                # .axiom.yml → rule objects
├── correction.py            # Self-correction prompt builder
├── resolver.py              # Entity normalization (fuzzy matching)
├── integration.py           # Vector DB integration (Chroma, Qdrant)
└── backends/
    ├── anthropic_llm.py     # Claude
    ├── openai_llm.py        # GPT-4o
    └── generic_http_llm.py  # Ollama / vLLM / any OpenAI-compatible

Design Principles

  1. ML handles language, Math handles truth. Neither modifies the other.
  2. Never alter the embedding space. Verification is a separate layer.
  3. Provider-agnostic. Swap LLM backends in one line. Z3 is always the judge.
  4. Zero false positives. When Z3 returns UNSAT, the contradiction is proven.

Roadmap

  • v0.1.0 — Z3 engine, SRO triples, multi-provider backends
  • v0.2.0 — Multi-claim extraction, entity resolution, fuzzy matching
  • v0.3.0 — KnowledgeBase, explainable proof traces, YAML rules
  • v0.4.0 — Selective verification, numeric/date rules, vector DB integration
  • v0.5.0 — Self-correction loop, auto-fix hallucinations
  • v0.6.0 — Negation handling, temporal logic
  • v0.7.0 — Advanced rule types (comparisons, cardinality)
  • v0.8.0 — Performance optimization, caching, parallel verification
  • v0.9.0 — Benchmarking against real-world hallucination datasets
  • v1.0.0 — Production-grade release

Contributing

git clone https://github.com/witchwasin/AxiomGuard.git
cd AxiomGuard
pip install -e ".[all,dev]"
pytest tests/

Areas where contributions are especially valuable:

  • Better NL-to-Logic translation — entity normalization, multi-claim extraction
  • New relation types — numeric comparisons, temporal logic, negation
  • Vector DB integrations — Pinecone, Weaviate, Milvus
  • Benchmarks — test against real-world hallucination datasets
  • New LLM backends — Gemini, Mistral, Cohere

All ideas, feedback, and PRs are welcome.


License

MIT License. See LICENSE.


Built by Witchwasin K. — proving that AI should prove its answers.

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

axiomguard-0.5.0.tar.gz (56.0 kB view details)

Uploaded Source

Built Distribution

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

axiomguard-0.5.0-py3-none-any.whl (42.4 kB view details)

Uploaded Python 3

File details

Details for the file axiomguard-0.5.0.tar.gz.

File metadata

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

File hashes

Hashes for axiomguard-0.5.0.tar.gz
Algorithm Hash digest
SHA256 e59bcf97b198f70857aae444b27abcf796a6ba79e2b15b7fc09eb1256b4201d0
MD5 f80120b2704f9b065499851ef42ade70
BLAKE2b-256 5307bfe38f1896972c85870de45be64a882489b64ecc5c48260a5516a414465c

See more details on using hashes here.

File details

Details for the file axiomguard-0.5.0-py3-none-any.whl.

File metadata

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

File hashes

Hashes for axiomguard-0.5.0-py3-none-any.whl
Algorithm Hash digest
SHA256 e8a41abb043d9ff5cf6fa6721540f5db9c29e8e635231cac59752980b8e12f72
MD5 678d5d893bb95e396f1a3d645dd6b00e
BLAKE2b-256 613cc71ee93d85b2f6d50dce00fe4b264e98f7d52d3667396f549ae93394c895

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