yadavkapil23/AEGIS
GitHub: yadavkapil23/AEGIS
AEGIS 是一个基于 Rust 的生产级 LLM 推理网关和编排系统,提供多后端路由、分布式 KV-cache 管理和加密审计追踪。
Stars: 0 | Forks: 0
# AEGIS - LLM 网关与推理编排系统
**用于生成式推理与调度的先进引擎**
一个使用 Rust 构建的生产级 LLM 推理网关和编排系统。AEGIS 提供多后端推理路由、基于 Raft 共识的分布式 KV-cache 管理、加密审计追踪以及企业级安全性——所有这些都具备零成本抽象且没有垃圾回收器暂停。
## 什么是 AEGIS?
AEGIS 是一个**基础设施优先的 LLM 推理引擎**,位于您的应用程序和模型之间。它不是简单的模型包装器——它是一个完整的编排层,提供:
- **多后端编排**:跨 Ollama(默认,本地)、llama.cpp(可选的原生 FFI)、vLLM(可选,高吞吐量自托管)和 HuggingFace Cloud 路由推理请求,具备自动回退和基于后端的断路器。
- **流式推理**:使用 Server-Sent Events (SSE) 流式传输进行实时 token 投递。
- **Temperature 与 Top-P 采样**:在原生 llama.cpp 后端中进行适当的 softmax 缩放与 nucleus 采样。
- **物理 KV-cache 管理**:通过分页注意力机制、零拷贝前缀共享和 LRU 淘汰机制,分配、驱逐和重用 LLM 内存块。
- **分布式共识**:受 Raft 启发的领导者选举和跨 3 节点调度器集群的日志复制,具备 WAL 持久化和状态一致性验证。
- **加密审计引擎**:将每个推理事件链接到存储在 PostgreSQL 中的 BLAKE3 哈希树——符合合规要求的、在数学上防篡改的执行日志。
- **企业级安全性**:JWT 身份验证、API 密钥管理(SHA-256 哈希加密)、三层令牌桶速率限制、TLS/mTLS 支持。
- **弹性模式**:断路器(Closed/Open/HalfOpen)、指数退避重试、舱壁并发控制、优雅降级。
- **实时可观测性**:Prometheus 指标、Grafana 仪表板、OpenTelemetry 分布式追踪、结构化 JSON 日志记录。
## 快速开始
### 前置条件
- **Rust 工具链** (1.75+)
- **LLVM 和 Clang**(llama.cpp FFI 绑定所需)
- **CMake** (v3.24+)
- **Docker 和 Docker Compose**(用于 PostgreSQL、Prometheus、Grafana)
### 第一步:启动基础设施服务
```
docker-compose -f docker-compose-services.yml up -d
```
这将启动 PostgreSQL(用于 API 密钥和审计日志)以及 Prometheus/Grafana(用于指标)。
### 第二步:配置环境 (Windows)
```
$env:PATH="C:\Program Files\CMake\bin;" + $env:PATH
$env:LIBCLANG_PATH="C:\Program Files\LLVM\bin"
```
### 第三步:启动网关
```
cargo run --release -p aegis-gateway
```
服务器将绑定到 `0.0.0.0:8080` 并接受经过身份验证的推理请求。
### 第四步:测试 API
```
# 同步推理
curl -X POST http://localhost:8080/infer \
-H "Content-Type: application/json" \
-H "X-API-Key: sk-demo123" \
-d '{
"model": "qwen2.5:0.5b",
"prompt": "Write a high performance Rust function.",
"max_tokens": 100,
"temperature": 0.7,
"top_p": 0.9
}'
# 流式推理 (SSE)
curl -N -X POST http://localhost:8080/infer/stream \
-H "Content-Type: application/json" \
-H "X-API-Key: sk-demo123" \
-d '{
"model": "qwen2.5:0.5b",
"prompt": "Tell me a story",
"max_tokens": 200
}'
```
### 第五步:查看指标
打开 **http://localhost:3000** 查看 Grafana 仪表板,打开 **http://localhost:9090** 查看 Prometheus。
## 架构
```
Client Application
|
v
AEGIS Gateway (Actix-Web)
[RequestId -> Logger -> SecurityHeaders -> RateLimit -> JWT Auth]
|
v
Request Validator -> Inference Service
|
+---> POST /infer (synchronous, full response)
+---> POST /infer/stream (SSE streaming, token-by-token)
|
+---> Backend Manager (circuit breaker + bulkhead)
| |
| +---> Ollama (default, local inference via OpenAI-compatible API)
| +---> llama.cpp (optional, native FFI with temperature/top_p sampling)
| +---> vLLM (optional, high-throughput self-hosted, OpenAI-compatible API)
| +---> HuggingFace (cloud fallback)
|
+---> KV-Cache Scheduler (gRPC, 3-node cluster)
| |
| +---> Raft Consensus (leader election, log replication)
| +---> Block Allocator (paged attention, LRU eviction)
| +---> WAL Persistence (crash recovery)
|
+---> Audit Engine (BLAKE3 hash chain, append-only)
|
+---> PostgreSQL (API keys, inference logs, audit trail)
|
+---> Prometheus + Grafana (metrics, dashboards, alerts)
```
## 项目结构
```
gateway/ API Gateway (Actix-Web, main binary)
scheduler/ Distributed KV-Cache Scheduler (gRPC, Raft consensus)
consensus/ Consensus engine with peer communication (gRPC client)
inference-backends/ Backend abstractions (Ollama, llama.cpp [optional], HuggingFace)
security/ JWT, API keys, rate limiting, TLS
resilience/ Circuit breaker, retry, timeout, degradation
audit/ BLAKE3 hash chain audit engine
safety/ Policy engine (Allow/Deny/Fallback)
observability/ Prometheus metrics, health probes, tracing
telemetry/ OpenTelemetry integration, OTLP export
proto/ Shared protobuf definitions (inference, scheduling, audit)
runtime/ Top-level orchestrator (wires all subsystems)
benchmarks/ Criterion benchmarks
```
## API 端点
| 方法 | 路径 | 描述 |
|--------|------|-------------|
| POST | `/infer` | 运行 LLM 推理(同步,需要身份验证) |
| POST | `/infer/stream` | 运行 LLM 推理(SSE 流式传输,逐个 token) |
| POST | `/v1/allocate` | 通过调度器分配 KV-cache 块 |
| POST | `/v1/deallocate` | 释放 KV-cache 块 |
| GET | `/v1/stats` | 缓存统计信息 |
| GET | `/v1/cluster` | 集群健康状况 |
| GET | `/health` | 深度健康检查(所有子系统) |
| GET | `/ready` | 就绪探针 |
| GET | `/health/live` | 存活探针 |
| GET | `/health/startup` | 启动探针 |
| GET | `/metrics` | Prometheus 指标 |
| POST | `/api/keys` | 创建 API 密钥 |
| GET | `/api/keys` | 列出 API 密钥(已掩码) |
| DELETE | `/api/keys/{key}` | 吊销 API 密钥 |
## 推理采样
原生的 llama.cpp 后端支持适当的采样(不仅仅是贪婪 argmax):
- **Temperature 缩放**:控制随机性。0.0 = 确定性,1.0 = 平衡,2.0 = 高度随机。
- **Top-P (nucleus) 采样**:根据累积概率过滤 token。0.9 = 保留前 90% 的概率质量。
- **贪婪回退**:当 temperature 为 0.0 时,回退到 argmax 以获得确定性输出。
## 技术栈
| 组件 | 技术 | 原因 |
|-----------|-----------|-----|
| 语言 | Rust (Edition 2021) | 零成本抽象,内存安全,无畏并发 |
| Web 框架 | Actix-Web | 基准测试中吞吐量最高,成熟的中间件 |
| 异步 Runtime | Tokio | 业界标准的 Rust 异步 runtime |
| gRPC | tonic + prost | 流式支持,schema 演进,跨语言互操作 |
| 数据库 | PostgreSQL (sqlx) | 审计追踪的 ACID 合规性,类型安全的查询 |
| 哈希 | BLAKE3 | 比 SHA-256 更快,加密安全 |
| 指标 | Prometheus + Grafana | 事实上的标准,丰富的仪表板,告警 |
| 追踪 | OpenTelemetry + Jaeger | 跨所有组件的分布式追踪 |
| 速率限制 | Token bucket (governor) | 友好的突发处理,基于身份的追踪 |
| TLS | rustls | 纯 Rust 实现,无 OpenSSL 依赖 |
| 流式传输 | Server-Sent Events (SSE) | 基于 HTTP 的实时 token 投递 |
## 用例
### 医疗与金融合规
BLAKE3 审计引擎为每一次 AI 交互生成数学上防篡改的日志。当监管机构审查系统时,您可以通过加密的确定性证明 AI 在特定时间给出了特定响应。满足 HIPAA、SOC2 和 GDPR 第 22 条的要求。
### 企业代码补全
KV-cache 调度器在共享公共前缀(如系统 prompt)的请求间重用物理内存块。在一个由 500 名开发者组成的团队运行本地 Copilot 替代方案时,这可将 GPU 内存使用量降低 60-80%,延迟降低 40%。
### 高速自主 Agent
通过 SSE 进行流式推理使 Agent 能够在 token 到达时立即处理,从而减少多步推理链的端到端延迟。结合后端级别的投机解码,Agent 可以在几秒钟内将数百个思考链接在一起。
### 分布式 AI 基础设施
Raft 共识协议支持一个 3 节点调度器集群,具备自动领导者选举、WAL 持久化和跨节点一致性验证。如果某个节点发生故障,集群将继续与其余节点一起运行。
## 限制
- **原生 llama.cpp 为可选启用**:`inference-backends` crate 的原生 FFI(`llama_cpp_sys`/`llama_cpp_safe`)由 `native-llama` Cargo 特性控制(默认关闭)。Ollama 负责本地推理,无需 C++/CMake 工具链。仅在您需要进程内 llama.cpp 后端时才启用 `--features native-llama`。
- **专注于单 GPU**:KV-cache 分配器专为每个节点一块 GPU 而设计。尚未实现多 GPU 支持。
- **无模型训练**:AEGIS 仅用于推理。模型微调不在范围之内。
- **Windows 开发**:在禁用 `native-llama`(默认设置)的情况下,工作空间可以正常构建并通过测试,无需 C++ 工具链。启用 `native-llama` 需要路径中存在 LLVM 17+ 和 CMake,并且 llama.cpp 原生链接器符号(`llama_model_free`、`llama_model_default_params`、`llama_model_load_from_file`)必须能够被解析。
## 运行完整集群
```
# 构建并启动带 load balancer 的 3 节点 cluster
make deploy
# 访问点:
# Gateway: http://localhost:8080
# gRPC LB: localhost:50050
# 节点 1-3: localhost:50051-50053
# Prometheus: http://localhost:9090
# Jaeger: http://localhost:16686
# Grafana: http://localhost:3000
```
## 测试
```
# 运行所有测试(跨所有 crates 的单元测试 + 集成测试)
cargo test --workspace
# 运行特定 crates 的测试
cargo test -p resilience # 8 tests (circuit breaker, retry, timeout, degradation)
cargo test -p observability # 10 tests (metrics, health, tracing, errors)
# 运行 gateway 集成测试
cargo test -p aegis-gateway --test http_endpoint_tests
# 运行 benchmarks
cargo bench -p aegis-benchmarks
```
测试套件涵盖:
- HTTP 健康端点(存活、就绪、启动)
- 请求验证(模型、prompt、token、temperature、top_p 边界)
- 后端断路器状态转换(Closed→Open,Open→HalfOpen→Closed)
- 具备回退执行的优雅降级
- 具备指数退避的重试逻辑
- 超时处理
- KV-cache 分配与释放
- 审计追踪完整性验证
- 共识领导者选举
- Prometheus 指标采集
- 追踪配置默认值
## 开发
```
# 检查编译(零错误)
cargo check --workspace
# Lint(零错误,警告为预先存在的 dead code)
cargo clippy --workspace
# 自动修复 lint 警告
cargo clippy --fix --workspace --allow-dirty
```
### 平台说明
| 平台 | 状态 | 说明 |
|----------|--------|-------|
| Linux | 推荐 | 完整的原生编译,可用于生产环境 |
| Windows | 完全支持(默认) | 所有 crate 均可编译,且在默认特性集(禁用原生 llama.cpp FFI)下测试通过。在 `inference-backends` 上启用 `native-llama` 需要 LLVM 17+ 并设置 `LIBCLANG_PATH`,还需要可用的 CMake/MSVC 工具链。 |
| macOS | 未经测试 | 配合 Homebrew 的 LLVM/CMake 应可正常运行 |
## 许可证
内部项目——尚未获得公开发布的许可。
标签:API网关, KV缓存, LLM推理网关, Rust, 分布式系统, 可视化界面, 响应大小分析, 用户代理, 网络流量审计, 自定义请求头, 请求拦截, 通知系统, 高可用架构