Metadata-Version: 2.4
Name: prismlang
Version: 0.1.0
Summary: Deterministic vector language protocol for multi-agent AI orchestration
Project-URL: Homepage, https://www.insightits.com/prismlang
Project-URL: Documentation, https://insightits.github.io/prismlang
Project-URL: Repository, https://github.com/insightits/prismlang
Project-URL: Bug Tracker, https://github.com/insightits/prismlang/issues
Project-URL: Paper, https://www.insightits.com/prismlang/paper
Author-email: Amin Parva <prismrag@insightits.com>
Maintainer-email: Amin Parva <prismrag@insightits.com>
License: Apache License
        Version 2.0, January 2004
        http://www.apache.org/licenses/
        
        TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
        1. Definitions.
        
           "License" shall mean the terms and conditions for use, reproduction,
           and distribution as defined by Sections 1 through 9 of this document.
        
           "Licensor" shall mean the copyright owner or entity authorized by
           the copyright owner that is granting the License.
        
           "Legal Entity" shall mean the union of the acting entity and all
           other entities that control, are controlled by, or are under common
           control with that entity.
        
           "You" (or "Your") shall mean an individual or Legal Entity
           exercising permissions granted by this License.
        
           "Source" form shall mean the preferred form for making modifications.
        
           "Object" form shall mean any form resulting from mechanical
           transformation or translation of a Source form.
        
           "Work" shall mean the work of authorship made available under the License.
        
           "Derivative Works" shall mean any work that is based on the Work.
        
           "Contribution" shall mean any work of authorship submitted to the Licensor.
        
           "Contributor" shall mean Licensor and any Legal Entity on behalf of whom
           a Contribution has been received by the Licensor.
        
        2. Grant of Copyright License. Subject to the terms and conditions of
           this License, each Contributor hereby grants to You a perpetual,
           worldwide, non-exclusive, no-charge, royalty-free, irrevocable
           copyright license to reproduce, prepare Derivative Works of,
           publicly display, publicly perform, sublicense, and distribute the
           Work and such Derivative Works in Source or Object form.
        
        3. Grant of Patent License. Subject to the terms and conditions of
           this License, each Contributor hereby grants to You a perpetual,
           worldwide, non-exclusive, no-charge, royalty-free, irrevocable
           patent license to make, use, sell, offer for sale, import, and
           otherwise transfer the Work.
        
        4. Redistribution. You may reproduce and distribute copies of the
           Work or Derivative Works thereof in any medium, with or without
           modifications, provided that You meet the following conditions:
        
           (a) You must give any other recipients of the Work or Derivative Works
               a copy of this License; and
        
           (b) You must cause any modified files to carry prominent notices
               stating that You changed the files; and
        
           (c) You must retain, in the Source form of any Derivative Works,
               all copyright, patent, trademark, and attribution notices; and
        
           (d) If the Work includes a "NOTICE" text file, you must include a
               readable copy of the attribution notices contained within.
        
        5. Submission of Contributions. Any Contribution intentionally submitted
           for inclusion in the Work shall be under the terms of this License.
        
        6. Trademarks. This License does not grant permission to use the trade
           names, trademarks, service marks, or product names of the Licensor.
        
        7. Disclaimer of Warranty. The Work is provided "AS IS", WITHOUT WARRANTIES
           OR CONDITIONS OF ANY KIND, either express or implied.
        
        8. Limitation of Liability. In no event shall any Contributor be liable
           for any damages arising from use of the Work.
        
        9. Accepting Warranty or Additional Liability. You may offer additional
           warranty or liability obligations consistent with this License.
        
        END OF TERMS AND CONDITIONS
        
        Copyright 2026 Insight IT Solutions LLC
        
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
        
            http://www.apache.org/licenses/LICENSE-2.0
        
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
License-File: LICENSE
Keywords: ai,deterministic,langgraph,llm,multi-agent,onnx,protocol,state-compression,tenant-isolation,vector
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Requires-Dist: huggingface-hub>=0.20.0
Requires-Dist: langgraph>=0.2.0
Requires-Dist: numpy>=1.26.0
Requires-Dist: onnxruntime>=1.17.0
Requires-Dist: tokenizers>=0.15.0
Requires-Dist: typing-extensions>=4.9.0
Provides-Extra: async-files
Requires-Dist: aiofiles>=23.0.0; extra == 'async-files'
Provides-Extra: async-postgres
Requires-Dist: asyncpg>=0.29.0; extra == 'async-postgres'
Provides-Extra: dev
Requires-Dist: aiofiles>=23.0.0; extra == 'dev'
Requires-Dist: asyncpg>=0.29.0; extra == 'dev'
Requires-Dist: mkdocs-material>=9.0.0; extra == 'dev'
Requires-Dist: mkdocs>=1.5.0; extra == 'dev'
Requires-Dist: mkdocstrings[python]>=0.24.0; extra == 'dev'
Requires-Dist: mypy>=1.8.0; extra == 'dev'
Requires-Dist: psycopg2-binary>=2.9.0; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
Requires-Dist: pytest>=7.4.0; extra == 'dev'
Requires-Dist: ruff>=0.1.0; extra == 'dev'
Provides-Extra: docs
Requires-Dist: mkdocs-material>=9.0.0; extra == 'docs'
Requires-Dist: mkdocs>=1.5.0; extra == 'docs'
Requires-Dist: mkdocstrings[python]>=0.24.0; extra == 'docs'
Provides-Extra: postgres
Requires-Dist: psycopg2-binary>=2.9.0; extra == 'postgres'
Description-Content-Type: text/markdown

<div align="center">

<img src="https://img.shields.io/badge/PrismLang-v0.1.0-6366f1?style=for-the-badge&labelColor=0f0f23" alt="PrismLang"/>

# PrismLang

### Deterministic Vector Language Protocol for LangGraph Multi-Agent AI

*Stop paying the token tax on every agent hop. Start routing with math.*

[![PyPI](https://img.shields.io/pypi/v/prismlang?color=06b6d4&label=PyPI&style=flat-square)](https://pypi.org/project/prismlang/)
[![Python](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12-blue?style=flat-square)](https://python.org)
[![License](https://img.shields.io/badge/license-Apache%202.0-22c55e?style=flat-square)](LICENSE)
[![LangGraph](https://img.shields.io/badge/LangGraph-0.2%2B-f97316?style=flat-square)](https://github.com/langchain-ai/langgraph)
[![Tests](https://img.shields.io/badge/tests-34%20passed-22c55e?style=flat-square)](tests/)
[![Security](https://img.shields.io/badge/security-hardened-6366f1?style=flat-square)](docs/SECURITY.md)

<br/>

**[📖 Docs](https://www.insightits.com/prismlang)** · **[🚀 Quickstart](#quick-start)** · **[📊 Benchmarks](#benchmark-results)** · **[🏢 Insight IT Solutions](https://www.insightits.com)**

<br/>

```
pip install prismlang
```

</div>

---

## The Problem

Every node in a LangGraph multi-agent pipeline reads **the entire message history** as prompt tokens. By turn 3 of a standard graph, every agent is paying for every prior agent's output — every single call.

```
Turn 1 →  800 B   1 agent  reading history
Turn 2 → 1,600 B  2 agents reading history
Turn 3 → 2,400 B  3 agents reading history    ← you're paying 3× for the same data
```

On top of that:
- **No audit trail** — you can't trace why an agent classified something the way it did
- **No tenant isolation** — in multi-tenant SaaS, one misconfigured agent can bleed context across org boundaries

---

## The Solution

PrismLang replaces growing text payloads with **64-number deterministic vectors** — one per agent turn. A single decorator on your existing nodes. No agent refactoring. No LLM retraining.

```
[Your Agent]  →  "Credit risk elevated in EM bonds."  (text, 400+ tokens)
                              ↓  @prism_node
              →  PrismEnvelope { vector[64], slug="risk", rule_chain }  (~414 bytes)
```

The math guarantees that **the same input always produces the same vector**, that **different tenants produce incompatible vectors**, and that **every routing decision is traceable back to a taxonomy rule**.

---

## How It Works

PrismLang applies two equations on every agent output:

**Step 1 — Spherical Blend** *(pulls the embedding toward its category direction)*
```
v' = normalize( (1 − α) · v  +  α · ‖v‖ · eᵢ )
```

**Step 2 — JL Reduction** *(compresses to k=64 dims, isolated per tenant)*
```
p = normalize( P · v' )
```

Where `P` is a `(64 × 384)` Gaussian matrix seeded from `SHA-256(tenant_id)`. A vector stolen from Tenant A is **geometrically meaningless** to any model operating under Tenant B's projection.

```
                    ┌─────────────────────────────────────────────┐
                    │           Your LangGraph Graph              │
                    │                                             │
  [researcher] ──→ [summarizer] ──→ [reviewer] ──→ [translator]  │
       │                │               │               │         │
  @prism_node      @prism_node     @prism_node     (boundary)     │
       │                │               │               │         │
  PrismEnvelope    PrismEnvelope   PrismEnvelope   Human text     │
  {64-d vector}    {64-d vector}   {64-d vector}                  │
  {rule_chain}     {rule_chain}    {rule_chain}                    │
                    │                                             │
                    │  prism_sequence  ─────────  append-only     │
                    └─────────────────────────────────────────────┘
```

---

## Quick Start

```python
from prismlang import (
    Category, TaxonomyConfig, PrismProjector,
    PrismState, prism_node, BoundaryTranslator,
    JsonFileCheckpointer,
)
from langgraph.graph import StateGraph, END

# 1. Define your domain taxonomy
taxonomy = TaxonomyConfig(categories=[
    Category("risk",       "Market Risk",   ["risk", "exposure", "volatility"]),
    Category("market",     "Market Data",   ["price", "equity", "bond"]),
    Category("compliance", "Compliance",    ["regulation", "audit", "kyc"]),
])

# 2. One projector per tenant — cryptographically isolated
projector = PrismProjector(taxonomy, tenant_id="acme-finance-prod", k=64)

# 3. Decorate your existing nodes — zero changes to agent logic
@prism_node(agent_id="analyst", projector=projector)
def analyst(state: PrismState) -> dict:
    return {"raw_output": "Credit risk exposure elevated in EM bonds."}

@prism_node(agent_id="reviewer", projector=projector)
def reviewer(state: PrismState) -> dict:
    prev = state["prism_sequence"][-1]["category_slug"]
    return {"raw_output": f"Reviewing {prev} findings for compliance sign-off."}

# 4. Build and run — exactly like any LangGraph graph
translator = BoundaryTranslator()
graph = StateGraph(PrismState)
graph.add_node("analyst",    analyst)
graph.add_node("reviewer",   reviewer)
graph.add_node("translator", translator.as_langgraph_node())
graph.set_entry_point("analyst")
graph.add_edge("analyst", "reviewer")
graph.add_edge("reviewer", "translator")
graph.add_edge("translator", END)

app = graph.compile(checkpointer=JsonFileCheckpointer())
result = app.invoke({
    "prism_sequence": [], "raw_output": "", "tenant_id": "acme-finance-prod"
})

# Inspect the audit envelope
envelope = result["prism_sequence"][0]
print(envelope["category_slug"])   # "risk"
print(len(envelope["vector"]))     # 64
print(envelope["rule_chain"])
# ['text -> encoder(all-MiniLM-L6-v2, d=384)',
#  "category_inference -> slug='risk'",
#  'spherical_blend(alpha=0.300) -> v_prime',
#  "JL_reduction(seed=sha256('acme-finance-prod'), k=64) -> p"]
```

---

## Benchmark Results

> Measured against standard LangGraph text-state across three enterprise domains.  
> Full methodology in [`docs/BENCHMARK.md`](docs/BENCHMARK.md). Results stored in PostgreSQL.

<table>
<tr>
  <th>Domain</th>
  <th>Metric</th>
  <th>Standard LangGraph</th>
  <th>PrismLang</th>
  <th>Change</th>
</tr>
<tr>
  <td rowspan="2"><b>🏥 Healthcare</b><br/><sub>ICU triage pipeline</sub></td>
  <td>Prompt tokens (3 turns)</td>
  <td>391</td>
  <td>148</td>
  <td><b>−62.1%</b></td>
</tr>
<tr>
  <td>State size (turn 3)</td>
  <td>1,928 B</td>
  <td>960 B</td>
  <td><b>−50.2%</b></td>
</tr>
<tr>
  <td rowspan="2"><b>💹 Finance</b><br/><sub>Risk / portfolio pipeline</sub></td>
  <td>Prompt tokens (3 turns)</td>
  <td>407</td>
  <td>175</td>
  <td><b>−57.0%</b></td>
</tr>
<tr>
  <td>State size (turn 3)</td>
  <td>1,760 B</td>
  <td>960 B</td>
  <td><b>−45.5%</b></td>
</tr>
<tr>
  <td rowspan="2"><b>📈 Trade Market</b><br/><sub>Signal / execution pipeline</sub></td>
  <td>Prompt tokens (3 turns)</td>
  <td>435</td>
  <td>180</td>
  <td><b>−58.6%</b></td>
</tr>
<tr>
  <td>State size (turn 3)</td>
  <td>1,867 B</td>
  <td>960 B</td>
  <td><b>−48.6%</b></td>
</tr>
</table>

> **LLM inference latency: unchanged.** PrismLang reduces state transport, not compute.  
> Encoding overhead per turn: ~31–35 ms CPU-only (no GPU required).

---

## Key Properties

| Property | Detail |
|---|---|
| **Zero agent refactoring** | Agents return `{"raw_output": "..."}` — nothing else changes |
| **Deterministic** | Same text + same tenant = identical vector, always |
| **Full audit trail** | Every envelope carries a `rule_chain` tracing the full decision path |
| **Tenant isolation** | `SHA-256(tenant_id)` seeds the JL matrix — cross-tenant vectors are incompatible |
| **No GPU** | ONNX Runtime CPU inference — runs on any standard server |
| **No external API** | Encoder is fully local — no network call per token |
| **Model-agnostic** | Works with GPT-4, Claude, Gemini, Llama, or any LLM |
| **Async native** | `@async_prism_node` for async LangGraph nodes |
| **Two checkpointers** | `JsonFileCheckpointer` (zero deps) + `PostgresCheckpointer` |

---

## Installation Options

```bash
# Core (local JSON checkpointing)
pip install prismlang

# PostgreSQL checkpointing
pip install "prismlang[postgres]"

# Async support (asyncpg + aiofiles)
pip install "prismlang[async-postgres,async-files]"

# Full development environment
pip install "prismlang[dev]"
```

---

## Run the Benchmarks

```bash
git clone https://github.com/insightitsGit/prismlang
cd prismlang
pip install -e ".[dev]"

# Runs all 3 domain benchmarks and prints comparison table
python -m benchmarks.run_all
```

Requires a running PostgreSQL instance. Set `DATABASE_URL` or use the default:  
`postgresql://insight_admin:...@localhost/prismLangDB`

---

## Project Structure

```
prismlang/
├── prismlang/
│   ├── encoder.py        # ONNX all-MiniLM-L6-v2 → 384-d unit vector
│   ├── taxonomy.py       # TaxonomyConfig + Category direction vectors (eᵢ)
│   ├── projector.py      # PrismProjector: spherical blend + JL reduction
│   ├── middleware.py     # @prism_node + @async_prism_node decorators
│   ├── checkpointer.py   # JsonFile + Postgres + Async variants
│   ├── exceptions.py     # Typed exception hierarchy (17 classes)
│   ├── envelope.py       # PrismEnvelope TypedDict
│   ├── state.py          # PrismState (LangGraph append-only channel)
│   └── translator.py     # BoundaryTranslator (structural reconstruction)
├── benchmarks/
│   └── domains/          # Healthcare · Finance · Trade Market
├── demo/
│   └── graph.py          # Runnable 3-node LangGraph demo
├── tests/                # 34 tests · 0 failures
└── docs/
    ├── ARCHITECTURE.md
    ├── BENCHMARK.md
    └── SECURITY.md
```

---

## Security

PrismLang's tenant isolation is a **geometric property** guaranteed by the Johnson-Lindenstrauss lemma — not an access-control system. For production deployments, see [`docs/SECURITY.md`](docs/SECURITY.md) which covers:

- What the JL matrix does and does not protect
- Overlay encryption for PII in `raw_output`
- Dependency security notes (onnxruntime, psycopg2, asyncpg)
- NumPy PRNG stability across version upgrades

To report a vulnerability: **prismrag@insightits.com** — do not open a public GitHub issue.

---

## Citation

```bibtex
@techreport{parva2026prismlang,
  title       = {PrismLang: A Deterministic Vector Language Protocol
                 for Auditable Multi-Agent AI Orchestration},
  author      = {Parva, Amin},
  year        = {2026},
  institution = {Insight IT Solutions LLC},
  url         = {https://www.insightits.com/prismlang}
}
```

---

## License

[Apache 2.0](LICENSE) — free for commercial and personal use.

---

<div align="center">

**Built by [Insight IT Solutions LLC](https://www.insightits.com)**

*Enterprise AI systems · LangGraph architecture · Vector search · Production deployment*

[🌐 Website](https://www.insightits.com) · [📧 Contact](mailto:prismrag@insightits.com) · [🔒 Security](mailto:prismrag@insightits.com)

</div>
