Metadata-Version: 2.4
Name: neuralbridge-sdk
Version: 2.2.3
Summary: MAPE-K Self-healing API Resilience Engine for LLM Providers — Automatic fault diagnosis, intelligent failover, and experience-driven learning
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
Requires-Dist: aiohttp>=3.9.0
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 v2.2.3

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

[![Version](https://img.shields.io/badge/version-2.2.3-blue)](https://pypi.org/project/neuralbridge/)
[![Python](https://img.shields.io/badge/python-3.10+-green)](https://www.python.org/)
[![Tests](https://img.shields.io/badge/tests-37%20passed-green)](tests/test_engine.py)
[![License](https://img.shields.io/badge/license-MIT-orange)](LICENSE)

---

## 快速开始

### 安装

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

### 基础使用

```python
from neuralbridge import SelfHealingEngine, ProviderConfig

# 创建引擎
engine = SelfHealingEngine()
engine.add_provider(ProviderConfig(
    name="openai",
    base_url="https://api.openai.com/v1",
    api_key="sk-...",
    models=["gpt-4o", "gpt-4o-mini"]
))

# 同步调用
result = engine.call_sync("Hello, world!", model="gpt-4o")
print(result)

# 异步调用
result = await engine.call("Hello, world!", model="gpt-4o")
```

### 流式响应

```python
async for chunk in engine._execute_stream(cfg, "Tell me a story", "gpt-4o"):
    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",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {"type": "string"}
            },
            "required": ["city"]
        }
    }
}]

result = engine.call_sync(
    "What's the weather in Beijing?",
    model="gpt-4o",
    tools=tools
)
```

---

## 核心功能

| 功能 | 状态 | 说明 |
|------|------|------|
| **自愈引擎** | ✅ | 诊断 → 重试 → 降级 → Failover |
| **流式响应** | ✅ | `stream=True` 支持 |
| **参数透传** | ✅ | tools/response_format/stop 等 14+ 参数 |
| **多 API 类型** | ✅ | chat/embeddings/images/audio |
| **遥测上报** | ✅ | 重试 + 磁盘缓存 + HMAC 签名 |
| **断路器** | ✅ | 故障类型分窗口 |
| **连接池** | ✅ | aiohttp 复用 |

---

## 测试

### 运行单元测试

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

### 测试覆盖

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

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

---

## 版本历史

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

**修复:**
- LearnedRule.source 字段缺失
- _execute_stream.api_type 参数缺失

**测试:**
- 添加 20 个功能测试
- 添加 .gitignore
- 清理 __pycache__

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

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

---

## 技术架构

```
User Request
    │
    ▼
┌─────────────────────────────────────┐
│  L1: Diagnoser (fault classifier)   │  ← P50 = 12μs (实测), 13 categories
│  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)   │  ← Redis cluster sync support
    └──────────┬──────────┘
               │
    ┌──────────▼──────────┐
    │  Telemetry          │  ← fire-and-forget + retry + disk cache
    │  (cloud reporting)  │  ← HMAC signature auth
    └─────────────────────┘
```

---

## 支持的服务商

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

---

## License

MIT
