| 1 | //! utopia-llm: OpenAI 兼容协议的薄客户端。 |
| 2 | //! 一套代码适配 DeepSeek / Qwen(DashScope 兼容模式) / GLM / OpenAI / Ollama / vLLM。 |
| 3 | |
| 4 | use futures_util::{Stream, StreamExt}; |
| 5 | use serde::{Deserialize, Serialize}; |
| 6 | use serde_json::json; |
| 7 | use std::time::Duration; |
| 8 | |
| 9 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 10 | pub struct ChatMessage { |
| 11 | pub role: String, |
| 12 | pub content: String, |
| 13 | } |
| 14 | |
| 15 | /// OpenAI 协议的工具调用(assistant 回合携带)。 |
| 16 | #[derive(Debug, Clone)] |
| 17 | pub struct ToolCall { |
| 18 | pub id: String, |
| 19 | pub name: String, |
| 20 | /// JSON 字符串参数(协议原样透传) |
| 21 | pub arguments: String, |
| 22 | } |
| 23 | |
| 24 | /// 工具对话的一个 assistant 回合:文本与工具调用至少其一。 |
| 25 | #[derive(Debug)] |
| 26 | pub struct AssistantTurn { |
| 27 | pub content: Option<String>, |
| 28 | pub tool_calls: Vec<ToolCall>, |
| 29 | } |
| 30 | |
| 31 | impl AssistantTurn { |
| 32 | /// 还原为 OpenAI 协议的 assistant 消息(回灌对话历史用)。 |
| 33 | pub fn to_message(&self) -> serde_json::Value { |
| 34 | let mut msg = json!({ "role": "assistant", "content": self.content }); |
| 35 | if !self.tool_calls.is_empty() { |
| 36 | msg["tool_calls"] = json!(self |
| 37 | .tool_calls |
| 38 | .iter() |
| 39 | .map(|c| json!({ |
| 40 | "id": c.id, |
| 41 | "type": "function", |
| 42 | "function": { "name": c.name, "arguments": c.arguments }, |
| 43 | })) |
| 44 | .collect::<Vec<_>>()); |
| 45 | } |
| 46 | msg |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | /// 工具结果消息(role=tool)。 |
| 51 | pub fn tool_result_message(tool_call_id: &str, content: &str) -> serde_json::Value { |
| 52 | json!({ "role": "tool", "tool_call_id": tool_call_id, "content": content }) |
| 53 | } |
| 54 | |
| 55 | /// 带工具的流式回合事件。 |
| 56 | #[derive(Debug)] |
| 57 | pub enum ToolStreamItem { |
| 58 | /// 增量正文(即时转发给前端) |
| 59 | Delta(String), |
| 60 | /// 流结束:完整回合(累积正文 + 归并后的工具调用) |
| 61 | Turn(AssistantTurn), |
| 62 | } |
| 63 | |
| 64 | /// **没能从端点拿到一个能解析的回答。** 两种:连不上(DNS、连接、TLS、超时), |
| 65 | /// 或者连上了但回来的根本不是这个 API(响应体解不成 JSON)。 |
| 66 | /// |
| 67 | /// 合成一类是有意的:从用户那边看这两种是同一件事——"你配的这个地址不是模型 API", |
| 68 | /// 该做的也是同一件事:去看 URL、看代理。第一版只收传输层失败,结果最常见的那种 |
| 69 | /// 故障(URL 配错、代理挡在中间回了 HTML)一条告警都不产生, |
| 70 | /// 正是"失败无声"本身。 |
| 71 | /// |
| 72 | /// **不含**端点干干净净地回了 4xx/5xx:那说明它就是模型 API,只是密钥、 |
| 73 | /// 配额或模型名不对——另一类问题,该找的人也不同。 |
| 74 | /// |
| 75 | /// 有类型而不是匹配错误文本:调用链上任何一层加一句 context 都会改文本, |
| 76 | /// 而 `anyhow` 的 source 链让 `downcast_ref` 一路都认得出来。 |
| 77 | #[derive(Debug, thiserror::Error)] |
| 78 | #[error("LLM endpoint gave no usable answer: {0}")] |
| 79 | pub struct Unreachable(#[from] pub reqwest::Error); |
| 80 | |
| 81 | /// anyhow 错误链里有没有 [`Unreachable`]。 |
| 82 | pub fn is_unreachable(err: &anyhow::Error) -> bool { |
| 83 | err.chain().any(|e| e.is::<Unreachable>()) |
| 84 | } |
| 85 | |
| 86 | /// 端点在限流。**跟 [`Unreachable`] 一样做成类型**,理由也一样:调用方要据此 |
| 87 | /// 决定「等一会儿再来」而不是「这块废了」,而错误文本一路都在被 context 改写。 |
| 88 | /// |
| 89 | /// 限流与其他 4xx 的区别是**它会自己好**。密钥错了重试一万次还是错,配额满了 |
| 90 | /// 等一分钟就过去——两者混在一起,重试预算就会花在永远不会好的那一类上。 |
| 91 | #[derive(Debug, thiserror::Error)] |
| 92 | #[error("LLM endpoint is rate limiting ({status}): {detail}")] |
| 93 | pub struct RateLimited { |
| 94 | pub status: u16, |
| 95 | /// **常常是 `None`。** 多数厂商的 429 不带 `Retry-After`(实测 SiliconFlow |
| 96 | /// 就不带),所以调用方必须自带退避,把这一项当「有则更准」的补充而不是判据。 |
| 97 | pub retry_after: Option<Duration>, |
| 98 | pub detail: String, |
| 99 | } |
| 100 | |
| 101 | /// anyhow 错误链里的 [`RateLimited`],穿透 context 层。 |
| 102 | pub fn rate_limited(err: &anyhow::Error) -> Option<&RateLimited> { |
| 103 | err.chain().find_map(|e| e.downcast_ref::<RateLimited>()) |
| 104 | } |
| 105 | |
| 106 | /// 账号付不起这次请求:欠费,或者套餐配额用尽。 |
| 107 | /// |
| 108 | /// **跟 [`RateLimited`] 分开,因为它不会自己好。** 限流等一分钟就过去, |
| 109 | /// 欠费等到天亮也还是欠费——重试只是在把同一个错误说三遍,而真正该发生的事 |
| 110 | /// (有人去充值)不会因为重试而发生。 |
| 111 | /// |
| 112 | /// 实测:一次跑测里 14 篇文档因为它整篇失败,而当时它跟普通失败走同一条路, |
| 113 | /// 唯一能知道原因的办法是去数据库里翻 `graph_error`。 |
| 114 | #[derive(Debug, thiserror::Error)] |
| 115 | #[error("LLM account cannot pay for this request ({status}): {detail}")] |
| 116 | pub struct OutOfCredit { |
| 117 | pub status: u16, |
| 118 | pub detail: String, |
| 119 | } |
| 120 | |
| 121 | /// anyhow 错误链里的 [`OutOfCredit`],穿透 context 层。 |
| 122 | pub fn out_of_credit(err: &anyhow::Error) -> Option<&OutOfCredit> { |
| 123 | err.chain().find_map(|e| e.downcast_ref::<OutOfCredit>()) |
| 124 | } |
| 125 | |
| 126 | /// `Retry-After` 的整数秒形态。 |
| 127 | /// |
| 128 | /// 规范还允许 HTTP-date,这里**不解析**:为一个很少有人发的头引一个日期库不划算, |
| 129 | /// 而解析失败当成没有正是对的——调用方本来就得有退避,多猜一个数只会更难查。 |
| 130 | fn retry_after_of(headers: &reqwest::header::HeaderMap) -> Option<Duration> { |
| 131 | headers |
| 132 | .get(reqwest::header::RETRY_AFTER)? |
| 133 | .to_str() |
| 134 | .ok()? |
| 135 | .trim() |
| 136 | .parse::<u64>() |
| 137 | .ok() |
| 138 | .map(Duration::from_secs) |
| 139 | } |
| 140 | |
| 141 | /// 非 2xx 统一在这里成型,分成三类:欠费、限流、其他。 |
| 142 | /// |
| 143 | /// **503 不算限流**:它可能是端点真挂了、也可能是中间代理,把它算进来会让 |
| 144 | /// 「等一会儿再来」用在等不回来的地方。判据窄一点,宁可退回「其他」。 |
| 145 | fn failure( |
| 146 | kind: &str, |
| 147 | status: reqwest::StatusCode, |
| 148 | retry_after: Option<Duration>, |
| 149 | body: &serde_json::Value, |
| 150 | ) -> anyhow::Error { |
| 151 | let detail = err_detail(body); |
| 152 | // **欠费要先判,而且不能只看状态码。** |
| 153 | // |
| 154 | // 402 是标准答案(SiliconFlow 用它),但 OpenAI 的余额耗尽走的是 **429**, |
| 155 | // 靠 body 里的 `insufficient_quota` 区分。只按状态码分类的话,一个没钱的 |
| 156 | // OpenAI 账号会被当成限流,然后无限退避重试一个永远不会好的东西—— |
| 157 | // 而退避越久,症状越像"端点慢",越查不到根上。 |
| 158 | if status == reqwest::StatusCode::PAYMENT_REQUIRED || says_out_of_credit(body) { |
| 159 | return anyhow::Error::new(OutOfCredit { |
| 160 | status: status.as_u16(), |
| 161 | detail, |
| 162 | }); |
| 163 | } |
| 164 | if status == reqwest::StatusCode::TOO_MANY_REQUESTS { |
| 165 | return anyhow::Error::new(RateLimited { |
| 166 | status: status.as_u16(), |
| 167 | retry_after, |
| 168 | detail, |
| 169 | }); |
| 170 | } |
| 171 | anyhow::anyhow!("{kind} request failed ({status}): {detail}") |
| 172 | } |
| 173 | |
| 174 | #[derive(Clone)] |
| 175 | pub struct LlmClient { |
| 176 | http: reqwest::Client, |
| 177 | base_url: String, |
| 178 | api_key: Option<String>, |
| 179 | pub model: String, |
| 180 | } |
| 181 | |
| 182 | /// 建连多久算失败。 |
| 183 | const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); |
| 184 | |
| 185 | /// **多久没有新字节算这个请求死了。** |
| 186 | /// |
| 187 | /// 不能用 `Client::timeout`(请求总时长):`chat_tools_stream` 是真流式, |
| 188 | /// 一次长对话正当地跑几分钟,总时长封顶会把它拦腰砍断。而 `read_timeout` |
| 189 | /// 量的是**沉默**——流式下 token 持续到达,永远碰不到它;非流式下它兜住的 |
| 190 | /// 正是「请求发出去就石沉大海」。 |
| 191 | /// |
| 192 | /// 为什么是 300 秒而不是 60:非流式调用的首字节要等模型把整段生成完, |
| 193 | /// 大提示词的抽取正常就要 60–120 秒,服务端排队时更久。设小了会把正常请求 |
| 194 | /// 判死,而这条路上「误杀」比「晚 5 分钟发现」贵得多——它会让本来能成的抽取失败。 |
| 195 | /// |
| 196 | /// **没有它的代价实测过**:`reqwest::Client::new()` 默认不设任何超时, |
| 197 | /// 32 路并发打同一个账号时请求全部挂住,32 个 worker 槽被永久占满, |
| 198 | /// 流水线停摆而**一条错误都不报**(jobs 的孤儿回收只在进程启动时跑一次, |
| 199 | /// 进程活着就永远收不了尸)。7459 块的一次灌入死在第 55 块上。 |
| 200 | const READ_TIMEOUT: Duration = Duration::from_secs(300); |
| 201 | |
| 202 | impl LlmClient { |
| 203 | pub fn new(base_url: &str, api_key: Option<&str>, model: &str) -> Self { |
| 204 | Self::with_timeouts(base_url, api_key, model, CONNECT_TIMEOUT, READ_TIMEOUT) |
| 205 | } |
| 206 | |
| 207 | /// 超时可注入,只为**测得动**——生产走 [`LlmClient::new`]。 |
| 208 | /// 拿 300 秒去测一次挂死要跑 5 分钟,那样的测试没人会留着。 |
| 209 | pub fn with_timeouts( |
| 210 | base_url: &str, |
| 211 | api_key: Option<&str>, |
| 212 | model: &str, |
| 213 | connect: Duration, |
| 214 | read: Duration, |
| 215 | ) -> Self { |
| 216 | Self { |
| 217 | http: reqwest::Client::builder() |
| 218 | .connect_timeout(connect) |
| 219 | .read_timeout(read) |
| 220 | .build() |
| 221 | // 只在 TLS 后端起不来时失败,那种情况下退回默认客户端也没有意义, |
| 222 | // 但也不该让整个进程崩在这里 |
| 223 | .unwrap_or_else(|e| { |
| 224 | tracing::error!(error = %e, "HTTP 客户端建不起来,退回无超时的默认客户端"); |
| 225 | reqwest::Client::new() |
| 226 | }), |
| 227 | base_url: base_url.trim_end_matches('/').to_string(), |
| 228 | api_key: api_key.map(String::from), |
| 229 | model: model.to_string(), |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | fn request(&self, path: &str) -> reqwest::RequestBuilder { |
| 234 | let mut req = self.http.post(format!("{}{path}", self.base_url)); |
| 235 | if let Some(key) = &self.api_key { |
| 236 | req = req.bearer_auth(key); |
| 237 | } |
| 238 | req |
| 239 | } |
| 240 | |
| 241 | /// 非流式对话(连通性测试等轻量场景)。 |
| 242 | pub async fn chat(&self, messages: &[ChatMessage]) -> anyhow::Result<String> { |
| 243 | let resp = self |
| 244 | .request("/chat/completions") |
| 245 | .json(&json!({ "model": self.model, "messages": messages, "stream": false })) |
| 246 | .send() |
| 247 | .await |
| 248 | .map_err(Unreachable)?; |
| 249 | let status = resp.status(); |
| 250 | let retry_after = retry_after_of(resp.headers()); |
| 251 | let body: serde_json::Value = resp.json().await.map_err(Unreachable)?; |
| 252 | if !status.is_success() { |
| 253 | return Err(failure("LLM", status, retry_after, &body)); |
| 254 | } |
| 255 | log_usage(&self.model, &body); |
| 256 | body["choices"][0]["message"]["content"] |
| 257 | .as_str() |
| 258 | .map(String::from) |
| 259 | .ok_or_else(|| anyhow::anyhow!("Unexpected LLM response shape: {body}")) |
| 260 | } |
| 261 | |
| 262 | /// 工具对话(非流式):messages 为 OpenAI 协议原始 JSON |
| 263 | /// (支持 assistant.tool_calls 与 role=tool 回合),tools 为 function 定义数组。 |
| 264 | pub async fn chat_tools( |
| 265 | &self, |
| 266 | messages: &[serde_json::Value], |
| 267 | tools: &serde_json::Value, |
| 268 | ) -> anyhow::Result<AssistantTurn> { |
| 269 | let resp = self |
| 270 | .request("/chat/completions") |
| 271 | .json(&json!({ |
| 272 | "model": self.model, |
| 273 | "messages": messages, |
| 274 | "tools": tools, |
| 275 | "stream": false, |
| 276 | })) |
| 277 | .send() |
| 278 | .await |
| 279 | .map_err(Unreachable)?; |
| 280 | let status = resp.status(); |
| 281 | let retry_after = retry_after_of(resp.headers()); |
| 282 | let body: serde_json::Value = resp.json().await.map_err(Unreachable)?; |
| 283 | if !status.is_success() { |
| 284 | return Err(failure("LLM", status, retry_after, &body)); |
| 285 | } |
| 286 | let msg = &body["choices"][0]["message"]; |
| 287 | if msg.is_null() { |
| 288 | anyhow::bail!("Unexpected LLM response shape: {body}"); |
| 289 | } |
| 290 | let content = msg["content"] |
| 291 | .as_str() |
| 292 | .map(String::from) |
| 293 | .filter(|s| !s.is_empty()); |
| 294 | let tool_calls = msg["tool_calls"] |
| 295 | .as_array() |
| 296 | .map(|calls| { |
| 297 | calls |
| 298 | .iter() |
| 299 | .filter_map(|c| { |
| 300 | Some(ToolCall { |
| 301 | id: c["id"].as_str()?.to_string(), |
| 302 | name: c["function"]["name"].as_str()?.to_string(), |
| 303 | arguments: c["function"]["arguments"] |
| 304 | .as_str() |
| 305 | .unwrap_or("{}") |
| 306 | .to_string(), |
| 307 | }) |
| 308 | }) |
| 309 | .collect() |
| 310 | }) |
| 311 | .unwrap_or_default(); |
| 312 | Ok(AssistantTurn { |
| 313 | content, |
| 314 | tool_calls, |
| 315 | }) |
| 316 | } |
| 317 | |
| 318 | /// 工具对话(流式):正文增量即时产出,工具调用按 OpenAI 协议的 |
| 319 | /// index 分片归并(id/name 首帧到达,arguments 逐帧续传),流末给出完整回合。 |
| 320 | pub async fn chat_tools_stream( |
| 321 | &self, |
| 322 | messages: &[serde_json::Value], |
| 323 | tools: &serde_json::Value, |
| 324 | ) -> anyhow::Result<impl Stream<Item = anyhow::Result<ToolStreamItem>> + Send + use<>> { |
| 325 | let resp = self |
| 326 | .request("/chat/completions") |
| 327 | .json(&json!({ |
| 328 | "model": self.model, |
| 329 | "messages": messages, |
| 330 | "tools": tools, |
| 331 | "stream": true, |
| 332 | })) |
| 333 | .send() |
| 334 | .await |
| 335 | .map_err(Unreachable)?; |
| 336 | if !resp.status().is_success() { |
| 337 | let status = resp.status(); |
| 338 | let retry_after = retry_after_of(resp.headers()); |
| 339 | let body: serde_json::Value = resp.json().await.unwrap_or_default(); |
| 340 | return Err(failure("LLM", status, retry_after, &body)); |
| 341 | } |
| 342 | |
| 343 | let mut bytes = resp.bytes_stream(); |
| 344 | let stream = async_stream::try_stream! { |
| 345 | let mut buf = String::new(); |
| 346 | let mut content = String::new(); |
| 347 | let mut calls: Vec<ToolCall> = Vec::new(); |
| 348 | let mut done = false; |
| 349 | 'outer: while let Some(part) = bytes.next().await { |
| 350 | let part = part?; |
| 351 | buf.push_str(&String::from_utf8_lossy(&part)); |
| 352 | while let Some(pos) = buf.find("\n\n") { |
| 353 | let frame = buf[..pos].to_string(); |
| 354 | buf.drain(..pos + 2); |
| 355 | for line in frame.lines() { |
| 356 | let Some(data) = line.strip_prefix("data:").map(str::trim) else { |
| 357 | continue; |
| 358 | }; |
| 359 | if data == "[DONE]" { |
| 360 | done = true; |
| 361 | break 'outer; |
| 362 | } |
| 363 | let Ok(v) = serde_json::from_str::<serde_json::Value>(data) else { |
| 364 | continue; |
| 365 | }; |
| 366 | let delta = &v["choices"][0]["delta"]; |
| 367 | if let Some(text) = delta["content"].as_str() { |
| 368 | if !text.is_empty() { |
| 369 | content.push_str(text); |
| 370 | yield ToolStreamItem::Delta(text.to_string()); |
| 371 | } |
| 372 | } |
| 373 | if let Some(tcs) = delta["tool_calls"].as_array() { |
| 374 | for tc in tcs { |
| 375 | let idx = tc["index"].as_u64().unwrap_or(0) as usize; |
| 376 | while calls.len() <= idx { |
| 377 | calls.push(ToolCall { |
| 378 | id: String::new(), |
| 379 | name: String::new(), |
| 380 | arguments: String::new(), |
| 381 | }); |
| 382 | } |
| 383 | let slot = &mut calls[idx]; |
| 384 | if let Some(id) = tc["id"].as_str() { |
| 385 | slot.id.push_str(id); |
| 386 | } |
| 387 | if let Some(n) = tc["function"]["name"].as_str() { |
| 388 | slot.name.push_str(n); |
| 389 | } |
| 390 | if let Some(a) = tc["function"]["arguments"].as_str() { |
| 391 | slot.arguments.push_str(a); |
| 392 | } |
| 393 | } |
| 394 | } |
| 395 | } |
| 396 | } |
| 397 | } |
| 398 | let _ = done; |
| 399 | calls.retain(|c| !c.name.is_empty()); |
| 400 | let content = if content.is_empty() { None } else { Some(content) }; |
| 401 | yield ToolStreamItem::Turn(AssistantTurn { content, tool_calls: calls }); |
| 402 | }; |
| 403 | Ok(stream) |
| 404 | } |
| 405 | |
| 406 | /// 流式对话:产出增量文本片段。 |
| 407 | pub async fn chat_stream( |
| 408 | &self, |
| 409 | messages: &[ChatMessage], |
| 410 | ) -> anyhow::Result<impl Stream<Item = anyhow::Result<String>> + Send + use<>> { |
| 411 | let messages = messages |
| 412 | .iter() |
| 413 | .map(|m| serde_json::to_value(m).unwrap_or_default()) |
| 414 | .collect::<Vec<_>>(); |
| 415 | self.chat_stream_raw(&messages).await |
| 416 | } |
| 417 | |
| 418 | /// 流式对话(原始 JSON 消息,可携带工具回合上下文)。 |
| 419 | pub async fn chat_stream_raw( |
| 420 | &self, |
| 421 | messages: &[serde_json::Value], |
| 422 | ) -> anyhow::Result<impl Stream<Item = anyhow::Result<String>> + Send + use<>> { |
| 423 | let resp = self |
| 424 | .request("/chat/completions") |
| 425 | .json(&json!({ "model": self.model, "messages": messages, "stream": true })) |
| 426 | .send() |
| 427 | .await |
| 428 | .map_err(Unreachable)?; |
| 429 | if !resp.status().is_success() { |
| 430 | let status = resp.status(); |
| 431 | let retry_after = retry_after_of(resp.headers()); |
| 432 | let body: serde_json::Value = resp.json().await.unwrap_or_default(); |
| 433 | return Err(failure("LLM", status, retry_after, &body)); |
| 434 | } |
| 435 | |
| 436 | let mut bytes = resp.bytes_stream(); |
| 437 | let stream = async_stream::try_stream! { |
| 438 | let mut buf = String::new(); |
| 439 | while let Some(part) = bytes.next().await { |
| 440 | let part = part?; |
| 441 | buf.push_str(&String::from_utf8_lossy(&part)); |
| 442 | // SSE 帧以空行分隔;逐帧取出已完整到达的部分 |
| 443 | while let Some(pos) = buf.find("\n\n") { |
| 444 | let frame = buf[..pos].to_string(); |
| 445 | buf.drain(..pos + 2); |
| 446 | for line in frame.lines() { |
| 447 | let Some(data) = line.strip_prefix("data:").map(str::trim) else { |
| 448 | continue; |
| 449 | }; |
| 450 | if data == "[DONE]" { |
| 451 | return; |
| 452 | } |
| 453 | if let Ok(v) = serde_json::from_str::<serde_json::Value>(data) { |
| 454 | if let Some(delta) = v["choices"][0]["delta"]["content"].as_str() { |
| 455 | if !delta.is_empty() { |
| 456 | yield delta.to_string(); |
| 457 | } |
| 458 | } |
| 459 | } |
| 460 | } |
| 461 | } |
| 462 | } |
| 463 | }; |
| 464 | Ok(stream) |
| 465 | } |
| 466 | |
| 467 | /// 批量 embedding。 |
| 468 | pub async fn embed(&self, texts: &[String]) -> anyhow::Result<Vec<Vec<f32>>> { |
| 469 | let resp = self |
| 470 | .request("/embeddings") |
| 471 | .json(&json!({ "model": self.model, "input": texts })) |
| 472 | .send() |
| 473 | .await |
| 474 | .map_err(Unreachable)?; |
| 475 | let status = resp.status(); |
| 476 | let retry_after = retry_after_of(resp.headers()); |
| 477 | let body: serde_json::Value = resp.json().await.map_err(Unreachable)?; |
| 478 | if !status.is_success() { |
| 479 | return Err(failure("Embedding", status, retry_after, &body)); |
| 480 | } |
| 481 | let data = body["data"] |
| 482 | .as_array() |
| 483 | .ok_or_else(|| anyhow::anyhow!("Unexpected embedding response shape"))?; |
| 484 | let mut out = Vec::with_capacity(data.len()); |
| 485 | for item in data { |
| 486 | let v = item["embedding"] |
| 487 | .as_array() |
| 488 | .ok_or_else(|| anyhow::anyhow!("Embedding 响应缺少向量"))? |
| 489 | .iter() |
| 490 | .filter_map(|x| x.as_f64().map(|f| f as f32)) |
| 491 | .collect(); |
| 492 | out.push(v); |
| 493 | } |
| 494 | Ok(out) |
| 495 | } |
| 496 | } |
| 497 | |
| 498 | /// 记一次调用的 token 开销。**缓存命中数是这里最重要的一列**:抽取靠 |
| 499 | /// "system 消息在一篇文档内逐块完全相同" 吃供应商的前缀缓存, |
| 500 | /// 往 system 里塞逐块变化的内容会让它悄悄归零——只有这个数看得见。 |
| 501 | /// |
| 502 | /// 字段名各家不一:OpenAI 用 prompt_tokens_details.cached_tokens, |
| 503 | /// DeepSeek 用 prompt_cache_hit_tokens。两个都读,谁在读谁。 |
| 504 | fn log_usage(model: &str, body: &serde_json::Value) { |
| 505 | let u = &body["usage"]; |
| 506 | if u.is_null() { |
| 507 | return; |
| 508 | } |
| 509 | let n = |k: &str| u[k].as_u64(); |
| 510 | let cached = u["prompt_tokens_details"]["cached_tokens"] |
| 511 | .as_u64() |
| 512 | .or_else(|| n("prompt_cache_hit_tokens")); |
| 513 | tracing::info!( |
| 514 | model, |
| 515 | prompt = n("prompt_tokens"), |
| 516 | completion = n("completion_tokens"), |
| 517 | cached, |
| 518 | "llm usage" |
| 519 | ); |
| 520 | } |
| 521 | |
| 522 | fn err_detail(body: &serde_json::Value) -> String { |
| 523 | body["error"]["message"] |
| 524 | .as_str() |
| 525 | .or_else(|| body["message"].as_str()) |
| 526 | .unwrap_or("unknown error") |
| 527 | .to_string() |
| 528 | } |
| 529 | |
| 530 | /// 响应体说不说这是余额问题。 |
| 531 | /// |
| 532 | /// **给 429 用的**:OpenAI 用同一个状态码表示「太快了」和「没钱了」, |
| 533 | /// `error.code` 或 `error.type` 里的 `insufficient_quota` 才是分界。 |
| 534 | /// |
| 535 | /// 只认这一个标识、不去匹配 message 的自由文本:措辞会改、会本地化, |
| 536 | /// 而 `code` 是接口契约的一部分。认不出来就退回按状态码判,那是安全的一侧 |
| 537 | /// (当成限流退避几次,比当成欠费直接放弃温和)。 |
| 538 | fn says_out_of_credit(body: &serde_json::Value) -> bool { |
| 539 | ["code", "type"] |
| 540 | .iter() |
| 541 | .filter_map(|k| body["error"][k].as_str()) |
| 542 | .any(|v| v == "insufficient_quota") |
| 543 | } |
| 544 | |
| 545 | #[cfg(test)] |
| 546 | mod tests { |
| 547 | use super::*; |
| 548 | |
| 549 | /// 真发一次注定失败的请求,拿一个货真价实的 `reqwest::Error`。 |
| 550 | /// 端口 1 上不会有东西监听,而 127.0.0.1 不走代理。 |
| 551 | async fn a_real_transport_error() -> reqwest::Error { |
| 552 | reqwest::Client::builder() |
| 553 | .no_proxy() |
| 554 | .build() |
| 555 | .unwrap() |
| 556 | .get("http://127.0.0.1:1/") |
| 557 | .send() |
| 558 | .await |
| 559 | .expect_err("端口 1 不该连得上") |
| 560 | } |
| 561 | |
| 562 | /// **接了连接却一个字节都不回**的服务端。 |
| 563 | /// |
| 564 | /// 这是生产上真正发生的形态,也是最难发现的一种:TCP 连得上、TLS 握得成、 |
| 565 | /// 请求发得出去,然后没了。连接错误会立刻报,这种不会——没有超时的话 |
| 566 | /// `send().await` 就永远停在那里,而调用它的 worker 槽再也不释放。 |
| 567 | async fn a_server_that_never_answers() -> std::net::SocketAddr { |
| 568 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 569 | let addr = listener.local_addr().unwrap(); |
| 570 | tokio::spawn(async move { |
| 571 | // 收下连接就攥着不放。**必须持有 socket**:一 drop 就是 FIN, |
| 572 | // 那样测的又变成了连接被关闭,不是沉默 |
| 573 | let mut held = Vec::new(); |
| 574 | while let Ok((sock, _)) = listener.accept().await { |
| 575 | held.push(sock); |
| 576 | } |
| 577 | }); |
| 578 | addr |
| 579 | } |
| 580 | |
| 581 | /// 请求挂住时必须**报错返回**,而不是永远等下去。 |
| 582 | /// |
| 583 | /// 没有这条守着,回归的样子是:一次灌入死在第 55 块,32 个 worker 槽被 |
| 584 | /// 永久占满,jobs 表里全是 running,而日志和界面上一个字都没有。 |
| 585 | #[tokio::test] |
| 586 | async fn a_silent_server_ends_in_an_error_not_a_hang() { |
| 587 | let addr = a_server_that_never_answers().await; |
| 588 | let client = LlmClient::with_timeouts( |
| 589 | &format!("http://{addr}"), |
| 590 | None, |
| 591 | "m", |
| 592 | Duration::from_secs(5), |
| 593 | Duration::from_millis(300), |
| 594 | ); |
| 595 | let started = tokio::time::Instant::now(); |
| 596 | let out = tokio::time::timeout( |
| 597 | std::time::Duration::from_secs(10), |
| 598 | client.chat(&[ChatMessage { |
| 599 | role: "user".into(), |
| 600 | content: "hi".into(), |
| 601 | }]), |
| 602 | ) |
| 603 | .await; |
| 604 | |
| 605 | // 外层 timeout 触发 = 客户端自己没有把它掐掉,正是要修的那个 bug |
| 606 | let inner = out.expect("客户端没有超时,请求一直挂着"); |
| 607 | assert!(inner.is_err(), "沉默的服务端不该被当成成功"); |
| 608 | assert!( |
| 609 | started.elapsed() < std::time::Duration::from_secs(5), |
| 610 | "read_timeout 没生效:等了 {:?}", |
| 611 | started.elapsed() |
| 612 | ); |
| 613 | } |
| 614 | |
| 615 | /// **判定必须穿透 context 层。** |
| 616 | /// |
| 617 | /// 这是整条链上最容易悄悄坏掉的一环:调用方每加一句 `.context("抽取失败")` |
| 618 | /// 就换掉一次错误文本,靠文本匹配的判定当天就废——而症状是告警再也不出现, |
| 619 | /// 没有任何测试会红,用户也不会来报"我没收到告警"。 |
| 620 | #[tokio::test] |
| 621 | async fn unreachable_survives_context_layers() { |
| 622 | let raw = a_real_transport_error().await; |
| 623 | let err = anyhow::Error::new(Unreachable(raw)) |
| 624 | .context("embedding 失败") |
| 625 | .context("process_document 失败"); |
| 626 | assert!(is_unreachable(&err)); |
| 627 | // 顺带钉住"文本会变"这件事本身:最外层已经不含端点的任何字样 |
| 628 | assert!(!err.to_string().contains("endpoint")); |
| 629 | } |
| 630 | |
| 631 | /// 反面:普通错误不该被认成端点问题,否则告警会对任何失败都亮。 |
| 632 | #[tokio::test] |
| 633 | async fn an_ordinary_failure_is_not_the_endpoint() { |
| 634 | let e = anyhow::anyhow!("Embedding 响应缺少向量").context("抽取失败"); |
| 635 | assert!(!is_unreachable(&e)); |
| 636 | } |
| 637 | |
| 638 | /// **限流要穿透 context 层被认出来。** |
| 639 | /// |
| 640 | /// 与 [`unreachable_survives_context_layers`] 同一个理由,后果更重:认不出来 |
| 641 | /// 就退回「这块废了」,而限流本来一分钟后就过去了。实测一次 1884 块的灌入里 |
| 642 | /// 55/60 篇文档因此整篇失败。 |
| 643 | #[tokio::test] |
| 644 | async fn a_rate_limit_survives_context_layers() { |
| 645 | let err = anyhow::Error::new(RateLimited { |
| 646 | status: 429, |
| 647 | retry_after: None, |
| 648 | detail: "TPM limit reached".into(), |
| 649 | }) |
| 650 | .context("抽取失败") |
| 651 | .context("process_document 失败"); |
| 652 | let hit = rate_limited(&err).expect("限流没被认出来"); |
| 653 | assert_eq!(hit.status, 429); |
| 654 | assert!(!err.to_string().contains("rate limiting")); |
| 655 | } |
| 656 | |
| 657 | /// **没有 `Retry-After` 是常规情况,不是异常。** |
| 658 | /// |
| 659 | /// 多数厂商的 429 不带这个头。判定必须只看类型,退避由调用方自己出—— |
| 660 | /// 把 `retry_after.is_some()` 当判据的话,这些厂商一个都识别不了。 |
| 661 | #[tokio::test] |
| 662 | async fn a_rate_limit_without_retry_after_is_still_a_rate_limit() { |
| 663 | let err = anyhow::Error::new(RateLimited { |
| 664 | status: 429, |
| 665 | retry_after: None, |
| 666 | detail: "TPM limit reached".into(), |
| 667 | }); |
| 668 | assert!(rate_limited(&err).is_some()); |
| 669 | assert!(rate_limited(&err).unwrap().retry_after.is_none()); |
| 670 | } |
| 671 | |
| 672 | /// 反面:限流不该被当成端点不可达,两者的处置完全不同。 |
| 673 | #[tokio::test] |
| 674 | async fn a_rate_limit_is_not_an_unreachable_endpoint() { |
| 675 | let err = anyhow::Error::new(RateLimited { |
| 676 | status: 429, |
| 677 | retry_after: Some(Duration::from_secs(7)), |
| 678 | detail: "slow down".into(), |
| 679 | }); |
| 680 | assert!(!is_unreachable(&err)); |
| 681 | assert_eq!( |
| 682 | rate_limited(&err).unwrap().retry_after, |
| 683 | Some(Duration::from_secs(7)) |
| 684 | ); |
| 685 | } |
| 686 | |
| 687 | /// **429 不一定是限流。** OpenAI 用同一个状态码表示「太快了」和「没钱了」, |
| 688 | /// 分界在 `error.code`。只按状态码分类的话,一个没钱的账号会被无限退避 |
| 689 | /// 重试——而重试越久,症状越像「端点慢」,越查不到根上。 |
| 690 | #[test] |
| 691 | fn a_429_that_says_insufficient_quota_is_a_billing_problem() { |
| 692 | let body = serde_json::json!({ |
| 693 | "error": { "message": "You exceeded your current quota", "code": "insufficient_quota" } |
| 694 | }); |
| 695 | let e = failure("LLM", reqwest::StatusCode::TOO_MANY_REQUESTS, None, &body); |
| 696 | assert!(out_of_credit(&e).is_some(), "该判成欠费"); |
| 697 | assert!(rate_limited(&e).is_none(), "不该判成限流"); |
| 698 | } |
| 699 | |
| 700 | /// 402 是标准答案,SiliconFlow 用的就是它。 |
| 701 | #[test] |
| 702 | fn a_402_is_a_billing_problem() { |
| 703 | let body = serde_json::json!({ "message": "Sorry, your account balance is insufficient" }); |
| 704 | let e = failure("LLM", reqwest::StatusCode::PAYMENT_REQUIRED, None, &body); |
| 705 | assert!(out_of_credit(&e).is_some()); |
| 706 | } |
| 707 | |
| 708 | /// 反面:不带那个标识的 429 还是限流,别把会自己好的事判成要人动手。 |
| 709 | #[test] |
| 710 | fn a_plain_429_is_still_a_rate_limit() { |
| 711 | let body = serde_json::json!({ "error": { "message": "TPM limit reached" } }); |
| 712 | let e = failure("LLM", reqwest::StatusCode::TOO_MANY_REQUESTS, None, &body); |
| 713 | assert!(rate_limited(&e).is_some()); |
| 714 | assert!(out_of_credit(&e).is_none()); |
| 715 | } |
| 716 | |
| 717 | /// 反面:别的 4xx 不是限流。密钥错了重试一万次还是错。 |
| 718 | #[tokio::test] |
| 719 | async fn an_auth_failure_is_not_a_rate_limit() { |
| 720 | let e = anyhow::anyhow!("LLM request failed (401 Unauthorized): bad key"); |
| 721 | assert!(rate_limited(&e).is_none()); |
| 722 | } |
| 723 | |
| 724 | /// 端点干干净净地回了 4xx 不算——那说明它就是模型 API, |
| 725 | /// 只是密钥或模型名不对,该找的人和该做的事都不一样。 |
| 726 | #[tokio::test] |
| 727 | async fn a_clean_api_error_is_a_different_problem() { |
| 728 | let e = anyhow::anyhow!("LLM request failed (401 Unauthorized): bad key"); |
| 729 | assert!(!is_unreachable(&e)); |
| 730 | } |
| 731 | } |