Metadata-Version: 2.4
Name: neuralbridge-sdk
Version: 2.2.6
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.6

> MAPE-K 自愈 API 弹性引擎 — 让 AI 应用自动从故障中恢复

[![Version](https://img.shields.io/badge/version-2.2.5-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)

---

## 快速开始

### 安装

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

### 基础使用

```python
from neuralbridge import SelfHealingEngine, ProviderConfig

# 创建引擎
engine = SelfHealingEngine()

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

# 同步调用
result = engine.call_sync(
    messages=[{"role": "user", "content": "Hello, world!"}],
    model="deepseek-chat"
)
print(result)

# 异步调用
result = await engine.call(
    messages=[{"role": "user", "content": "Hello, world!"}],
    model="deepseek-chat"
)
```

### 流式响应

```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(
    messages=[{"role": "user", "content": "What's the weather in Beijing?"}],
    model="deepseek-chat",
    tools=tools
)
```

---

## 核心功能

| 功能 | 状态 | 说明 |
|------|------|------|
| **自愈引擎** | ✅ | 诊断 → 重试 → 降级 → Failover |
| **流式响应** | ✅ | `_execute_stream()` 支持 |
| **参数透传** | ✅ | tools/response_format/stop/top_p 等 |
| **多 API 类型** | ✅ | chat/embeddings/images/audio |
| **遥测上报** | ✅ | 重试 + 磁盘缓存 + HMAC 签名 |
| **断路器** | ✅ | 故障类型分窗口 |
| **连接池** | ✅ | aiohttp 复用 |
| **零依赖** | ✅ | 同步调用无需安装依赖 |

---

## 性能基准

**实测数据（2026-05-29）：**

| 指标 | 实测值 | 阈值 | 状态 |
|------|--------|------|------|
| 诊断 P50 | **12μs** | < 50μs | ✅ |
| 诊断 P99 | **36μs** | < 200μs | ✅ |
| 遥测吞吐 | **62,736 条/秒** | > 1000 条/秒 | ✅ |
| 引擎内存 | **0.09MB** | < 50MB | ✅ |
| 断路器速度 | **0.33μs** | < 1μs | ✅ |

**测试环境：** Windows 11, Python 3.10, 本地机器

---

## 测试

### 运行单元测试

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

### 测试覆盖

- **诊断器分类**: 6 种故障类型
- **Failover**: 健康选择 + 主备切换
- **Streaming**: async generator + SSE 解析
- **参数透传**: tools/tool_choice/response_format/stop 等
- **遥测**: record_fault/HMAC/队列上限/磁盘缓存

**37 个测试用例，全部通过。**

---

## 遥测

### 启用遥测

```python
from neuralbridge import TelemetryCollector

tc = TelemetryCollector(
    endpoint="https://api.neuralbridge.cn/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"
)
```

### 生成遥测报告

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

**输出示例：**
```
# NeuralBridge 遥测日报
总事件数：554
成功恢复：1 (0.2%)
平均延迟：2.2ms

故障类型分布:
- rate_limit: 250
- timeout: 150
- server_error: 100
```

---

## 版本历史

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

**修复:**
- README API 用法修正 (`run()` → `call_sync()`)
- 安装命令修正 (`pip install neuralbridge-sdk`)
- 代码示例全部使用真实 API 验证

**新增:**
- 遥测报告脚本 (`scripts/telemetry_report.py`)
- 本地缓存数据读取和报告生成

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

**修复:**
- 测试用例数量修正 (20 → 37)
- 性能数据修正为实测值

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

**功能:**
- 遥测集成
- 环境变量端点
- 数据格式兼容

---

## 技术架构

```
User Request
    │
    ▼
┌─────────────────────────────────────┐
│  L1: Diagnoser (fault classifier)   │  ← P50 < 12μs, 6 种故障类型
│  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
    └─────────────────────┘
```

---

## 支持的服务商

| 服务商 | 模型 | 状态 |
|--------|------|------|
| 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 | ✅ |

---

## 链接

- **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
