Metadata-Version: 2.4
Name: ninel
Version: 1.0.0
Summary: 9L Safety Framework - Universal AI Safety Layer implementing the 9L Architecture
Author: 9L Framework Team
License: MIT
Project-URL: Homepage, https://github.com/9L-framework/ninel
Project-URL: Documentation, https://9l-framework.github.io/ninel
Project-URL: Repository, https://github.com/9L-framework/ninel
Project-URL: Issues, https://github.com/9L-framework/ninel/issues
Keywords: ai-safety,machine-learning,transparency,audit,llm,openai,anthropic,responsible-ai,explainability,human-oversight
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
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 :: Security
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.24.0
Requires-Dist: pydantic>=2.0.0
Provides-Extra: openai
Requires-Dist: openai>=1.0.0; extra == "openai"
Provides-Extra: anthropic
Requires-Dist: anthropic>=0.18.0; extra == "anthropic"
Provides-Extra: google
Requires-Dist: google-generativeai>=0.3.0; extra == "google"
Provides-Extra: huggingface
Requires-Dist: transformers>=4.30.0; extra == "huggingface"
Requires-Dist: torch>=2.0.0; extra == "huggingface"
Provides-Extra: all
Requires-Dist: openai>=1.0.0; extra == "all"
Requires-Dist: anthropic>=0.18.0; extra == "all"
Requires-Dist: google-generativeai>=0.3.0; extra == "all"
Requires-Dist: transformers>=4.30.0; extra == "all"
Requires-Dist: scikit-learn>=1.0.0; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
Requires-Dist: black>=23.0.0; extra == "dev"
Requires-Dist: ruff>=0.1.0; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Dynamic: license-file

# 9L Safety Framework (ninel)

<div align="center">

**Universal AI Safety Layer | Transparency by Construction**

</div>

## What is 9L?

9L is a safety framework that wraps any AI model with architectural guarantees for transparency, human oversight, and accountability. It implements The 9L Architecture v1.0, a formally-verified framework with 15 axioms ensuring that:

- Every output includes confidence and explanation
- Uncertain decisions are escalated to humans
- All operations are cryptographically auditable
- Safety is architectural, not behavioral

> "Safety is not a property we add to systems. It is a geometric constraint on the space of possible computations."

## Installation

```bash
# Core package
pip install ninel

# With OpenAI support
pip install ninel[openai]

# With Anthropic support
pip install ninel[anthropic]

# All providers
pip install ninel[all]
```

## Quick Start

### Basic Usage

```python
from ninel import NineL

# Wrap any AI model
client = NineL(provider="openai", model="gpt-4")

# Make requests with full safety guarantees
result = client.complete("What is the capital of France?")

print(result.output)         # "The capital of France is Paris."
print(result.confidence)     # 0.95
print(result.audit_hash)     # "a1b2c3d4..."
print(result.was_escalated)  # False
```

### Automatic Escalation

```python
from ninel import NineL, NineLConfig

# Configure escalation threshold
config = NineLConfig(escalation_threshold=0.7)
client = NineL(provider="anthropic", model="claude-sonnet-4-20250514", config=config)

# Low-confidence responses trigger human review
result = client.complete("What will the stock market do tomorrow?")

if result.was_escalated:
    print(f"Escalation reason: {result.escalation_reason}")
    print(f"Human decision: {result.human_decision}")
```

### Audit Trail Verification

```python
# Verify any past decision
operation = client.verify_audit(result.audit_hash)
print(f"Verified: {operation}")

# Check chain integrity
is_valid = client.verify_chain_integrity()
print(f"Chain integrity: {'✓' if is_valid else '✗'}")
```

## The 9L Architecture

### The 9 Layers

| Layer | Name | Purpose |
|-------|------|---------|
| L1 | State | Typed entity management |
| L2 | Routing | Communication algebra |
| L3 | Constraints | Policy enforcement |
| L4 | Patterns | Anomaly detection |
| L5 | Coherence | Consistency verification |
| L6 | Correction | Self-healing |
| L7 | Relations | Graph analysis |
| L8 | Commitment | Cryptographic audit |
| L9 | Authorization | Human oversight |

### The 15 Axioms

**Layer Axioms (L1-L7):**

1. **L1: Typed State** - All entities conform to schemas
2. **L2: Gated Flow** - Information flows through valid channels
3. **L3: Explicit Uncertainty** - Every output includes (output, γ, Ξ)
4. **L4: Coherence** - Internal consistency is verified
5. **L5: Commitment** - All operations are committed and immutable
6. **L6: Escalation** - Low confidence triggers human review
7. **L7: Interpretability** - All decisions have explanations

**Communication Axioms (C1-C8):**

1. **C1: Typed Channels** - Messages match permitted types
2. **C2: Delivery Guarantees** - Every message has a defined fate
3. **C3: Escalation Convergence** - All layers can escalate to L9
4. **C4: Commitment Universality** - All layers commit to L8
5. **C5: Bidirectionality** - All edges have return paths
6. **C6: Invariant Preservation** - Edge invariants are enforced
7. **C7: Totality** - No undefined mappings
8. **C8: Type Coverage** - No orphan message types

## Configuration

```python
from ninel import NineL, NineLConfig

config = NineLConfig(
    # Escalation (Axiom L6)
    escalation_threshold=0.7,

    # Human Review (Axiom L9)
    human_review_webhook="https://your-review-system.com/api",
    human_review_timeout_seconds=3600,
    auto_approve_on_timeout=False,

    # Audit (Axioms L5, L8)
    enable_commitment=True,
    commitment_backend="file",  # "memory", "file", "postgresql"
    commitment_path="audit_log.jsonl",

    # Constraints
    max_tokens=4096,
    blocked_topics=["harmful_topic"],

    # Pipeline Control
    enable_patterns=True,
    enable_coherence=True,

    # Logging
    log_level="INFO",
    verbose_pipeline=True,
)

client = NineL(provider="openai", model="gpt-4", config=config)
```

## Supported Providers

### OpenAI

```python
from ninel import NineL

client = NineL(
    provider="openai",
    model="gpt-4-turbo",
    api_key="sk-...",  # Or set OPENAI_API_KEY env var
)
```

### Anthropic

```python
from ninel import NineL

client = NineL(
    provider="anthropic",
    model="claude-sonnet-4-20250514",
    api_key="sk-ant-...",  # Or set ANTHROPIC_API_KEY env var
)
```

### Custom Models

```python
from ninel import NineL, CustomAdapter

# Create custom adapter
adapter = CustomAdapter(
    provider_name="my_provider",
    model_name="my_model",
    call_fn=lambda prompt, **kw: my_model.generate(prompt),
    output_extractor=lambda resp: resp["text"],
    confidence_extractor=lambda resp: resp.get("confidence", 0.5),
)

client = NineL(adapter=adapter)
```

## Human Review Integration

### Webhook Integration

```python
from ninel import NineL, WebhookReview

review = WebhookReview(
    submit_url="https://your-system.com/api/review/submit",
    poll_url="https://your-system.com/api/review/status",
    api_key="your-api-key",
)

client = NineL(provider="openai", human_review=review)
```

### Custom Callbacks

```python
from ninel import NineL, CallbackReview

def on_escalation(case):
    # Send to Slack, create ticket, etc.
    return case.case_id

def get_decision(case_id, timeout):
    # Poll your review system
    return {"decision": "approve", "rationale": "Looks good"}

review = CallbackReview(
    submit_callback=on_escalation,
    decision_callback=get_decision,
)

client = NineL(provider="openai", human_review=review)
```

## API Reference

### NineLResult

```python
@dataclass
class NineLResult:
    output: str              # The AI response
    confidence: float        # γ ∈ [0, 1]
    explanation: Dict        # Ξ - decision explanation
    audit_hash: str          # Cryptographic proof
    escalation_status: EscalationStatus
    escalation_reason: Optional[str]
    request_id: str
    model: str
    provider: str
    latency_ms: float
    human_decision: Optional[str]
    human_rationale: Optional[str]

    @property
    def was_escalated(self) -> bool: ...

    @property
    def is_approved(self) -> bool: ...
```

### NineL Methods

```python
class NineL:
    def complete(
        self,
        prompt: str,
        require_human_review: bool = False,
        **kwargs
    ) -> NineLResult: ...

    def verify_audit(self, audit_hash: str) -> Optional[Dict]: ...
    def get_audit_chain_length(self) -> int: ...
    def verify_chain_integrity(self) -> bool: ...

    @property
    def request_count(self) -> int: ...

    @property
    def escalation_count(self) -> int: ...

    @property
    def escalation_rate(self) -> float: ...
```

## Testing

```python
from ninel import create_mock_client

# Create mock client for testing
client = create_mock_client(escalation_threshold=0.6)

# Set up test responses
client.adapter.set_response(
    "test prompt",
    "test output",
    confidence=0.8
)

# Test your application
result = client.complete("test prompt")
assert result.confidence == 0.8
assert not result.was_escalated
```

## Safety Guarantees

| Guarantee | Mechanism |
|-----------|-----------|
| Cannot produce unexplained outputs | Axioms L3, L7 |
| Cannot bypass human review when uncertain | Axioms L6, L9 |
| Cannot operate without audit trail | Axioms L5, L8 |
| Cannot route through invalid channels | Axiom L2 |
| Cannot accept malformed inputs | Axiom L1 |

These are geometric constraints, not behavioral hopes. The system literally cannot compute without satisfying them.

## License

MIT License - see [LICENSE](LICENSE) for details.

## Citation

If you use 9L in your research, please cite:

```bibtex
@software{ninel2025,
  title = {9L Safety Framework},
  author = {9L Framework Team},
  year = {2025},
  url = {https://github.com/9L-framework/ninel}
}
```

<div align="center">

**9L: Making AI Safety Architectural**

</div>
