feat: 开源混合流 + Ultrafast 推理框架(v5.2.1 提取版)
Browse files- .gitignore +2 -0
- Cargo.toml +26 -0
- LICENSE +21 -0
- README.md +183 -0
- examples/hybrid_demo.rs +136 -0
- src/hybrid.rs +233 -0
- src/lib.rs +206 -0
- src/pool.rs +32 -0
- src/types.rs +90 -0
- src/ultrafast.rs +139 -0
.gitignore
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/target
|
| 2 |
+
Cargo.lock
|
Cargo.toml
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[package]
|
| 2 |
+
name = "perch-ultrafast"
|
| 3 |
+
version = "0.1.0"
|
| 4 |
+
edition = "2021"
|
| 5 |
+
description = "Hybrid streaming + Ultrafast inference framework: local draft answers in 0.08s, cloud model takes over seamlessly."
|
| 6 |
+
license = "MIT"
|
| 7 |
+
keywords = ["llm", "streaming", "hybrid", "latency", "tokio"]
|
| 8 |
+
categories = ["asynchronous", "web-programming"]
|
| 9 |
+
|
| 10 |
+
[dependencies]
|
| 11 |
+
futures = "0.3"
|
| 12 |
+
tokio = { version = "1", features = ["rt", "time", "sync", "macros"] }
|
| 13 |
+
tokio-util = "0.7"
|
| 14 |
+
reqwest = { version = "0.12", default-features = false, features = [
|
| 15 |
+
"json",
|
| 16 |
+
"gzip",
|
| 17 |
+
"brotli",
|
| 18 |
+
"deflate",
|
| 19 |
+
"stream",
|
| 20 |
+
"rustls-tls",
|
| 21 |
+
] }
|
| 22 |
+
serde = { version = "1", features = ["derive"] }
|
| 23 |
+
serde_json = "1"
|
| 24 |
+
|
| 25 |
+
[dev-dependencies]
|
| 26 |
+
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2026 栖木 Perch contributors
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
README.md
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language:
|
| 3 |
+
- zh
|
| 4 |
+
- en
|
| 5 |
+
tags:
|
| 6 |
+
- rust
|
| 7 |
+
- llm
|
| 8 |
+
- streaming
|
| 9 |
+
- latency
|
| 10 |
+
- inference
|
| 11 |
+
- tokio
|
| 12 |
+
- framework
|
| 13 |
+
license: mit
|
| 14 |
+
pretty_name: perch-ultrafast — Hybrid Streaming + Ultrafast Inference
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
# ⚡ perch-ultrafast
|
| 18 |
+
|
| 19 |
+
**让 LLM 应用的首字延迟从 1 秒降到 0.08 秒——不换模型,不掉质量。**
|
| 20 |
+
|
| 21 |
+
从 [栖木 Perch](https://huggingface.co/hongcoding/perch)(macOS 本地优先 AI 工作台)中提取的
|
| 22 |
+
可复用 Rust 框架。MIT 开源。
|
| 23 |
+
|
| 24 |
+
> **一句话原理**:云端大模型首 token 要 0.5~2s(网络+排队+预填充),本机小模型只要 0.05~0.2s。
|
| 25 |
+
> 那就**两条流同时开**——本机先出草稿让你有东西读,云端一到立刻接棒。
|
| 26 |
+
> 你看到的首字延迟 = 本机延迟,最终答案质量 = 云端质量。
|
| 27 |
+
|
| 28 |
+
---
|
| 29 |
+
|
| 30 |
+
## 📊 实测数据(栖木 Perch 生产环境)
|
| 31 |
+
|
| 32 |
+
| 场景 | 首字延迟 | 用户体验 |
|
| 33 |
+
|---|---|---|
|
| 34 |
+
| 纯云端(大模型) | 0.88 ~ 1.39s | 盯着空屏幕等 |
|
| 35 |
+
| 纯本机(0.6B) | 0.04 ~ 0.18s | 快,但质量有限 |
|
| 36 |
+
| **本框架混合流** | **< 0.2s 首字 + 云端质量** | **立刻有字,随后升级** |
|
| 37 |
+
|
| 38 |
+
Demo 跑出来的真实时序(`cargo run --example hybrid_demo`):
|
| 39 |
+
|
| 40 |
+
```
|
| 41 |
+
⏱ 开始(0ms)
|
| 42 |
+
|
| 43 |
+
[82ms] 首字可见 → 我是一个本机小模型,这是我的草稿答案。
|
| 44 |
+
[902ms] ⚡ 云端模型已接棒(清空草稿)
|
| 45 |
+
这是云端大模型的正式答案,质量更高、信息更全。
|
| 46 |
+
[1130ms] ✅ 完成
|
| 47 |
+
|
| 48 |
+
首字延迟: 82ms(纯云端需要 900ms)—— 快 11 倍
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
---
|
| 52 |
+
|
| 53 |
+
## 🚀 快速开始
|
| 54 |
+
|
| 55 |
+
```toml
|
| 56 |
+
[dependencies]
|
| 57 |
+
perch-ultrafast = { git = "https://huggingface.co/hongcoding/perch-ultrafast" }
|
| 58 |
+
```
|
| 59 |
+
|
| 60 |
+
```rust
|
| 61 |
+
use std::sync::Arc;
|
| 62 |
+
use perch_ultrafast::{hybrid::{run_hybrid, HybridConfig}, types::*};
|
| 63 |
+
use tokio_util::sync::CancellationToken;
|
| 64 |
+
|
| 65 |
+
let result = run_hybrid(
|
| 66 |
+
local_provider, // 本机 0.6B(预热过)
|
| 67 |
+
cloud_provider, // 云端大模型
|
| 68 |
+
ChatRequest { think: Some(ThinkLevel::Off), ..request.clone() }, // 本机:关思考求快
|
| 69 |
+
request, // 云端:原样
|
| 70 |
+
CancellationToken::new(),
|
| 71 |
+
HybridConfig::default(),
|
| 72 |
+
|chunk| match chunk {
|
| 73 |
+
StreamChunk::Delta { text } => print!("{text}"),
|
| 74 |
+
StreamChunk::Replaced { .. } => println!("\n[云端接棒]"),
|
| 75 |
+
StreamChunk::Done { .. } => println!("\n[done]"),
|
| 76 |
+
_ => {}
|
| 77 |
+
},
|
| 78 |
+
).await;
|
| 79 |
+
|
| 80 |
+
println!("云端接棒 = {}", result.used_cloud);
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
**只需实现一个 trait** 就能接入任何后端:
|
| 84 |
+
|
| 85 |
+
```rust
|
| 86 |
+
pub trait Provider: Send + Sync {
|
| 87 |
+
fn chat_stream(&self, request: ChatRequest, cancel: CancellationToken)
|
| 88 |
+
-> BoxFuture<Result<ProviderStream, String>>;
|
| 89 |
+
}
|
| 90 |
+
```
|
| 91 |
+
|
| 92 |
+
Ollama、OpenAI 兼容接口、自建推理服务——都是几十行适配。
|
| 93 |
+
|
| 94 |
+
---
|
| 95 |
+
|
| 96 |
+
## 🧠 Ultrafast 推理框架(三条加速法则)
|
| 97 |
+
|
| 98 |
+
混合流解决**首字**,Ultrafast 解决**整体**。两者互补。
|
| 99 |
+
|
| 100 |
+
### 1. 关思考(think-off on dispatch)
|
| 101 |
+
推理模型的 thinking 链显著拉高首 token 延迟。加速模式在**下发时**强制 `think: Off` /
|
| 102 |
+
`thinking: {"type":"disabled"}`。
|
| 103 |
+
|
| 104 |
+
> ⚠️ **只覆盖本次下发值,不改用户持久化档位**——关掉开关立刻回到原思考强度。
|
| 105 |
+
|
| 106 |
+
### 2. 连接池复用(connection-pool reuse)
|
| 107 |
+
`reqwest::Client` 做成进程级单例(`OnceLock`),连接池跨请求复用,
|
| 108 |
+
省掉每条请求的 TCP + TLS 握手。同时启用 gzip/brotli——下行字节更少,正文更早到。
|
| 109 |
+
|
| 110 |
+
### 3. 回复预算(reply budget)
|
| 111 |
+
未显式指定时给一个较小的 `max_tokens`(默认 2048),避免模型啰嗦。
|
| 112 |
+
**用户显式设定优先,绝不覆盖。**
|
| 113 |
+
|
| 114 |
+
### 4. 模型锁 🔒(model lock)
|
| 115 |
+
**加速开关无权更换模型。**
|
| 116 |
+
|
| 117 |
+
速度不能靠"偷偷换成更快的模型"——那会改变答案质量,是欺骗。
|
| 118 |
+
用户选了 MiMo 就只用 MiMo,不因"求快"而 fallback 到小模型。
|
| 119 |
+
|
| 120 |
+
---
|
| 121 |
+
|
| 122 |
+
## 🛡️ 四条设计红线
|
| 123 |
+
|
| 124 |
+
| 红线 | 原因 |
|
| 125 |
+
|---|---|
|
| 126 |
+
| **加速不换模型** | 偷偷换模型 = 欺骗用户 |
|
| 127 |
+
| **只改下发值** | 不动持久化档位,关掉即恢复 |
|
| 128 |
+
| **云端失败保留草稿** | 不把用户的答案变成错误页 |
|
| 129 |
+
| **本机失败静默降级** | 行为等同没用混合流,不打扰用户 |
|
| 130 |
+
|
| 131 |
+
这些红线都有**契约测试钉死**(`cargo test`)。
|
| 132 |
+
|
| 133 |
+
---
|
| 134 |
+
|
| 135 |
+
## 🏗️ 架构
|
| 136 |
+
|
| 137 |
+
```
|
| 138 |
+
src/
|
| 139 |
+
├── types.rs Provider trait / StreamChunk / ChatRequest
|
| 140 |
+
├── hybrid.rs 混合流 mux(本机草稿 → 云端接棒 + 双向降级)
|
| 141 |
+
├── ultrafast.rs 加速规则(关思考 / 预算 / 简洁提示 / 模型锁)
|
| 142 |
+
└── pool.rs 连接池单例
|
| 143 |
+
examples/
|
| 144 |
+
└── hybrid_demo.rs 可运行 demo(真实时序)
|
| 145 |
+
```
|
| 146 |
+
|
| 147 |
+
**核心只有 600 行 Rust**,无业务耦合,可直接嵌入你的项目。
|
| 148 |
+
|
| 149 |
+
---
|
| 150 |
+
|
| 151 |
+
## 🧩 降级矩阵(生产环境验证)
|
| 152 |
+
|
| 153 |
+
| 情况 | 行为 |
|
| 154 |
+
|---|---|
|
| 155 |
+
| 本机预热完成 | 草稿 0.08s 出字,云端 ~0.9s 接棒 |
|
| 156 |
+
| 本机冷启动 | 本机超���(50ms)→ 纯云端,用户体验等同没用混合流 |
|
| 157 |
+
| 本机不可用 | 门控跳过 → 纯云端 |
|
| 158 |
+
| 云端建流失败 | 本机草稿继续跑完(不丢答案) |
|
| 159 |
+
| 云端中途出错 | 保留草稿按完成收尾(不把草稿变错误) |
|
| 160 |
+
| 用户取消 | 两条流同时取消 |
|
| 161 |
+
|
| 162 |
+
---
|
| 163 |
+
|
| 164 |
+
## 🔬 测试
|
| 165 |
+
|
| 166 |
+
```bash
|
| 167 |
+
cargo test # 5 个单元测试 + 1 个文档测试
|
| 168 |
+
cargo run --example hybrid_demo # 看真实时序
|
| 169 |
+
```
|
| 170 |
+
|
| 171 |
+
覆盖:接棒触发 / Replaced 信号 / 云端失败回退本地 / 模型锁 / 预算不覆盖用户设定 / 简洁提示去重。
|
| 172 |
+
|
| 173 |
+
---
|
| 174 |
+
|
| 175 |
+
## 📖 来源
|
| 176 |
+
|
| 177 |
+
本框架是 [栖木 Perch](https://huggingface.co/hongcoding/perch) v5.2.1 的
|
| 178 |
+
`src-tauri/src/commands.rs` + `providers/cloud.rs` 中混合流/加速逻辑的独立提取版,
|
| 179 |
+
去掉了 Tauri/数据库/UI 业务耦合,保留可复用的核心。
|
| 180 |
+
|
| 181 |
+
## 📜 许可
|
| 182 |
+
|
| 183 |
+
MIT — 随便用,注明出处即可。
|
examples/hybrid_demo.rs
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! 可运行 demo:用两个假 provider 演示混合流时序。
|
| 2 |
+
//!
|
| 3 |
+
//! ```bash
|
| 4 |
+
//! cargo run --example hybrid_demo
|
| 5 |
+
//! ```
|
| 6 |
+
//!
|
| 7 |
+
//! 输出会显示:本机草稿先出字 → 云端接棒 → 最终内容。
|
| 8 |
+
|
| 9 |
+
use std::sync::Arc;
|
| 10 |
+
use std::time::{Duration, Instant};
|
| 11 |
+
|
| 12 |
+
use futures::stream;
|
| 13 |
+
use perch_ultrafast::hybrid::{run_hybrid, HybridConfig};
|
| 14 |
+
use perch_ultrafast::types::{
|
| 15 |
+
BoxFuture, ChatRequest, MessageRole, Provider, ProviderStream, StreamChunk, ThinkLevel,
|
| 16 |
+
};
|
| 17 |
+
use tokio_util::sync::CancellationToken;
|
| 18 |
+
|
| 19 |
+
/// 模拟一个把文本按字符流式吐出的模型。
|
| 20 |
+
struct MockProvider {
|
| 21 |
+
text: String,
|
| 22 |
+
/// 首字延迟
|
| 23 |
+
first_delay: Duration,
|
| 24 |
+
/// 每个字符间隔
|
| 25 |
+
per_char: Duration,
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
impl Provider for MockProvider {
|
| 29 |
+
fn chat_stream(
|
| 30 |
+
&self,
|
| 31 |
+
_request: ChatRequest,
|
| 32 |
+
_cancel: CancellationToken,
|
| 33 |
+
) -> BoxFuture<Result<ProviderStream, String>> {
|
| 34 |
+
let text = self.text.clone();
|
| 35 |
+
let first_delay = self.first_delay;
|
| 36 |
+
let per_char = self.per_char;
|
| 37 |
+
Box::pin(async move {
|
| 38 |
+
let (tx, rx) = tokio::sync::mpsc::channel::<StreamChunk>(64);
|
| 39 |
+
tokio::spawn(async move {
|
| 40 |
+
tokio::time::sleep(first_delay).await;
|
| 41 |
+
for ch in text.chars() {
|
| 42 |
+
if tx
|
| 43 |
+
.send(StreamChunk::Delta {
|
| 44 |
+
text: ch.to_string(),
|
| 45 |
+
})
|
| 46 |
+
.await
|
| 47 |
+
.is_err()
|
| 48 |
+
{
|
| 49 |
+
return;
|
| 50 |
+
}
|
| 51 |
+
tokio::time::sleep(per_char).await;
|
| 52 |
+
}
|
| 53 |
+
let _ = tx
|
| 54 |
+
.send(StreamChunk::Done {
|
| 55 |
+
prompt_tokens: None,
|
| 56 |
+
completion_tokens: None,
|
| 57 |
+
eval_ms: None,
|
| 58 |
+
cached_tokens: None,
|
| 59 |
+
})
|
| 60 |
+
.await;
|
| 61 |
+
});
|
| 62 |
+
let s = stream::unfold(rx, |mut rx| async move {
|
| 63 |
+
rx.recv().await.map(|chunk| (chunk, rx))
|
| 64 |
+
});
|
| 65 |
+
Ok(Box::pin(s) as ProviderStream)
|
| 66 |
+
})
|
| 67 |
+
}
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
#[tokio::main]
|
| 71 |
+
async fn main() {
|
| 72 |
+
let request = ChatRequest {
|
| 73 |
+
model: "cloud-big".to_string(),
|
| 74 |
+
messages: vec![perch_ultrafast::ChatMessage {
|
| 75 |
+
role: MessageRole::User,
|
| 76 |
+
content: "介绍一下你自己".to_string(),
|
| 77 |
+
}],
|
| 78 |
+
think: Some(ThinkLevel::High),
|
| 79 |
+
max_tokens: None,
|
| 80 |
+
tools: None,
|
| 81 |
+
};
|
| 82 |
+
|
| 83 |
+
// 本机 0.6B:首字 80ms,每字 15ms
|
| 84 |
+
let local = Arc::new(MockProvider {
|
| 85 |
+
text: "我是一个本机小模型,这是我的草稿答案。".to_string(),
|
| 86 |
+
first_delay: Duration::from_millis(80),
|
| 87 |
+
per_char: Duration::from_millis(15),
|
| 88 |
+
});
|
| 89 |
+
// 云端大模型:首字 900ms,每字 8ms
|
| 90 |
+
let cloud = Arc::new(MockProvider {
|
| 91 |
+
text: "这是云端大模型的正式答案,质量更高、信息更全。".to_string(),
|
| 92 |
+
first_delay: Duration::from_millis(900),
|
| 93 |
+
per_char: Duration::from_millis(8),
|
| 94 |
+
});
|
| 95 |
+
|
| 96 |
+
let start = Instant::now();
|
| 97 |
+
println!("⏱ 开始(0ms)\n");
|
| 98 |
+
|
| 99 |
+
let mut first_visible: Option<Duration> = None;
|
| 100 |
+
let result = run_hybrid(
|
| 101 |
+
local,
|
| 102 |
+
cloud,
|
| 103 |
+
ChatRequest {
|
| 104 |
+
think: Some(ThinkLevel::Off),
|
| 105 |
+
max_tokens: Some(2048),
|
| 106 |
+
..request.clone()
|
| 107 |
+
},
|
| 108 |
+
request,
|
| 109 |
+
CancellationToken::new(),
|
| 110 |
+
HybridConfig::default(),
|
| 111 |
+
|chunk| match chunk {
|
| 112 |
+
StreamChunk::Delta { text } => {
|
| 113 |
+
let t = start.elapsed();
|
| 114 |
+
if first_visible.is_none() {
|
| 115 |
+
first_visible = Some(t);
|
| 116 |
+
print!("[{}ms] 首字可见 → ", t.as_millis());
|
| 117 |
+
}
|
| 118 |
+
print!("{text}");
|
| 119 |
+
}
|
| 120 |
+
StreamChunk::Replaced { message } => {
|
| 121 |
+
println!("\n[{}ms] ⚡ {message}(清空草稿)\n ", start.elapsed().as_millis());
|
| 122 |
+
}
|
| 123 |
+
StreamChunk::Done { .. } => {
|
| 124 |
+
println!("\n\n[{}ms] ✅ 完成", start.elapsed().as_millis());
|
| 125 |
+
}
|
| 126 |
+
_ => {}
|
| 127 |
+
},
|
| 128 |
+
)
|
| 129 |
+
.await;
|
| 130 |
+
|
| 131 |
+
println!("\n最终内容({} 字): {}", result.content.chars().count(), result.content);
|
| 132 |
+
println!("云端接棒: {}", result.used_cloud);
|
| 133 |
+
if let Some(t) = first_visible {
|
| 134 |
+
println!("首字延迟: {}ms(纯云端需要 {}ms)", t.as_millis(), 900);
|
| 135 |
+
}
|
| 136 |
+
}
|
src/hybrid.rs
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! 混合流(Hybrid Streaming):本机小模型先出草稿,云端大模型无缝接棒。
|
| 2 |
+
//!
|
| 3 |
+
//! # 为什么
|
| 4 |
+
//!
|
| 5 |
+
//! 云端大模型的**首 token 延迟**通常在 0.5~2 秒(网络 + 排队 + 预填充)。
|
| 6 |
+
//! 本机小模型(如 0.6B)热身后首 token 只要 0.04~0.2 秒。
|
| 7 |
+
//!
|
| 8 |
+
//! 混合流让用户**立刻有东西可读**:本机先答,云端一到就接棒——
|
| 9 |
+
//! 用户看到的首字延迟 = 本机延迟,最终质量 = 云端质量。
|
| 10 |
+
//!
|
| 11 |
+
//! # 时序
|
| 12 |
+
//!
|
| 13 |
+
//! ```text
|
| 14 |
+
//! t=0ms 同时开两条流(本机 + 云端)
|
| 15 |
+
//! t=80ms 本机首字到达 → 用户立刻看到草稿
|
| 16 |
+
//! t=900ms 云端首字到达 → 发 Replaced(前端清空草稿)→ 换成云端正文
|
| 17 |
+
//! t=3000ms 云端结束 → Done
|
| 18 |
+
//! ```
|
| 19 |
+
//!
|
| 20 |
+
//! # 降级
|
| 21 |
+
//!
|
| 22 |
+
//! - 云端建流失败 → 纯本地跑完(有草稿就继续用)
|
| 23 |
+
//! - 本机建流失败 → 纯云端跑完(行为等同没用混合流)
|
| 24 |
+
//! - 云端中途出错 → 保留本地草稿、按完成收尾(不把草稿变成错误)
|
| 25 |
+
|
| 26 |
+
use std::sync::Arc;
|
| 27 |
+
use std::time::Duration;
|
| 28 |
+
|
| 29 |
+
use futures::StreamExt;
|
| 30 |
+
use tokio_util::sync::CancellationToken;
|
| 31 |
+
|
| 32 |
+
use crate::types::{ChatRequest, Provider, ProviderStream, StreamChunk};
|
| 33 |
+
|
| 34 |
+
/// 混合流配置。
|
| 35 |
+
#[derive(Debug, Clone)]
|
| 36 |
+
pub struct HybridConfig {
|
| 37 |
+
/// 等本机草稿流建立的上限。超时就先不管草稿(云端照跑)。
|
| 38 |
+
pub fast_open_timeout: Duration,
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
impl Default for HybridConfig {
|
| 42 |
+
fn default() -> Self {
|
| 43 |
+
Self {
|
| 44 |
+
fast_open_timeout: Duration::from_millis(50),
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
/// 混合流跑完后的结果。
|
| 50 |
+
#[derive(Debug, Clone, Default)]
|
| 51 |
+
pub struct HybridResult {
|
| 52 |
+
/// 最终正文(接棒后是云端内容;未接棒则是本地草稿)。
|
| 53 |
+
pub content: String,
|
| 54 |
+
/// 是否真的发生了"云端接棒"。
|
| 55 |
+
pub used_cloud: bool,
|
| 56 |
+
/// 是否正常结束(false = 被取消 / 异常)。
|
| 57 |
+
pub finished: bool,
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
/// 跑一次混合流。所有分片通过 `emit` 回调下发给调用方(接 WebSocket / IPC / SSE)。
|
| 61 |
+
///
|
| 62 |
+
/// - `fast`:本机快模型(预热过,首字 ~0.08s)
|
| 63 |
+
/// - `slow`:云端慢模型(质量担当)
|
| 64 |
+
/// - `fast_request`:通常复用 `slow_request` 的消息上下文,但关思考 + 小 max_tokens
|
| 65 |
+
///
|
| 66 |
+
/// 返回时流已结束(正常 Done / 出错 / 取消)。
|
| 67 |
+
pub async fn run_hybrid<F>(
|
| 68 |
+
fast: Arc<dyn Provider>,
|
| 69 |
+
slow: Arc<dyn Provider>,
|
| 70 |
+
fast_request: ChatRequest,
|
| 71 |
+
slow_request: ChatRequest,
|
| 72 |
+
cancel: CancellationToken,
|
| 73 |
+
config: HybridConfig,
|
| 74 |
+
mut emit: F,
|
| 75 |
+
) -> HybridResult
|
| 76 |
+
where
|
| 77 |
+
F: FnMut(StreamChunk),
|
| 78 |
+
{
|
| 79 |
+
let mut content = String::new();
|
| 80 |
+
let mut used_cloud = false;
|
| 81 |
+
|
| 82 |
+
// ── 同时开两条流 ────────────────────────────────────────────────
|
| 83 |
+
// 云端正式连接**立刻**发起(本机草稿绝不能推迟它);
|
| 84 |
+
// 本机草稿给一个短超时,太慢就当没有草稿。
|
| 85 |
+
let fast_cancel = cancel.clone();
|
| 86 |
+
let slow_cancel = cancel.clone();
|
| 87 |
+
let fast_open = async move {
|
| 88 |
+
tokio::time::timeout(
|
| 89 |
+
config.fast_open_timeout,
|
| 90 |
+
fast.chat_stream(fast_request, fast_cancel),
|
| 91 |
+
)
|
| 92 |
+
.await
|
| 93 |
+
.unwrap_or_else(|_| Err("draft not ready".to_string()))
|
| 94 |
+
};
|
| 95 |
+
let (fast_res, slow_res) = tokio::select! {
|
| 96 |
+
biased;
|
| 97 |
+
_ = cancel.cancelled() => {
|
| 98 |
+
return HybridResult { content, used_cloud, finished: false };
|
| 99 |
+
}
|
| 100 |
+
results = async { tokio::join!(fast_open, slow.chat_stream(slow_request, slow_cancel)) } => results,
|
| 101 |
+
};
|
| 102 |
+
|
| 103 |
+
let mut fast_stream: Option<ProviderStream> = fast_res.ok();
|
| 104 |
+
let mut slow_stream = match slow_res {
|
| 105 |
+
Ok(s) => s,
|
| 106 |
+
Err(message) => {
|
| 107 |
+
// 云端建流失败 → 退回纯本地(有草稿就继续跑完,没有就报错)
|
| 108 |
+
if let Some(mut fast) = fast_stream.take() {
|
| 109 |
+
while let Some(chunk) = fast.next().await {
|
| 110 |
+
match chunk {
|
| 111 |
+
StreamChunk::Delta { text } => {
|
| 112 |
+
content.push_str(&text);
|
| 113 |
+
emit(StreamChunk::Delta { text });
|
| 114 |
+
}
|
| 115 |
+
StreamChunk::Done { .. } => {
|
| 116 |
+
emit(chunk);
|
| 117 |
+
return HybridResult { content, used_cloud, finished: true };
|
| 118 |
+
}
|
| 119 |
+
StreamChunk::Error { message } => {
|
| 120 |
+
emit(StreamChunk::Error { message });
|
| 121 |
+
return HybridResult { content, used_cloud, finished: false };
|
| 122 |
+
}
|
| 123 |
+
other => emit(other),
|
| 124 |
+
}
|
| 125 |
+
}
|
| 126 |
+
return HybridResult { content, used_cloud, finished: true };
|
| 127 |
+
}
|
| 128 |
+
emit(StreamChunk::Error { message });
|
| 129 |
+
return HybridResult { content, used_cloud, finished: false };
|
| 130 |
+
}
|
| 131 |
+
};
|
| 132 |
+
|
| 133 |
+
// ── 阶段 1:本机先答,云端一到就接棒 ───────────────────────────
|
| 134 |
+
loop {
|
| 135 |
+
if cancel.is_cancelled() {
|
| 136 |
+
return HybridResult { content, used_cloud, finished: false };
|
| 137 |
+
}
|
| 138 |
+
if used_cloud {
|
| 139 |
+
// ── 阶段 2:只消费云端 ──────────────────────────────────
|
| 140 |
+
match slow_stream.next().await {
|
| 141 |
+
Some(StreamChunk::Delta { text }) => {
|
| 142 |
+
content.push_str(&text);
|
| 143 |
+
emit(StreamChunk::Delta { text });
|
| 144 |
+
}
|
| 145 |
+
Some(StreamChunk::Done { .. }) => {
|
| 146 |
+
emit(StreamChunk::Done {
|
| 147 |
+
prompt_tokens: None,
|
| 148 |
+
completion_tokens: None,
|
| 149 |
+
eval_ms: None,
|
| 150 |
+
cached_tokens: None,
|
| 151 |
+
});
|
| 152 |
+
return HybridResult { content, used_cloud, finished: true };
|
| 153 |
+
}
|
| 154 |
+
Some(StreamChunk::Error { message }) => {
|
| 155 |
+
emit(StreamChunk::Error { message });
|
| 156 |
+
return HybridResult { content, used_cloud, finished: false };
|
| 157 |
+
}
|
| 158 |
+
Some(other) => emit(other),
|
| 159 |
+
None => {
|
| 160 |
+
// 云端流提前结束(没发 Done):按完成处理
|
| 161 |
+
return HybridResult { content, used_cloud, finished: true };
|
| 162 |
+
}
|
| 163 |
+
}
|
| 164 |
+
} else {
|
| 165 |
+
tokio::select! {
|
| 166 |
+
_ = cancel.cancelled() => {
|
| 167 |
+
return HybridResult { content, used_cloud, finished: false };
|
| 168 |
+
}
|
| 169 |
+
f = next_opt(&mut fast_stream) => {
|
| 170 |
+
match f {
|
| 171 |
+
Some(StreamChunk::Delta { text }) => {
|
| 172 |
+
content.push_str(&text);
|
| 173 |
+
emit(StreamChunk::Delta { text });
|
| 174 |
+
}
|
| 175 |
+
Some(_) => {}
|
| 176 |
+
None => { fast_stream = None; }
|
| 177 |
+
}
|
| 178 |
+
}
|
| 179 |
+
s = slow_stream.next() => {
|
| 180 |
+
match s {
|
| 181 |
+
Some(StreamChunk::Delta { text }) => {
|
| 182 |
+
// ── 接棒:清草稿 + 发 Replaced + 用云端继续 ──
|
| 183 |
+
used_cloud = true;
|
| 184 |
+
content.clear();
|
| 185 |
+
emit(StreamChunk::Replaced {
|
| 186 |
+
message: "云端模型已接棒".to_string(),
|
| 187 |
+
});
|
| 188 |
+
content.push_str(&text);
|
| 189 |
+
emit(StreamChunk::Delta { text });
|
| 190 |
+
}
|
| 191 |
+
Some(StreamChunk::Done {
|
| 192 |
+
prompt_tokens,
|
| 193 |
+
completion_tokens,
|
| 194 |
+
eval_ms,
|
| 195 |
+
cached_tokens,
|
| 196 |
+
}) => {
|
| 197 |
+
// 云端没有正文就结束(本地草稿作为结果)
|
| 198 |
+
emit(StreamChunk::Done {
|
| 199 |
+
prompt_tokens,
|
| 200 |
+
completion_tokens,
|
| 201 |
+
eval_ms,
|
| 202 |
+
cached_tokens,
|
| 203 |
+
});
|
| 204 |
+
return HybridResult { content, used_cloud, finished: true };
|
| 205 |
+
}
|
| 206 |
+
Some(StreamChunk::Error { message }) => {
|
| 207 |
+
// 云端失败:本地草稿保留,按完成收尾
|
| 208 |
+
if content.trim().is_empty() {
|
| 209 |
+
emit(StreamChunk::Error { message });
|
| 210 |
+
return HybridResult { content, used_cloud, finished: false };
|
| 211 |
+
}
|
| 212 |
+
return HybridResult { content, used_cloud, finished: true };
|
| 213 |
+
}
|
| 214 |
+
Some(other) => emit(other),
|
| 215 |
+
None => {
|
| 216 |
+
// 云端流提前结束:草稿作为结果
|
| 217 |
+
return HybridResult { content, used_cloud, finished: true };
|
| 218 |
+
}
|
| 219 |
+
}
|
| 220 |
+
}
|
| 221 |
+
}
|
| 222 |
+
}
|
| 223 |
+
}
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
/// 取流的下一个元素;流已经关闭(None)时**永远挂起**,
|
| 227 |
+
/// 这样 `select!` 里另一条流可以继续被轮询。
|
| 228 |
+
async fn next_opt(stream: &mut Option<ProviderStream>) -> Option<StreamChunk> {
|
| 229 |
+
match stream.as_mut() {
|
| 230 |
+
Some(s) => s.next().await,
|
| 231 |
+
None => std::future::pending().await,
|
| 232 |
+
}
|
| 233 |
+
}
|
src/lib.rs
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! # perch-ultrafast
|
| 2 |
+
//!
|
| 3 |
+
//! **混合流 + Ultrafast 推理框架**——把"用户感觉慢"从架构层面解决。
|
| 4 |
+
//!
|
| 5 |
+
//! 从 [栖木 Perch](https://huggingface.co/hongcoding/perch)(macOS 本地优先 AI 工作台)
|
| 6 |
+
//! 中提取的可复用 Rust crate。
|
| 7 |
+
//!
|
| 8 |
+
//! ## 解决的问题
|
| 9 |
+
//!
|
| 10 |
+
//! 云端大模型首 token 延迟 0.5~2s,用户盯着空屏幕等。本机小模型首 token 0.05~0.2s。
|
| 11 |
+
//!
|
| 12 |
+
//! **混合流**:两条流同时开——本机先出草稿(用户立刻有东西读),云端一到就接棒
|
| 13 |
+
//! (质量升级)。首字延迟 = 本机延迟,最终质量 = 云端质量。
|
| 14 |
+
//!
|
| 15 |
+
//! ## 快速开始
|
| 16 |
+
//!
|
| 17 |
+
//! ```rust,no_run
|
| 18 |
+
//! use std::sync::Arc;
|
| 19 |
+
//! use perch_ultrafast::{hybrid::{run_hybrid, HybridConfig}, types::*};
|
| 20 |
+
//! use tokio_util::sync::CancellationToken;
|
| 21 |
+
//!
|
| 22 |
+
//! # async fn demo(local: Arc<dyn Provider>, cloud: Arc<dyn Provider>, req: ChatRequest) {
|
| 23 |
+
//! let cancel = CancellationToken::new();
|
| 24 |
+
//! let result = run_hybrid(
|
| 25 |
+
//! local.clone(),
|
| 26 |
+
//! cloud,
|
| 27 |
+
//! ChatRequest { think: Some(ThinkLevel::Off), ..req.clone() }, // 本机:关思考求快
|
| 28 |
+
//! req, // 云端:原样
|
| 29 |
+
//! cancel,
|
| 30 |
+
//! HybridConfig::default(),
|
| 31 |
+
//! |chunk| match chunk {
|
| 32 |
+
//! StreamChunk::Delta { text } => print!("{text}"),
|
| 33 |
+
//! StreamChunk::Replaced { .. } => println!("\n[云端接棒]"),
|
| 34 |
+
//! StreamChunk::Done { .. } => println!("\n[done]"),
|
| 35 |
+
//! _ => {}
|
| 36 |
+
//! },
|
| 37 |
+
//! )
|
| 38 |
+
//! .await;
|
| 39 |
+
//! println!("最终 {} 字,云端接棒 = {}", result.content.chars().count(), result.used_cloud);
|
| 40 |
+
//! # }
|
| 41 |
+
//! ```
|
| 42 |
+
//!
|
| 43 |
+
//! ## 两个模块
|
| 44 |
+
//!
|
| 45 |
+
//! - [`hybrid`]:混合流 mux(本机草稿 → 云端接棒,含双向降级)
|
| 46 |
+
//! - [`ultrafast`]:加速规则(关思考 / 回复预算 / 简洁提示 / **模型锁红线**)
|
| 47 |
+
//! - [`pool`]:连接池单例(复用 TCP + TLS,启用压缩)
|
| 48 |
+
//!
|
| 49 |
+
//! ## 实测数据(栖木 Perch,MiMo 云端 + 本机 qwen3-0.6B)
|
| 50 |
+
//!
|
| 51 |
+
//! | 场景 | 首字延迟 | 说明 |
|
| 52 |
+
//! |---|---|---|
|
| 53 |
+
//! | 纯云端 | 0.88~1.39s | 用户盯着空屏幕 |
|
| 54 |
+
//! | 本机热身 | **0.04~0.18s** | 混合流草稿 |
|
| 55 |
+
//! | 混合流首字 | **< 0.2s** | 本机草稿立刻可读 |
|
| 56 |
+
//! | 云端接棒 | ~0.9s | 无缝替换,质量升级 |
|
| 57 |
+
//!
|
| 58 |
+
//! ## 设计红线
|
| 59 |
+
//!
|
| 60 |
+
//! - **加速绝不换模型**(不偷偷路由到小模型)
|
| 61 |
+
//! - **只改本次下发值**(不动用户持久化档位)
|
| 62 |
+
//! - **云端失败保留草稿**(不把用户的答案变成错误)
|
| 63 |
+
//! - **本机失败静默降级**(行为等同没用混合流,不打扰用户)
|
| 64 |
+
|
| 65 |
+
pub mod hybrid;
|
| 66 |
+
pub mod pool;
|
| 67 |
+
pub mod types;
|
| 68 |
+
pub mod ultrafast;
|
| 69 |
+
|
| 70 |
+
pub use hybrid::{run_hybrid, HybridConfig, HybridResult};
|
| 71 |
+
pub use types::{
|
| 72 |
+
BoxFuture, ChatMessage, ChatRequest, MessageRole, Provider, ProviderStream, StreamChunk,
|
| 73 |
+
ThinkLevel,
|
| 74 |
+
};
|
| 75 |
+
pub use ultrafast::{apply_ultrafast, UltrafastConfig};
|
| 76 |
+
|
| 77 |
+
#[cfg(test)]
|
| 78 |
+
mod tests {
|
| 79 |
+
use super::*;
|
| 80 |
+
use std::sync::Arc;
|
| 81 |
+
use tokio_util::sync::CancellationToken;
|
| 82 |
+
|
| 83 |
+
/// 测试用 provider:按给定脚本吐 chunk(真异步,不阻塞 runtime)。
|
| 84 |
+
struct ScriptedProvider {
|
| 85 |
+
chunks: Vec<StreamChunk>,
|
| 86 |
+
delay_ms: u64,
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
impl Provider for ScriptedProvider {
|
| 90 |
+
fn chat_stream(
|
| 91 |
+
&self,
|
| 92 |
+
_request: ChatRequest,
|
| 93 |
+
_cancel: CancellationToken,
|
| 94 |
+
) -> BoxFuture<Result<ProviderStream, String>> {
|
| 95 |
+
let chunks = self.chunks.clone();
|
| 96 |
+
let delay = std::time::Duration::from_millis(self.delay_ms);
|
| 97 |
+
Box::pin(async move {
|
| 98 |
+
let (tx, rx) = tokio::sync::mpsc::channel::<StreamChunk>(16);
|
| 99 |
+
tokio::spawn(async move {
|
| 100 |
+
for chunk in chunks {
|
| 101 |
+
tokio::time::sleep(delay).await;
|
| 102 |
+
if tx.send(chunk).await.is_err() {
|
| 103 |
+
return;
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
});
|
| 107 |
+
let s = futures::stream::unfold(rx, |mut rx| async move {
|
| 108 |
+
rx.recv().await.map(|chunk| (chunk, rx))
|
| 109 |
+
});
|
| 110 |
+
Ok(Box::pin(s) as ProviderStream)
|
| 111 |
+
})
|
| 112 |
+
}
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
fn request() -> ChatRequest {
|
| 116 |
+
ChatRequest {
|
| 117 |
+
model: "m".to_string(),
|
| 118 |
+
messages: vec![],
|
| 119 |
+
think: None,
|
| 120 |
+
max_tokens: None,
|
| 121 |
+
tools: None,
|
| 122 |
+
}
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
#[tokio::test]
|
| 126 |
+
async fn cloud_takes_over_and_replaces_draft() {
|
| 127 |
+
let local = Arc::new(ScriptedProvider {
|
| 128 |
+
chunks: vec![
|
| 129 |
+
StreamChunk::Delta { text: "draft".into() },
|
| 130 |
+
StreamChunk::Done {
|
| 131 |
+
prompt_tokens: None,
|
| 132 |
+
completion_tokens: None,
|
| 133 |
+
eval_ms: None,
|
| 134 |
+
cached_tokens: None,
|
| 135 |
+
},
|
| 136 |
+
],
|
| 137 |
+
delay_ms: 0,
|
| 138 |
+
});
|
| 139 |
+
let cloud = Arc::new(ScriptedProvider {
|
| 140 |
+
chunks: vec![
|
| 141 |
+
StreamChunk::Delta { text: "final".into() },
|
| 142 |
+
StreamChunk::Done {
|
| 143 |
+
prompt_tokens: None,
|
| 144 |
+
completion_tokens: None,
|
| 145 |
+
eval_ms: None,
|
| 146 |
+
cached_tokens: None,
|
| 147 |
+
},
|
| 148 |
+
],
|
| 149 |
+
delay_ms: 30,
|
| 150 |
+
});
|
| 151 |
+
let mut events = Vec::new();
|
| 152 |
+
let result = run_hybrid(
|
| 153 |
+
local,
|
| 154 |
+
cloud,
|
| 155 |
+
request(),
|
| 156 |
+
request(),
|
| 157 |
+
CancellationToken::new(),
|
| 158 |
+
HybridConfig::default(),
|
| 159 |
+
|c| events.push(c),
|
| 160 |
+
)
|
| 161 |
+
.await;
|
| 162 |
+
assert!(result.used_cloud, "云端应该接棒");
|
| 163 |
+
assert_eq!(result.content, "final");
|
| 164 |
+
let replaced = events.iter().any(|c| matches!(c, StreamChunk::Replaced { .. }));
|
| 165 |
+
assert!(replaced, "接棒时应下发 Replaced 让前端清草稿");
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
#[tokio::test]
|
| 169 |
+
async fn cloud_failure_falls_back_to_local() {
|
| 170 |
+
struct FailingProvider;
|
| 171 |
+
impl Provider for FailingProvider {
|
| 172 |
+
fn chat_stream(
|
| 173 |
+
&self,
|
| 174 |
+
_request: ChatRequest,
|
| 175 |
+
_cancel: CancellationToken,
|
| 176 |
+
) -> BoxFuture<Result<ProviderStream, String>> {
|
| 177 |
+
Box::pin(async { Err("cloud down".to_string()) })
|
| 178 |
+
}
|
| 179 |
+
}
|
| 180 |
+
let local = Arc::new(ScriptedProvider {
|
| 181 |
+
chunks: vec![
|
| 182 |
+
StreamChunk::Delta { text: "local only".into() },
|
| 183 |
+
StreamChunk::Done {
|
| 184 |
+
prompt_tokens: None,
|
| 185 |
+
completion_tokens: None,
|
| 186 |
+
eval_ms: None,
|
| 187 |
+
cached_tokens: None,
|
| 188 |
+
},
|
| 189 |
+
],
|
| 190 |
+
delay_ms: 0,
|
| 191 |
+
});
|
| 192 |
+
let result = run_hybrid(
|
| 193 |
+
local,
|
| 194 |
+
Arc::new(FailingProvider),
|
| 195 |
+
request(),
|
| 196 |
+
request(),
|
| 197 |
+
CancellationToken::new(),
|
| 198 |
+
HybridConfig::default(),
|
| 199 |
+
|_| {},
|
| 200 |
+
)
|
| 201 |
+
.await;
|
| 202 |
+
assert!(!result.used_cloud);
|
| 203 |
+
assert_eq!(result.content, "local only", "云端挂了应保留本地草稿");
|
| 204 |
+
assert!(result.finished);
|
| 205 |
+
}
|
| 206 |
+
}
|
src/pool.rs
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! 连接池:进程级单例 `reqwest::Client`。
|
| 2 |
+
//!
|
| 3 |
+
//! 每次新建 client = 每条请求都白付一次 TCP + TLS 握手(几十到几百 ms)。
|
| 4 |
+
//! 做成单例后,第二条请求起直接复用连接 → 流式首 token 明显提前。
|
| 5 |
+
//!
|
| 6 |
+
//! 注意:`reqwest::Client` 内部的连接池是**按 client 实例**管理的,
|
| 7 |
+
//! 所以一定要复用同一个实例,而不是每次请求 new 一个。
|
| 8 |
+
|
| 9 |
+
use std::sync::OnceLock;
|
| 10 |
+
use std::time::Duration;
|
| 11 |
+
|
| 12 |
+
/// 全局单例 HTTP 客户端(首次调用时懒初始化,之后复用)。
|
| 13 |
+
///
|
| 14 |
+
/// 失败会返回错误字符串——调用方可以降级为一次性 client。
|
| 15 |
+
pub fn shared_client() -> Result<reqwest::Client, String> {
|
| 16 |
+
static CLIENT: OnceLock<Result<reqwest::Client, String>> = OnceLock::new();
|
| 17 |
+
CLIENT
|
| 18 |
+
.get_or_init(|| {
|
| 19 |
+
reqwest::Client::builder()
|
| 20 |
+
// 保留空闲连接,供后续请求复用(keep-alive)
|
| 21 |
+
.pool_max_idle_per_host(8)
|
| 22 |
+
.pool_idle_timeout(Duration::from_secs(90))
|
| 23 |
+
.tcp_keepalive(Duration::from_secs(30))
|
| 24 |
+
// 启用压缩:减少下行字节,流式正文更早到
|
| 25 |
+
.gzip(true)
|
| 26 |
+
.brotli(true)
|
| 27 |
+
.deflate(true)
|
| 28 |
+
.build()
|
| 29 |
+
.map_err(|e| format!("初始化 HTTP 客户端失败:{e}"))
|
| 30 |
+
})
|
| 31 |
+
.clone()
|
| 32 |
+
}
|
src/types.rs
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! 核心类型:Provider 抽象 / 流式 chunk / 对话请求。
|
| 2 |
+
//!
|
| 3 |
+
//! 这一层刻意做到最小——你可以把任何 LLM 后端(Ollama / OpenAI 兼容接口 /
|
| 4 |
+
//! 自建推理服务)适配成 `Provider`,混合流与 Ultrafast 规则就能直接复用。
|
| 5 |
+
|
| 6 |
+
use std::future::Future;
|
| 7 |
+
use std::pin::Pin;
|
| 8 |
+
|
| 9 |
+
use futures::Stream;
|
| 10 |
+
use tokio_util::sync::CancellationToken;
|
| 11 |
+
|
| 12 |
+
/// 一个可取消的流式响应流。
|
| 13 |
+
pub type ProviderStream = Pin<Box<dyn Stream<Item = StreamChunk> + Send>>;
|
| 14 |
+
|
| 15 |
+
/// 装箱 future(避免 async-trait 依赖)。
|
| 16 |
+
pub type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
|
| 17 |
+
|
| 18 |
+
/// 流式响应分片。
|
| 19 |
+
#[derive(Debug, Clone)]
|
| 20 |
+
pub enum StreamChunk {
|
| 21 |
+
/// 正文增量。
|
| 22 |
+
Delta { text: String },
|
| 23 |
+
/// 思考过程增量(推理模型)。
|
| 24 |
+
Reasoning { text: String },
|
| 25 |
+
/// 接棒信号:混合流从"本机草稿"切到"云端正式"时下发,
|
| 26 |
+
/// 前端应清空已显示的草稿内容再继续渲染后续 delta。
|
| 27 |
+
Replaced { message: String },
|
| 28 |
+
/// 正常结束(带用量统计)。
|
| 29 |
+
Done {
|
| 30 |
+
prompt_tokens: Option<u64>,
|
| 31 |
+
completion_tokens: Option<u64>,
|
| 32 |
+
eval_ms: Option<u64>,
|
| 33 |
+
cached_tokens: Option<u64>,
|
| 34 |
+
},
|
| 35 |
+
/// 出错。
|
| 36 |
+
Error { message: String },
|
| 37 |
+
/// 被截断(达到 max_tokens 上限等)。
|
| 38 |
+
Truncated { message: String },
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
/// 思考强度档位。
|
| 42 |
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
| 43 |
+
pub enum ThinkLevel {
|
| 44 |
+
Off,
|
| 45 |
+
Low,
|
| 46 |
+
Medium,
|
| 47 |
+
High,
|
| 48 |
+
Frenzy,
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
impl Default for ThinkLevel {
|
| 52 |
+
fn default() -> Self {
|
| 53 |
+
ThinkLevel::Medium
|
| 54 |
+
}
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
/// 一条对话消息。
|
| 58 |
+
#[derive(Debug, Clone)]
|
| 59 |
+
pub struct ChatMessage {
|
| 60 |
+
pub role: MessageRole,
|
| 61 |
+
pub content: String,
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
| 65 |
+
pub enum MessageRole {
|
| 66 |
+
System,
|
| 67 |
+
User,
|
| 68 |
+
Assistant,
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
/// 一次对话请求。`model` 是"模型锁"的落点:加速开关**不允许**改它。
|
| 72 |
+
#[derive(Debug, Clone, Default)]
|
| 73 |
+
pub struct ChatRequest {
|
| 74 |
+
pub model: String,
|
| 75 |
+
pub messages: Vec<ChatMessage>,
|
| 76 |
+
pub think: Option<ThinkLevel>,
|
| 77 |
+
pub max_tokens: Option<u32>,
|
| 78 |
+
/// 工具定义等由调用方自行透传;框架不解释其语义。
|
| 79 |
+
pub tools: Option<serde_json::Value>,
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
/// 任何能流式输出 LLM 回复的后端。
|
| 83 |
+
pub trait Provider: Send + Sync {
|
| 84 |
+
/// 发起一次流式请求。`cancel` 被触发时应尽快结束流并返回。
|
| 85 |
+
fn chat_stream(
|
| 86 |
+
&self,
|
| 87 |
+
request: ChatRequest,
|
| 88 |
+
cancel: CancellationToken,
|
| 89 |
+
) -> BoxFuture<Result<ProviderStream, String>>;
|
| 90 |
+
}
|
src/ultrafast.rs
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//! Ultrafast 推理框架:不换模型、不切 provider,只靠"减少浪费"把延迟压下来。
|
| 2 |
+
//!
|
| 3 |
+
//! # 三条加速法则
|
| 4 |
+
//!
|
| 5 |
+
//! 1. **关思考**(think-off):推理模型的 thinking 链会显著拉高首 token 延迟。
|
| 6 |
+
//! 加速模式在**下发时**把思考档强制为 off——只影响本次请求,不改用户持久化档位。
|
| 7 |
+
//! 2. **连接池复用**:HTTP 客户端做成进程级单例,省掉每条请求的 TCP + TLS 握手。
|
| 8 |
+
//! 3. **回复预算**:未指定时用一个较小的 `max_tokens`(如 2048),避免模型啰嗦。
|
| 9 |
+
//!
|
| 10 |
+
//! # 红线
|
| 11 |
+
//!
|
| 12 |
+
//! - **锁模型**:加速开关绝不允许更换模型(速度不能靠"偷偷换成更快的模型")。
|
| 13 |
+
//! - **只改下发值**:关掉开关立刻回到用户原来的思考档位。
|
| 14 |
+
//! - **不改协议**:只复用连接,不改请求协议(避免触发风控)。
|
| 15 |
+
|
| 16 |
+
use crate::types::{ChatRequest, ThinkLevel};
|
| 17 |
+
|
| 18 |
+
/// Ultrafast 配置。
|
| 19 |
+
#[derive(Debug, Clone)]
|
| 20 |
+
pub struct UltrafastConfig {
|
| 21 |
+
/// 是否强制关思考(下发值,不改用户存档)。
|
| 22 |
+
pub force_think_off: bool,
|
| 23 |
+
/// 未显式指定时的回复上限(`None` = 不限制)。
|
| 24 |
+
pub default_max_tokens: Option<u32>,
|
| 25 |
+
/// 是否插入"简洁作答"系统提示(让模型少写铺垫)。
|
| 26 |
+
pub concise_prompt: bool,
|
| 27 |
+
/// 简洁提示的文案(可自定义/本地化)。
|
| 28 |
+
pub concise_prompt_text: String,
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
impl Default for UltrafastConfig {
|
| 32 |
+
fn default() -> Self {
|
| 33 |
+
Self {
|
| 34 |
+
force_think_off: true,
|
| 35 |
+
default_max_tokens: Some(2048),
|
| 36 |
+
concise_prompt: true,
|
| 37 |
+
concise_prompt_text: "请简洁作答,直接给结论,减少铺垫。".to_string(),
|
| 38 |
+
}
|
| 39 |
+
}
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
/// 应用 Ultrafast 规则到一次请求上(**原地修改,不碰 model**)。
|
| 43 |
+
///
|
| 44 |
+
/// 返回值是实际生效的规则说明(便于前端展示/审计):
|
| 45 |
+
/// 例如 `["think-off", "budget=2048", "concise"]`。
|
| 46 |
+
pub fn apply_ultrafast(request: &mut ChatRequest, config: &UltrafastConfig) -> Vec<String> {
|
| 47 |
+
let mut applied = Vec::new();
|
| 48 |
+
|
| 49 |
+
// 法则 1:关思考(只改本次下发值)
|
| 50 |
+
if config.force_think_off {
|
| 51 |
+
request.think = Some(ThinkLevel::Off);
|
| 52 |
+
applied.push("think-off".to_string());
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
// 法则 3:回复预算(只在调用方没显式指定时兜底)
|
| 56 |
+
if let (None, Some(budget)) = (request.max_tokens, config.default_max_tokens) {
|
| 57 |
+
request.max_tokens = Some(budget);
|
| 58 |
+
applied.push(format!("budget={budget}"));
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
// 简洁提示(插到消息最前面,仅当没有 system 消息时)
|
| 62 |
+
if config.concise_prompt
|
| 63 |
+
&& !config.concise_prompt_text.trim().is_empty()
|
| 64 |
+
&& !request
|
| 65 |
+
.messages
|
| 66 |
+
.iter()
|
| 67 |
+
.any(|m| m.role == crate::types::MessageRole::System)
|
| 68 |
+
{
|
| 69 |
+
request.messages.insert(
|
| 70 |
+
0,
|
| 71 |
+
crate::types::ChatMessage {
|
| 72 |
+
role: crate::types::MessageRole::System,
|
| 73 |
+
content: config.concise_prompt_text.clone(),
|
| 74 |
+
},
|
| 75 |
+
);
|
| 76 |
+
applied.push("concise".to_string());
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
// 红线:模型锁——这里**故意什么都不做**。
|
| 80 |
+
// `request.model` 永远保持调用方设置的值,加速开关无权改它。
|
| 81 |
+
|
| 82 |
+
applied
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
#[cfg(test)]
|
| 86 |
+
mod tests {
|
| 87 |
+
use super::*;
|
| 88 |
+
use crate::types::{ChatMessage, MessageRole};
|
| 89 |
+
|
| 90 |
+
fn req() -> ChatRequest {
|
| 91 |
+
ChatRequest {
|
| 92 |
+
model: "cloud-big".to_string(),
|
| 93 |
+
messages: vec![ChatMessage {
|
| 94 |
+
role: MessageRole::User,
|
| 95 |
+
content: "hi".to_string(),
|
| 96 |
+
}],
|
| 97 |
+
think: Some(ThinkLevel::High),
|
| 98 |
+
max_tokens: None,
|
| 99 |
+
tools: None,
|
| 100 |
+
}
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
#[test]
|
| 104 |
+
fn forces_think_off_without_touching_model() {
|
| 105 |
+
let mut request = req();
|
| 106 |
+
apply_ultrafast(&mut request, &UltrafastConfig::default());
|
| 107 |
+
assert_eq!(request.think, Some(ThinkLevel::Off));
|
| 108 |
+
// 红线:模型锁
|
| 109 |
+
assert_eq!(request.model, "cloud-big");
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
#[test]
|
| 113 |
+
fn respects_explicit_max_tokens() {
|
| 114 |
+
let mut request = req();
|
| 115 |
+
request.max_tokens = Some(8192);
|
| 116 |
+
apply_ultrafast(&mut request, &UltrafastConfig::default());
|
| 117 |
+
assert_eq!(request.max_tokens, Some(8192), "用户显式设定的上限不能被覆盖");
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
#[test]
|
| 121 |
+
fn inserts_concise_prompt_once() {
|
| 122 |
+
let mut request = req();
|
| 123 |
+
apply_ultrafast(&mut request, &UltrafastConfig::default());
|
| 124 |
+
let systems = request
|
| 125 |
+
.messages
|
| 126 |
+
.iter()
|
| 127 |
+
.filter(|m| m.role == MessageRole::System)
|
| 128 |
+
.count();
|
| 129 |
+
assert_eq!(systems, 1);
|
| 130 |
+
// 再跑一次不会重复插入
|
| 131 |
+
apply_ultrafast(&mut request, &UltrafastConfig::default());
|
| 132 |
+
let systems = request
|
| 133 |
+
.messages
|
| 134 |
+
.iter()
|
| 135 |
+
.filter(|m| m.role == MessageRole::System)
|
| 136 |
+
.count();
|
| 137 |
+
assert_eq!(systems, 1);
|
| 138 |
+
}
|
| 139 |
+
}
|