⚛️ QSVAPS — Quantum Superposition Verification for Agent Plan Safety

PyPI License: MIT Python 3.10+ Tests Qiskit

The first framework to use Grover's quantum search as a verification oracle for AI agent plans.

Classical Generation  →  Quantum Verification  →  Classical Repair
     (LLM agent)         (Grover's algorithm)       (LLM agent)

🔴 The Problem: AI Agents Fly Blind

AI agents (LangChain, AutoGen, CrewAI) generate multi-step plans every day — chaining API calls, orchestrating tools, executing code. But here's the uncomfortable truth:

Nobody verifies these plans before execution.

A plan that looks correct step-by-step can fail catastrophically due to emergent interactions between steps:

Classical verification requires checking every possible execution scenario. For a plan with 20 decision points, that's 2²⁰ = 1,048,576 scenarios. Exhaustive checking is too slow.

🟢 The Solution: Quantum Verification

QSVAPS uses Grover's quantum search algorithm — a provably optimal quantum algorithm — to search the space of potential failures quadratically faster than any classical approach:

Scenario Classical Brute Force QSVAPS (Grover)
20 decision points (2²⁰ states) ~1,000,000 checks ~1,000 iterations
30 decision points (2³⁰ states) ~1,000,000,000 checks ~31,623 iterations
Speedup O(N) O(√N) — provably optimal

This isn't quantum for the sake of quantum. Grover's speedup is information-theoretically optimal — no classical algorithm can do better for unstructured search.

🧭 Where QSVAPS Fits

┌──────────────────────────────────────────────────────────────────────┐
│                      AI Agent Architecture                          │
├──────────────────────────────────────────────────────────────────────┤
│                                                                      │
│  ┌─────────────┐     ┌──────────────────┐     ┌──────────────────┐  │
│  │             │     │                  │     │                  │  │
│  │  LLM Agent  │────▶│     QSVAPS       │────▶│  Safe Execution  │  │
│  │  generates  │     │  verifies plan   │     │  with confidence │  │
│  │  plan       │     │  using quantum   │     │                  │  │
│  │             │     │  search          │     │                  │  │
│  └─────────────┘     └────────┬─────────┘     └──────────────────┘  │
│         ▲                     │                                      │
│         │              If violations found                           │
│         │                     │                                      │
│         └─────────────────────┘                                      │
│              LLM repairs plan                                        │
│                                                                      │
└──────────────────────────────────────────────────────────────────────┘

QSVAPS sits between plan generation and execution. It's the safety layer that catches failures before they happen — using quantum computing as a verification co-processor.

What Makes This Novel

Existing Approach QSVAPS Difference
Quantum Neural Networks Uses quantum for verification, not model training
LLM generates quantum code Quantum code enhances the agent itself
Quantum hyperparameter tuning Quantum solves a core agent bottleneck
Classical plan verification Provable quadratic speedup via Grover's algorithm

⚡ Quick Start

Install

pip install qsvaps

Run the Demo

python -m qsvaps.demo

No API keys needed — uses the Qiskit Aer simulator and a built-in mock LLM.

Use in Your Code

from qsvaps import Plan, PlanAction, ResourceConstraint, PlanVerifier

# Define your agent's plan
plan = Plan(
    name="Data Pipeline",
    actions=[
        PlanAction(name="fetch_data", description="Fetch from API", resources=["api_quota"]),
        PlanAction(name="transform", description="Transform dataset"),
        PlanAction(name="save", description="Write to database", can_fail=False),
    ],
    dependencies=[("fetch_data", "transform"), ("transform", "save")],
    resource_constraints=[ResourceConstraint("api_quota", max_concurrent=1)],
)

# Quantum verification
verifier = PlanVerifier(shots=2048)
result = verifier.verify(plan, verbose=True)

if not result.is_safe:
    print(f"Found {result.num_violations} failure modes!")
    for witness in result.witnesses:
        print(witness.explanation)

Verify & Auto-Repair with LLM

from qsvaps import PlanVerifier, LLMInterface

# Connect to any OpenAI-compatible API
llm = LLMInterface(api_key="sk-...", model="gpt-4")

# Or use the built-in mock for testing
# llm = LLMInterface(mock=True)

verifier = PlanVerifier(llm=llm, max_repair_iterations=3)
results = verifier.verify_and_repair(plan, verbose=True)

# The repaired plan is in results[-1].plan

🔬 How It Works

Step 1: Constraint Extraction

Your plan's structure is automatically analyzed to extract boolean constraints:

Plan: fetch_data → transform → save

Constraints extracted:
  C1 [DEPENDENCY]: 'transform' requires 'fetch_data' to succeed first
     Formula: (¬x₁) ∨ x₀
  C2 [DEPENDENCY]: 'save' requires 'transform' to succeed first
     Formula: (¬x₂) ∨ x₁
  C3 [COMPLETION]: 'save' must succeed
     Formula: x₂

Supported constraint types:

Step 2: Quantum Oracle Construction

Constraints are encoded as a quantum phase oracle — a circuit that flips the phase of states where any constraint is violated:

|valid⟩    →   |valid⟩     (no phase change)
|violation⟩ → -|violation⟩  (phase flipped)

Step 3: Grover's Search

Grover's algorithm amplifies the probability of measuring violation states:

                    ┌──────────┐  ┌──────────┐
|0⟩⊗ⁿ ── H⊗ⁿ ──┤  Oracle  ├──┤ Diffuser ├── × k iterations ── Measure
                    └──────────┘  └──────────┘

k = ⌊π/4 × √(N/M)⌋  where N = total states, M = violations

Step 4: Witness Decoding

Measured bitstrings are decoded into human-readable failure witnesses:

Witness #1 (measured 272 times):
  ✅ Action 'fetch_data' succeeds
  ✅ Action 'transform' succeeds  
  ❌ Action 'save' FAILS
  
  Violated: 'save' must succeed
  
  → This scenario means the pipeline completes processing
    but fails to persist results — silent data loss.

Step 5: LLM Repair Loop

Witnesses are fed to an LLM that revises the plan:

Agent: "Your plan fails when 'save' fails with no fallback.
        Add a retry mechanism or fallback storage."

→ Repaired plan adds: save_fallback (write to local disk)
→ Re-verification confirms the fix

📦 Project Structure

qsvaps/
├── models.py              # Plan, Action, Constraint, Witness dataclasses
├── constraint_engine.py   # Boolean constraint extraction from plans
├── oracle_builder.py      # Quantum phase oracle + Grover diffuser
├── grover_search.py       # Grover's algorithm execution engine
├── verifier.py            # Main verification pipeline
├── llm_interface.py       # LLM integration (OpenAI + mock mode)
└── visualization.py       # ASCII diagrams + matplotlib plots

📊 Verified Results

Demo verification of a 6-action API orchestration pipeline:

Metric Value
Qubits 7
State space 128
Violations found 127 / 128
Grover iterations 1
Circuit depth 516
Circuit gates 1,320
Theoretical speedup 128×

🧪 Running Tests

pip install pytest
python -m pytest tests/ -v

52 tests covering: models, constraint extraction, oracle correctness (statevector verified), Grover amplification, end-to-end verification, and repair loops.

🛣️ Roadmap

📖 Research Background

QSVAPS introduces a new architectural pattern: "Generate classically, verify quantumly." While quantum computing research typically focuses on replacing classical components (QNNs, VQCs), QSVAPS uses quantum algorithms in a fundamentally different role — as a verification oracle that checks classical output.

This builds on:

The novelty lies in the bridge: encoding agent plan constraints as quantum oracles, enabling quantum speedup for a real-world AI safety problem.

📦 Dependencies

Package Version Purpose
qiskit ≥ 1.0.0 Quantum circuit construction
qiskit-aer ≥ 0.13.0 Local quantum simulation
numpy ≥ 1.24.0 Numerical operations
matplotlib ≥ 3.7.0 Result visualization
openai ≥ 1.0.0 Optional — LLM integration

📄 Citation

@software{qsvaps2025,
  title={QSVAPS: Quantum Superposition Verification for Agent Plan Safety},
  year={2025},
  license={MIT},
  url={https://github.com/vmore2/qsvaps}
}

🤝 Contributing

See CONTRIBUTING.md for guidelines.

📜 License

MIT