Metadata-Version: 2.4
Name: neuralbridge-sdk
Version: 2.7.5
Summary: NeuralBridge — MAPE-K Self-Healing API Resilience Engine. Intelligent fault diagnosis, 4-level self-healing cascade, contract validation, and semantic boundary protection for LLM providers.
Author-email: NeuralBridge Team <neuralbridge@coze.email>
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/hhhfs9s7y9-code/neuralbridge-sdk
Project-URL: Repository, https://github.com/hhhfs9s7y9-code/neuralbridge-sdk
Project-URL: Documentation, https://github.com/hhhfs9s7y9-code/neuralbridge-sdk/tree/main/docs
Project-URL: Bug Tracker, https://github.com/hhhfs9s7y9-code/neuralbridge-sdk/issues
Project-URL: Changelog, https://github.com/hhhfs9s7y9-code/neuralbridge-sdk/blob/main/CHANGELOG.md
Keywords: llm,self-healing,mape-k,failover,circuit-breaker,api-resilience,openai,anthropic,deepseek,contract-validation,semantic-topology
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
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: Programming Language :: Go
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Networking
Classifier: Topic :: System :: Monitoring
Classifier: Typing :: Typed
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Provides-Extra: async
Requires-Dist: aiohttp>=3.13.5; extra == "async"
Provides-Extra: redis
Requires-Dist: redis; extra == "redis"
Provides-Extra: otel
Requires-Dist: opentelemetry-api; extra == "otel"
Requires-Dist: opentelemetry-sdk; extra == "otel"
Requires-Dist: opentelemetry-exporter-otlp-proto-grpc; extra == "otel"
Provides-Extra: all
Requires-Dist: aiohttp>=3.13.5; extra == "all"
Requires-Dist: redis; extra == "all"
Requires-Dist: opentelemetry-api; extra == "all"
Requires-Dist: opentelemetry-sdk; extra == "all"
Requires-Dist: opentelemetry-exporter-otlp-proto-grpc; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: pytest-asyncio; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Dynamic: license-file

# NeuralBridge SDK

**MAPE-K Self-Healing API Resilience Engine for LLM Providers**

[![PyPI](https://img.shields.io/pypi/v/neuralbridge-sdk)](https://pypi.org/project/neuralbridge-sdk/)
[![Go Reference](https://pkg.go.dev/badge/github.com/neuralbridge/sdk-go.svg)](https://pkg.go.dev/github.com/neuralbridge/sdk-go)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
[![IP Protected](https://img.shields.io/badge/IP-Patent%20Pending-red.svg)](IP-NOTICE.md)

Python · Go · Gateway Proxy — Zero dependency for sync calls. Adaptive fault tolerance with learning.

---

## Why NeuralBridge?

| Problem | NeuralBridge Solution |
|---------|----------------------|
| LLM APIs fail 6-14x more than cloud infra | **MAPE-K 5-stage loop**: every call traverses Monitor → Analyze → Plan → Execute → Knowledge |
| Failover produces wrong output | **Contract Validator**: 5 strategies verify cross-model semantic correctness |
| Creative tasks shouldn't be auto-healed | **Semantic Topology 3-Domain**: OUT_OF_BOUNDS blocks self-healing by design |
| Same error takes same time every time | **FlywheelLearner**: Nth recovery 4x+ faster than 1st |

## Quick Start

### Python

```bash
pip install neuralbridge-sdk
```

```python
from neuralbridge import SelfHealingEngine

engine = SelfHealingEngine(providers=["openai", "anthropic", "deepseek"])
result = engine.call_sync("Hello, world!")

print(result.text)          # Response text
print(result.provider)      # Which provider served it
print(result.mapek_trace)   # Proof of 5-phase traversal
```

### Go

```bash
go get github.com/neuralbridge/sdk-go/pkg/neuralbridge
```

```go
package main

import (
    "fmt"
    "github.com/neuralbridge/sdk-go/pkg/neuralbridge"
)

func main() {
    engine := neuralbridge.NewEngine(
        neuralbridge.WithProviders("openai", "anthropic", "deepseek"),
    )
    result, err := engine.Call("Hello, world!")
    if err != nil {
        panic(err)
    }
    fmt.Println(result.Text)
    fmt.Println(result.MapekTrace)
}
```

### Gateway Proxy (Any Language)

```bash
pip install neuralbridge-sdk
python -m neuralbridge.gateway --port 8080 --providers openai,anthropic
```

```bash
# Drop-in replacement for any OpenAI client
curl http://localhost:8080/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-4o","messages":[{"role":"user","content":"Hello!"}]}'
```

## Architecture

```
┌──────────────────────────────────────────────────────┐
│                   MAPE-K Adaptive Loop                │
│  ┌─────────┐   ┌──────────┐   ┌──────┐   ┌────────┐ │
│  │ Monitor │──▶│ Analyze  │──▶│ Plan │──▶│Execute │ │
│  └────┬────┘   └──────────┘   └──────┘   └───┬────┘ │
│       │                                       │      │
│       │         ┌───────────┐                 │      │
│       └────────▶│ Knowledge │◀────────────────┘      │
│                 │(Flywheel) │                        │
│                 └─────┬─────┘                        │
│                       │                              │
│  ┌────────────────────┼─────────────────────────┐   │
│  │   Semantic Topology │                         │   │
│  │  ┌──────────────┐ ┌┴────────────┐ ┌────────┐ │   │
│  │  │STRONG_EQUIV  │ │TAU_NEIGHBOR │ │OOB     │ │   │
│  │  │Contract=Must │ │Contract=Opt │ │Blocked │ │   │
│  │  └──────────────┘ └─────────────┘ └────────┘ │   │
│  └──────────────────────────────────────────────┘   │
└──────────────────────────────────────────────────────┘
```

**MAPE-K Phases** — every `call()` traverses all 5 with microsecond-precision timestamps:

| Phase | Responsibility | Boundary |
|-------|---------------|----------|
| **Monitor** | Collect metrics, check rate limits, select provider | Read-only |
| **Analyze** | Diagnose faults, detect slow degradation | Output label only |
| **Plan** | Flywheel + HA decision (L1→L2→L3→L4) | Decision only |
| **Execute** | Retry / downgrade / failover / direct | Action |
| **Knowledge** | Feedback to FlywheelLearner | Record only |

**Heal Cascade**: `L1 Retry → L2 Downgrade → L3 Failover → L4 Learned`

**Contract Validator** (5 strategies, zero dependencies):

| Strategy | Method |
|----------|--------|
| **Schema** | JSON required keys validation |
| **Determinism** | SHA256 hash matching |
| **Similarity** | Jaccard word-level similarity |
| **Entities** | Required keyword presence |
| **Forbidden** | Regex hallucination guard |

```python
from neuralbridge import Contract

contract = Contract(
    output_schema={"required": ["name", "age"]},
    required_entities=["Python"],
    forbidden_patterns=[r"I cannot", r"as an AI"],
)

result = engine.call_sync(
    "Extract name and age from: John is 30 years old",
    task_type="extraction",
    has_schema=True,
    contract=contract,
)
print(result.validation_passed)  # True
```

## API Reference

### SelfHealingEngine

```python
engine = SelfHealingEngine(
    providers=["openai", "anthropic", "deepseek"],
    api_keys={"openai": "sk-..."},           # optional, auto-detects from env
)

# Async
result = await engine.call(
    prompt="Hello",
    model="gpt-4o",                          # optional
    task_type="classification",              # auto-classifies semantic domain
    contract=Contract(...),                  # output validation
)

# Sync
result = engine.call_sync("Hello")

# Health
engine.health_check()          # {"openai": "healthy", ...}
engine.get_available_providers()  # ["openai", "anthropic"]
engine.get_mapek_stats()         # MAPE-K specific statistics
```

### CallResult

```python
result.text                # Response text
result.provider            # Provider that served the request
result.success             # Whether the call succeeded
result.heal_level          # "l1_retry" | "l2_downgrade" | "l3_failover" | "l4_learned"
result.semantic_domain     # "strong_equiv" | "tau_neighborhood" | "out_of_bounds"
result.validation_passed   # Contract validation result
result.mapek_trace         # MAPE-K phase trace with timestamps
result.latency_ms         # Call latency
```

### Gateway Proxy

```python
from neuralbridge import serve

server = serve(host="0.0.0.0", port=8080, providers=["openai", "anthropic"])
```

| Endpoint | Description |
|----------|-------------|
| `POST /v1/chat/completions` | OpenAI-compatible chat API |
| `POST /v1/completions` | Legacy completions |
| `POST /v1/embeddings` | Embeddings |
| `GET /v1/models` | List models |
| `GET /health` | K8s liveness/readiness |
| `GET /metrics` | Prometheus metrics |
| `GET /mapek` | MAPE-K statistics |

## Supported Providers

| Provider | Preset | Models | Env Key |
|----------|--------|--------|---------|
| OpenAI | ✅ | gpt-4o, gpt-4o-mini, gpt-3.5-turbo | OPENAI_API_KEY |
| Anthropic | ✅ | claude-sonnet-4, claude-3-5-haiku | ANTHROPIC_API_KEY |
| DeepSeek | ✅ | deepseek-chat, deepseek-coder, deepseek-reasoner | DEEPSEEK_API_KEY |
| Google | ✅ | gemini-2.0-flash, gemini-1.5-pro | GOOGLE_API_KEY |
| DashScope | ✅ | qwen-max, qwen-plus, qwen-turbo | DASHSCOPE_API_KEY |
| Azure | ✅ | gpt-4o, gpt-4o-mini | AZURE_OPENAI_API_KEY |
| NVIDIA | ✅ | llama-3.1-8b, llama-3.1-70b | NVIDIA_API_KEY |
| Groq | ✅ | — | GROQ_API_KEY |
| Custom | ✅ | Any | — |

## Benchmark (v2.5.1)

**Real API** — DeepSeek (deepseek-chat), 11 sequential calls:

| Metric | Value |
|--------|-------|
| P50 latency | 582ms |
| Avg latency | 892ms |
| Min / Max | 534ms / 3891ms |

**Functional tests** — all 6/6 PASS with real LLM responses:

| Scenario | Result | Detail |
|----------|--------|--------|
| Basic Call | ✅ PASS | MAPE-K 5-phase trace, 621ms |
| Contract Schema | ✅ PASS | JSON extraction + schema validation in STRONG_EQUIVALENCE |
| Contract Forbidden | ✅ PASS | Hallucination guard blocks "I cannot" patterns |
| Semantic STRONG_EQUIVALENCE | ✅ PASS | classification + schema → strong_equiv domain |
| Semantic TAU_NEIGHBORHOOD | ✅ PASS | summarization → tau_neighborhood domain |
| Semantic OUT_OF_BOUNDS | ✅ PASS | creative_writing → out_of_bounds, self-healing blocked |

**Unit tests** — 147 total (Python 25 + Go 122), all PASS

## Comparison

| Capability | NeuralBridge | LiteLLM | Portkey |
|-----------|-------------|---------|---------|
| MAPE-K 5-Phase Loop | ✅ MapeKTrace per call | ❌ | ❌ |
| Semantic Boundary (3-Domain) | ✅ OOB blocks healing by design | ❌ | ❌ |
| Contract Validator | ✅ 5 strategies, zero dep | ❌ | Guardrails plugin |
| Flywheel Learning | ✅ 93 rules + persist + TTL decay | ❌ | ❌ |
| Zero Dependency (sync) | ✅ | ❌ | ❌ |
| Architecture Model | Closed-loop autonomic (MAPE-K) | Pass-through router | Middleware gateway |

## Documentation

- [Cookbook](COOKBOOK.md) — 15 practical recipes
- [Case Study](CASE_STUDY.md) — Production deployment report
- [Technical Report](TECHNICAL_REPORT.md) — Architecture deep-dive
- [Contributing](CONTRIBUTING.md) — How to contribute
- [Changelog](CHANGELOG.md) — Version history

## Intellectual Property

NeuralBridge contains proprietary technology protected under **pending patent applications**:

- **MAPE-K 5-Phase Adaptive Loop** — Patent Pending
- **Semantic Topology Three-Domain Classification** — Patent Pending
- **Contract Validator (5 Strategies)** — Patent Pending
- **FlywheelLearner with TTL Decay** — Patent Pending
- **Per-Category Circuit Breaker** — Patent Pending

"NeuralBridge" is a trademark of NeuralBridge Team. See [IP-NOTICE.md](IP-NOTICE.md) and [NOTICE](NOTICE).

## License

Licensed under the **Apache License, Version 2.0**. See [LICENSE](LICENSE).
