Metadata-Version: 2.4
Name: neuralbridge-sdk
Version: 2.2.10
Summary: MAPE-K Self-healing API Resilience Engine for LLM Providers — Zero dependency for sync calls
Author-email: NeuralBridge Team <neuralbridge@coze.email>
Project-URL: Homepage, https://github.com/hhhfs9s7y9-code/neuralbridge-sdk
Project-URL: Documentation, https://github.com/hhhfs9s7y9-code/neuralbridge-sdk#readme
Project-URL: Repository, https://github.com/hhhfs9s7y9-code/neuralbridge-sdk.git
Project-URL: Changelog, https://github.com/hhhfs9s7y9-code/neuralbridge-sdk/blob/main/README.md#version-history
Keywords: api,self-healing,resilience,llm,mape-k,circuit-breaker,rate-limiter,failover,middleware,openai,anthropic,azure,google,deepseek
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
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: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Monitoring
Classifier: Topic :: System :: Networking
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Provides-Extra: async
Requires-Dist: aiohttp>=3.9.0; extra == "async"
Provides-Extra: redis
Requires-Dist: redis>=5.0.0; extra == "redis"
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"

# NeuralBridge SDK v2.2.10

> MAPE-K Self-healing API Resilience Engine — Zero dependency for sync calls

[![Version](https://img.shields.io/badge/version-2.2.9-blue)](https://pypi.org/project/neuralbridge-sdk/)
[![Python](https://img.shields.io/badge/python-3.10+-green)](https://www.python.org/)
[![Tests](https://img.shields.io/badge/tests-37%20passed-green)](https://github.com/hhhfs9s7y9-code/neuralbridge-sdk/tree/main/tests)
[![License](https://img.shields.io/badge/license-MIT-orange)](LICENSE)

---

## Quick Start

### Installation

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

### Basic Usage

```python
from neuralbridge import SelfHealingEngine, ProviderConfig

# Create engine
engine = SelfHealingEngine()

# Add provider
engine.add_provider(ProviderConfig(
    name="deepseek",
    base_url="https://api.deepseek.com/v1",
    api_key="sk-your-api-key",
    models=["deepseek-chat"]
))

# Sync call
result = engine.call_sync(
    prompt="Hello, world!",
    model="deepseek-chat"
)
print(result)

# Async call
result = await engine.call(
    prompt="Hello, world!",
    model="deepseek-chat"
)
```

### Streaming Response

```python
async for chunk in engine._execute_stream(
    cfg=engine._providers["deepseek"],
    prompt="Tell me a story",
    model="deepseek-chat"
):
    if "choices" in chunk:
        delta = chunk["choices"][0].get("delta", {}).get("content", "")
        if delta:
            print(delta, end="", flush=True)
```

### Function Calling

```python
tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get weather for a city",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "City name"}
            },
            "required": ["city"]
        }
    }
}]

result = engine.call_sync(
    prompt="What's the weather in Beijing?",
    model="deepseek-chat",
    tools=tools
)
```

---

## Core Features

| Feature | Status | Description |
|---------|--------|-------------|
| **Self-Healing** | ✅ | Diagnose → Retry → Downgrade → Failover |
| **Streaming** | ✅ | `_execute_stream()` support |
| **Zero Dependency** | ✅ | Sync calls require no dependencies |
| **Multi-API Types** | ✅ | chat/embeddings/images/audio |
| **Telemetry** | ✅ | Retry + disk cache + HMAC |
| **Circuit Breaker** | ✅ | Per-category cooldown |
| **Connection Pool** | ✅ | aiohttp reuse |

---

## Performance

> Zero dependency · 1.4ms cold import · 71μs diagnosis

---

## Testing

### Run Unit Tests

```bash
pytest tests/ -v
```

### Test Coverage

- **Diagnoser Classification**: 6 fault types
- **Failover**: Health selection + primary/backup switch
- **Streaming**: async generator + SSE parsing
- **Parameter Passthrough**: tools/tool_choice/response_format/stop etc.
- **Telemetry**: record_fault/HMAC/queue limit/disk cache

**37 test cases, all passed.**

---

## Telemetry

### Enable Telemetry

```python
from neuralbridge import TelemetryCollector

tc = TelemetryCollector(
    endpoint="https://telemetreceiver-neuralbridge-fqarqvcdlt.cn-hangzhou.fcapp.run/api/v1/telemetry",
    batch_size=50,
    flush_interval=30
)

tc.record_fault(
    fault_type="rate_limit",
    provider="openai",
    model="gpt-4o",
    recovery_action="failover",
    recovery_ok=True,
    latency_ms=1234.5,
    api_key="your-hmac-key"
)
```

### Generate Telemetry Report

```bash
python scripts/telemetry_report.py
```

**Output Example:**
```
# NeuralBridge Daily Telemetry Report
Total Events: 554
Success Recovery: 1 (0.2%)
Average Latency: 2.2ms

Fault Type Distribution:
- rate_limit: 250
- timeout: 150
- server_error: 100
```

---

## Version History

### v2.2.10 (2026-05-29)

**Fix:**
- README API examples corrected (`prompt=...` not `messages=[...]`)

### v2.2.8 (2026-05-29)

**Performance:**
- Extreme lazy loading (import time 0.2ms)
- All imports lazy-loaded including SelfHealingEngine

### v2.2.7 (2026-05-29)

**Performance:**
- Lazy loading optimization (import time 326ms → 74ms)

### v2.2.6 (2026-05-29)

**Fix:**
- urllib imports confirmed

### v2.2.5 (2026-05-29)

**Feature:**
- Zero dependency version (sync calls use urllib)

### v2.2.4 (2026-05-29)

**Fix:**
- Telemetry endpoint fixed to FC direct URL
- README corrected

### v2.2.0 (2026-05-28)

**Features:**
- Telemetry integration
- Environment variable endpoint
- Data format compatibility

---

## Technical Architecture

```
User Request
    │
    ▼
┌─────────────────────────────────────┐
│  L1: Diagnoser (fault classifier)   │  ← P50 < 12μs, 6 fault types
│  Output: label only, NEVER act      │
└──────────────┬──────────────────────┘
               │
    ┌──────────▼──────────┐
    │  HA Layer           │
    │  • Circuit Breaker  │  ← fault-category-aware cooldown
    │  • Rate Limiter     │  ← per-provider token bucket
    │  • Bulkhead         │  ← concurrency isolation
    └──────────┬──────────┘
               │
    ┌──────────▼──────────┐
    │  L4: Flywheel       │  ← learns from recovery outcomes
    │  (Knowledge base)   │  ← 84 bootstrap rules
    └──────────┬──────────┘
               │
    ┌──────────▼──────────┐
    │  Telemetry          │  ← retry + disk cache + HMAC
    │  (cloud reporting)  │  ← batch upload
    └─────────────────────┘
```

---

## Supported Providers

| Provider | Models | Status |
|----------|--------|--------|
| OpenAI | gpt-4o, gpt-4o-mini, gpt-3.5-turbo | ✅ |
| Anthropic | claude-sonnet-4, claude-3-5-haiku | ✅ |
| Azure OpenAI | gpt-4o, gpt-4o-mini | ✅ |
| Google | gemini-2.0-flash, gemini-1.5-pro | ✅ |
| DashScope | qwen-max, qwen-plus, qwen-turbo | ✅ |
| DeepSeek | deepseek-chat, deepseek-coder | ✅ |
| NVIDIA | llama-3.1-8b, llama-3.1-70b | ✅ |

---

## Go SDK

Go language version synchronized:

```bash
go get github.com/hhhfs9s7y9-code/neuralbridge-sdk-go
```

**Go SDK Features:**
- ✅ Zero dependency (sync calls use standard library)
- ✅ Full functionality (CallSync, Call, AddProvider)
- ✅ Telemetry reporting
- ✅ Circuit breaker
- ✅ Self-healing engine

**Version**: v2.2.10

**GitHub**: https://github.com/hhhfs9s7y9-code/neuralbridge-sdk-go

---

## Links

- **PyPI**: https://pypi.org/project/neuralbridge-sdk/
- **GitHub**: https://github.com/hhhfs9s7y9-code/neuralbridge-sdk
- **Issues**: https://github.com/hhhfs9s7y9-code/neuralbridge-sdk/issues

---

## License

MIT
