| 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 | #[derive(Clone)] |
| 87 | pub struct LlmClient { |
| 88 | http: reqwest::Client, |
| 89 | base_url: String, |
| 90 | api_key: Option<String>, |
| 91 | pub model: String, |
| 92 | } |
| 93 | |
| 94 | /// 建连多久算失败。 |
| 95 | const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); |
| 96 | |
| 97 | /// **多久没有新字节算这个请求死了。** |
| 98 | /// |
| 99 | /// 不能用 `Client::timeout`(请求总时长):`chat_tools_stream` 是真流式, |
| 100 | /// 一次长对话正当地跑几分钟,总时长封顶会把它拦腰砍断。而 `read_timeout` |
| 101 | /// 量的是**沉默**——流式下 token 持续到达,永远碰不到它;非流式下它兜住的 |
| 102 | /// 正是「请求发出去就石沉大海」。 |
| 103 | /// |
| 104 | /// 为什么是 300 秒而不是 60:非流式调用的首字节要等模型把整段生成完, |
| 105 | /// 大提示词的抽取正常就要 60–120 秒,服务端排队时更久。设小了会把正常请求 |
| 106 | /// 判死,而这条路上「误杀」比「晚 5 分钟发现」贵得多——它会让本来能成的抽取失败。 |
| 107 | /// |
| 108 | /// **没有它的代价实测过**:`reqwest::Client::new()` 默认不设任何超时, |
| 109 | /// 32 路并发打同一个账号时请求全部挂住,32 个 worker 槽被永久占满, |
| 110 | /// 流水线停摆而**一条错误都不报**(jobs 的孤儿回收只在进程启动时跑一次, |
| 111 | /// 进程活着就永远收不了尸)。7459 块的一次灌入死在第 55 块上。 |
| 112 | const READ_TIMEOUT: Duration = Duration::from_secs(300); |
| 113 | |
| 114 | impl LlmClient { |
| 115 | pub fn new(base_url: &str, api_key: Option<&str>, model: &str) -> Self { |
| 116 | Self::with_timeouts(base_url, api_key, model, CONNECT_TIMEOUT, READ_TIMEOUT) |
| 117 | } |
| 118 | |
| 119 | /// 超时可注入,只为**测得动**——生产走 [`LlmClient::new`]。 |
| 120 | /// 拿 300 秒去测一次挂死要跑 5 分钟,那样的测试没人会留着。 |
| 121 | pub fn with_timeouts( |
| 122 | base_url: &str, |
| 123 | api_key: Option<&str>, |
| 124 | model: &str, |
| 125 | connect: Duration, |
| 126 | read: Duration, |
| 127 | ) -> Self { |
| 128 | Self { |
| 129 | http: reqwest::Client::builder() |
| 130 | .connect_timeout(connect) |
| 131 | .read_timeout(read) |
| 132 | .build() |
| 133 | // 只在 TLS 后端起不来时失败,那种情况下退回默认客户端也没有意义, |
| 134 | // 但也不该让整个进程崩在这里 |
| 135 | .unwrap_or_else(|e| { |
| 136 | tracing::error!(error = %e, "HTTP 客户端建不起来,退回无超时的默认客户端"); |
| 137 | reqwest::Client::new() |
| 138 | }), |
| 139 | base_url: base_url.trim_end_matches('/').to_string(), |
| 140 | api_key: api_key.map(String::from), |
| 141 | model: model.to_string(), |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | fn request(&self, path: &str) -> reqwest::RequestBuilder { |
| 146 | let mut req = self.http.post(format!("{}{path}", self.base_url)); |
| 147 | if let Some(key) = &self.api_key { |
| 148 | req = req.bearer_auth(key); |
| 149 | } |
| 150 | req |
| 151 | } |
| 152 | |
| 153 | /// 非流式对话(连通性测试等轻量场景)。 |
| 154 | pub async fn chat(&self, messages: &[ChatMessage]) -> anyhow::Result<String> { |
| 155 | let resp = self |
| 156 | .request("/chat/completions") |
| 157 | .json(&json!({ "model": self.model, "messages": messages, "stream": false })) |
| 158 | .send() |
| 159 | .await |
| 160 | .map_err(Unreachable)?; |
| 161 | let status = resp.status(); |
| 162 | let body: serde_json::Value = resp.json().await.map_err(Unreachable)?; |
| 163 | if !status.is_success() { |
| 164 | anyhow::bail!("LLM request failed ({status}): {}", err_detail(&body)); |
| 165 | } |
| 166 | log_usage(&self.model, &body); |
| 167 | body["choices"][0]["message"]["content"] |
| 168 | .as_str() |
| 169 | .map(String::from) |
| 170 | .ok_or_else(|| anyhow::anyhow!("Unexpected LLM response shape: {body}")) |
| 171 | } |
| 172 | |
| 173 | /// 工具对话(非流式):messages 为 OpenAI 协议原始 JSON |
| 174 | /// (支持 assistant.tool_calls 与 role=tool 回合),tools 为 function 定义数组。 |
| 175 | pub async fn chat_tools( |
| 176 | &self, |
| 177 | messages: &[serde_json::Value], |
| 178 | tools: &serde_json::Value, |
| 179 | ) -> anyhow::Result<AssistantTurn> { |
| 180 | let resp = self |
| 181 | .request("/chat/completions") |
| 182 | .json(&json!({ |
| 183 | "model": self.model, |
| 184 | "messages": messages, |
| 185 | "tools": tools, |
| 186 | "stream": false, |
| 187 | })) |
| 188 | .send() |
| 189 | .await |
| 190 | .map_err(Unreachable)?; |
| 191 | let status = resp.status(); |
| 192 | let body: serde_json::Value = resp.json().await.map_err(Unreachable)?; |
| 193 | if !status.is_success() { |
| 194 | anyhow::bail!("LLM request failed ({status}): {}", err_detail(&body)); |
| 195 | } |
| 196 | let msg = &body["choices"][0]["message"]; |
| 197 | if msg.is_null() { |
| 198 | anyhow::bail!("Unexpected LLM response shape: {body}"); |
| 199 | } |
| 200 | let content = msg["content"] |
| 201 | .as_str() |
| 202 | .map(String::from) |
| 203 | .filter(|s| !s.is_empty()); |
| 204 | let tool_calls = msg["tool_calls"] |
| 205 | .as_array() |
| 206 | .map(|calls| { |
| 207 | calls |
| 208 | .iter() |
| 209 | .filter_map(|c| { |
| 210 | Some(ToolCall { |
| 211 | id: c["id"].as_str()?.to_string(), |
| 212 | name: c["function"]["name"].as_str()?.to_string(), |
| 213 | arguments: c["function"]["arguments"] |
| 214 | .as_str() |
| 215 | .unwrap_or("{}") |
| 216 | .to_string(), |
| 217 | }) |
| 218 | }) |
| 219 | .collect() |
| 220 | }) |
| 221 | .unwrap_or_default(); |
| 222 | Ok(AssistantTurn { |
| 223 | content, |
| 224 | tool_calls, |
| 225 | }) |
| 226 | } |
| 227 | |
| 228 | /// 工具对话(流式):正文增量即时产出,工具调用按 OpenAI 协议的 |
| 229 | /// index 分片归并(id/name 首帧到达,arguments 逐帧续传),流末给出完整回合。 |
| 230 | pub async fn chat_tools_stream( |
| 231 | &self, |
| 232 | messages: &[serde_json::Value], |
| 233 | tools: &serde_json::Value, |
| 234 | ) -> anyhow::Result<impl Stream<Item = anyhow::Result<ToolStreamItem>> + Send + use<>> { |
| 235 | let resp = self |
| 236 | .request("/chat/completions") |
| 237 | .json(&json!({ |
| 238 | "model": self.model, |
| 239 | "messages": messages, |
| 240 | "tools": tools, |
| 241 | "stream": true, |
| 242 | })) |
| 243 | .send() |
| 244 | .await |
| 245 | .map_err(Unreachable)?; |
| 246 | if !resp.status().is_success() { |
| 247 | let status = resp.status(); |
| 248 | let body: serde_json::Value = resp.json().await.unwrap_or_default(); |
| 249 | anyhow::bail!("LLM request failed ({status}): {}", err_detail(&body)); |
| 250 | } |
| 251 | |
| 252 | let mut bytes = resp.bytes_stream(); |
| 253 | let stream = async_stream::try_stream! { |
| 254 | let mut buf = String::new(); |
| 255 | let mut content = String::new(); |
| 256 | let mut calls: Vec<ToolCall> = Vec::new(); |
| 257 | let mut done = false; |
| 258 | 'outer: while let Some(part) = bytes.next().await { |
| 259 | let part = part?; |
| 260 | buf.push_str(&String::from_utf8_lossy(&part)); |
| 261 | while let Some(pos) = buf.find("\n\n") { |
| 262 | let frame = buf[..pos].to_string(); |
| 263 | buf.drain(..pos + 2); |
| 264 | for line in frame.lines() { |
| 265 | let Some(data) = line.strip_prefix("data:").map(str::trim) else { |
| 266 | continue; |
| 267 | }; |
| 268 | if data == "[DONE]" { |
| 269 | done = true; |
| 270 | break 'outer; |
| 271 | } |
| 272 | let Ok(v) = serde_json::from_str::<serde_json::Value>(data) else { |
| 273 | continue; |
| 274 | }; |
| 275 | let delta = &v["choices"][0]["delta"]; |
| 276 | if let Some(text) = delta["content"].as_str() { |
| 277 | if !text.is_empty() { |
| 278 | content.push_str(text); |
| 279 | yield ToolStreamItem::Delta(text.to_string()); |
| 280 | } |
| 281 | } |
| 282 | if let Some(tcs) = delta["tool_calls"].as_array() { |
| 283 | for tc in tcs { |
| 284 | let idx = tc["index"].as_u64().unwrap_or(0) as usize; |
| 285 | while calls.len() <= idx { |
| 286 | calls.push(ToolCall { |
| 287 | id: String::new(), |
| 288 | name: String::new(), |
| 289 | arguments: String::new(), |
| 290 | }); |
| 291 | } |
| 292 | let slot = &mut calls[idx]; |
| 293 | if let Some(id) = tc["id"].as_str() { |
| 294 | slot.id.push_str(id); |
| 295 | } |
| 296 | if let Some(n) = tc["function"]["name"].as_str() { |
| 297 | slot.name.push_str(n); |
| 298 | } |
| 299 | if let Some(a) = tc["function"]["arguments"].as_str() { |
| 300 | slot.arguments.push_str(a); |
| 301 | } |
| 302 | } |
| 303 | } |
| 304 | } |
| 305 | } |
| 306 | } |
| 307 | let _ = done; |
| 308 | calls.retain(|c| !c.name.is_empty()); |
| 309 | let content = if content.is_empty() { None } else { Some(content) }; |
| 310 | yield ToolStreamItem::Turn(AssistantTurn { content, tool_calls: calls }); |
| 311 | }; |
| 312 | Ok(stream) |
| 313 | } |
| 314 | |
| 315 | /// 流式对话:产出增量文本片段。 |
| 316 | pub async fn chat_stream( |
| 317 | &self, |
| 318 | messages: &[ChatMessage], |
| 319 | ) -> anyhow::Result<impl Stream<Item = anyhow::Result<String>> + Send + use<>> { |
| 320 | let messages = messages |
| 321 | .iter() |
| 322 | .map(|m| serde_json::to_value(m).unwrap_or_default()) |
| 323 | .collect::<Vec<_>>(); |
| 324 | self.chat_stream_raw(&messages).await |
| 325 | } |
| 326 | |
| 327 | /// 流式对话(原始 JSON 消息,可携带工具回合上下文)。 |
| 328 | pub async fn chat_stream_raw( |
| 329 | &self, |
| 330 | messages: &[serde_json::Value], |
| 331 | ) -> anyhow::Result<impl Stream<Item = anyhow::Result<String>> + Send + use<>> { |
| 332 | let resp = self |
| 333 | .request("/chat/completions") |
| 334 | .json(&json!({ "model": self.model, "messages": messages, "stream": true })) |
| 335 | .send() |
| 336 | .await |
| 337 | .map_err(Unreachable)?; |
| 338 | if !resp.status().is_success() { |
| 339 | let status = resp.status(); |
| 340 | let body: serde_json::Value = resp.json().await.unwrap_or_default(); |
| 341 | anyhow::bail!("LLM request failed ({status}): {}", err_detail(&body)); |
| 342 | } |
| 343 | |
| 344 | let mut bytes = resp.bytes_stream(); |
| 345 | let stream = async_stream::try_stream! { |
| 346 | let mut buf = String::new(); |
| 347 | while let Some(part) = bytes.next().await { |
| 348 | let part = part?; |
| 349 | buf.push_str(&String::from_utf8_lossy(&part)); |
| 350 | // SSE 帧以空行分隔;逐帧取出已完整到达的部分 |
| 351 | while let Some(pos) = buf.find("\n\n") { |
| 352 | let frame = buf[..pos].to_string(); |
| 353 | buf.drain(..pos + 2); |
| 354 | for line in frame.lines() { |
| 355 | let Some(data) = line.strip_prefix("data:").map(str::trim) else { |
| 356 | continue; |
| 357 | }; |
| 358 | if data == "[DONE]" { |
| 359 | return; |
| 360 | } |
| 361 | if let Ok(v) = serde_json::from_str::<serde_json::Value>(data) { |
| 362 | if let Some(delta) = v["choices"][0]["delta"]["content"].as_str() { |
| 363 | if !delta.is_empty() { |
| 364 | yield delta.to_string(); |
| 365 | } |
| 366 | } |
| 367 | } |
| 368 | } |
| 369 | } |
| 370 | } |
| 371 | }; |
| 372 | Ok(stream) |
| 373 | } |
| 374 | |
| 375 | /// 批量 embedding。 |
| 376 | pub async fn embed(&self, texts: &[String]) -> anyhow::Result<Vec<Vec<f32>>> { |
| 377 | let resp = self |
| 378 | .request("/embeddings") |
| 379 | .json(&json!({ "model": self.model, "input": texts })) |
| 380 | .send() |
| 381 | .await |
| 382 | .map_err(Unreachable)?; |
| 383 | let status = resp.status(); |
| 384 | let body: serde_json::Value = resp.json().await.map_err(Unreachable)?; |
| 385 | if !status.is_success() { |
| 386 | anyhow::bail!("Embedding request failed ({status}): {}", err_detail(&body)); |
| 387 | } |
| 388 | let data = body["data"] |
| 389 | .as_array() |
| 390 | .ok_or_else(|| anyhow::anyhow!("Unexpected embedding response shape"))?; |
| 391 | let mut out = Vec::with_capacity(data.len()); |
| 392 | for item in data { |
| 393 | let v = item["embedding"] |
| 394 | .as_array() |
| 395 | .ok_or_else(|| anyhow::anyhow!("Embedding 响应缺少向量"))? |
| 396 | .iter() |
| 397 | .filter_map(|x| x.as_f64().map(|f| f as f32)) |
| 398 | .collect(); |
| 399 | out.push(v); |
| 400 | } |
| 401 | Ok(out) |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | /// 记一次调用的 token 开销。**缓存命中数是这里最重要的一列**:抽取靠 |
| 406 | /// "system 消息在一篇文档内逐块完全相同" 吃供应商的前缀缓存, |
| 407 | /// 往 system 里塞逐块变化的内容会让它悄悄归零——只有这个数看得见。 |
| 408 | /// |
| 409 | /// 字段名各家不一:OpenAI 用 prompt_tokens_details.cached_tokens, |
| 410 | /// DeepSeek 用 prompt_cache_hit_tokens。两个都读,谁在读谁。 |
| 411 | fn log_usage(model: &str, body: &serde_json::Value) { |
| 412 | let u = &body["usage"]; |
| 413 | if u.is_null() { |
| 414 | return; |
| 415 | } |
| 416 | let n = |k: &str| u[k].as_u64(); |
| 417 | let cached = u["prompt_tokens_details"]["cached_tokens"] |
| 418 | .as_u64() |
| 419 | .or_else(|| n("prompt_cache_hit_tokens")); |
| 420 | tracing::info!( |
| 421 | model, |
| 422 | prompt = n("prompt_tokens"), |
| 423 | completion = n("completion_tokens"), |
| 424 | cached, |
| 425 | "llm usage" |
| 426 | ); |
| 427 | } |
| 428 | |
| 429 | fn err_detail(body: &serde_json::Value) -> String { |
| 430 | body["error"]["message"] |
| 431 | .as_str() |
| 432 | .or_else(|| body["message"].as_str()) |
| 433 | .unwrap_or("unknown error") |
| 434 | .to_string() |
| 435 | } |
| 436 | |
| 437 | #[cfg(test)] |
| 438 | mod tests { |
| 439 | use super::*; |
| 440 | |
| 441 | /// 真发一次注定失败的请求,拿一个货真价实的 `reqwest::Error`。 |
| 442 | /// 端口 1 上不会有东西监听,而 127.0.0.1 不走代理。 |
| 443 | async fn a_real_transport_error() -> reqwest::Error { |
| 444 | reqwest::Client::builder() |
| 445 | .no_proxy() |
| 446 | .build() |
| 447 | .unwrap() |
| 448 | .get("http://127.0.0.1:1/") |
| 449 | .send() |
| 450 | .await |
| 451 | .expect_err("端口 1 不该连得上") |
| 452 | } |
| 453 | |
| 454 | /// **接了连接却一个字节都不回**的服务端。 |
| 455 | /// |
| 456 | /// 这是生产上真正发生的形态,也是最难发现的一种:TCP 连得上、TLS 握得成、 |
| 457 | /// 请求发得出去,然后没了。连接错误会立刻报,这种不会——没有超时的话 |
| 458 | /// `send().await` 就永远停在那里,而调用它的 worker 槽再也不释放。 |
| 459 | async fn a_server_that_never_answers() -> std::net::SocketAddr { |
| 460 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); |
| 461 | let addr = listener.local_addr().unwrap(); |
| 462 | tokio::spawn(async move { |
| 463 | // 收下连接就攥着不放。**必须持有 socket**:一 drop 就是 FIN, |
| 464 | // 那样测的又变成了连接被关闭,不是沉默 |
| 465 | let mut held = Vec::new(); |
| 466 | while let Ok((sock, _)) = listener.accept().await { |
| 467 | held.push(sock); |
| 468 | } |
| 469 | }); |
| 470 | addr |
| 471 | } |
| 472 | |
| 473 | /// 请求挂住时必须**报错返回**,而不是永远等下去。 |
| 474 | /// |
| 475 | /// 没有这条守着,回归的样子是:一次灌入死在第 55 块,32 个 worker 槽被 |
| 476 | /// 永久占满,jobs 表里全是 running,而日志和界面上一个字都没有。 |
| 477 | #[tokio::test] |
| 478 | async fn a_silent_server_ends_in_an_error_not_a_hang() { |
| 479 | let addr = a_server_that_never_answers().await; |
| 480 | let client = LlmClient::with_timeouts( |
| 481 | &format!("http://{addr}"), |
| 482 | None, |
| 483 | "m", |
| 484 | Duration::from_secs(5), |
| 485 | Duration::from_millis(300), |
| 486 | ); |
| 487 | let started = tokio::time::Instant::now(); |
| 488 | let out = tokio::time::timeout( |
| 489 | std::time::Duration::from_secs(10), |
| 490 | client.chat(&[ChatMessage { |
| 491 | role: "user".into(), |
| 492 | content: "hi".into(), |
| 493 | }]), |
| 494 | ) |
| 495 | .await; |
| 496 | |
| 497 | // 外层 timeout 触发 = 客户端自己没有把它掐掉,正是要修的那个 bug |
| 498 | let inner = out.expect("客户端没有超时,请求一直挂着"); |
| 499 | assert!(inner.is_err(), "沉默的服务端不该被当成成功"); |
| 500 | assert!( |
| 501 | started.elapsed() < std::time::Duration::from_secs(5), |
| 502 | "read_timeout 没生效:等了 {:?}", |
| 503 | started.elapsed() |
| 504 | ); |
| 505 | } |
| 506 | |
| 507 | /// **判定必须穿透 context 层。** |
| 508 | /// |
| 509 | /// 这是整条链上最容易悄悄坏掉的一环:调用方每加一句 `.context("抽取失败")` |
| 510 | /// 就换掉一次错误文本,靠文本匹配的判定当天就废——而症状是告警再也不出现, |
| 511 | /// 没有任何测试会红,用户也不会来报"我没收到告警"。 |
| 512 | #[tokio::test] |
| 513 | async fn unreachable_survives_context_layers() { |
| 514 | let raw = a_real_transport_error().await; |
| 515 | let err = anyhow::Error::new(Unreachable(raw)) |
| 516 | .context("embedding 失败") |
| 517 | .context("process_document 失败"); |
| 518 | assert!(is_unreachable(&err)); |
| 519 | // 顺带钉住"文本会变"这件事本身:最外层已经不含端点的任何字样 |
| 520 | assert!(!err.to_string().contains("endpoint")); |
| 521 | } |
| 522 | |
| 523 | /// 反面:普通错误不该被认成端点问题,否则告警会对任何失败都亮。 |
| 524 | #[tokio::test] |
| 525 | async fn an_ordinary_failure_is_not_the_endpoint() { |
| 526 | let e = anyhow::anyhow!("Embedding 响应缺少向量").context("抽取失败"); |
| 527 | assert!(!is_unreachable(&e)); |
| 528 | } |
| 529 | |
| 530 | /// 端点干干净净地回了 4xx 不算——那说明它就是模型 API, |
| 531 | /// 只是密钥或模型名不对,该找的人和该做的事都不一样。 |
| 532 | #[tokio::test] |
| 533 | async fn a_clean_api_error_is_a_different_problem() { |
| 534 | let e = anyhow::anyhow!("LLM request failed (401 Unauthorized): bad key"); |
| 535 | assert!(!is_unreachable(&e)); |
| 536 | } |
| 537 | } |