//! 測試工具: one fake model service for every test that needs a model (agent.rs, app.rs and here), //! instead of three servers each written in its own test module. It speaks OpenAI's chat //! completions stream and Anthropic's messages stream, answers each request with the next //! reply of a script — words, a tool call, an error status with Retry-After, a dropped //! connection, an empty answer — and keeps every request it got. Like grok-build's //! xai-grok-test-support. //! //! `cfg(test)` only. use serde_json::{json, Value}; use std::io::{Read, Write}; use std::sync::{Arc, Mutex}; /// One answer of the script. #[derive(Clone, Debug)] pub enum Reply { /// Words. Text(String), /// A tool call (`args` is the arguments object). Call { id: String, name: String, args: Value }, /// An HTTP error: the status, a JSON body, and Retry-After (seconds) when given. Fail { status: u16, body: String, retry_after: Option }, /// The connection is closed without an answer. Drop, /// A stream with nothing in it (no words, no call). Empty, /// This status and body as they are (for a test that writes its own stream). Raw(u16, String), } impl Reply { pub fn text(t: &str) -> Reply { Reply::Text(t.into()) } pub fn call(id: &str, name: &str, args: Value) -> Reply { Reply::Call { id: id.into(), name: name.into(), args } } pub fn busy(retry_after: u64) -> Reply { Reply::Fail { status: 503, body: r#"{"error":{"message":"Server busy: queue longer than 10 seconds"}}"#.into(), retry_after: Some(retry_after) } } } /// Which provider's stream. #[derive(Clone, Copy, Debug, PartialEq)] pub enum Format { OpenAi, Anthropic, } /// A running fake model service. pub struct Fake { pub port: u16, /// Every request as it came (headers and body). pub raw: Arc>>, /// Every request's body as JSON (Null when it wasn't). pub bodies: Arc>>, } impl Fake { /// Answers the script in order; after it, `then` for every request (None: it stops listening, /// and the next request finds nobody). pub fn start(format: Format, script: Vec, then: Option) -> Fake { let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let port = l.local_addr().unwrap().port(); let (raw, bodies) = (Arc::new(Mutex::new(vec![])), Arc::new(Mutex::new(vec![]))); let (raw2, bodies2) = (raw.clone(), bodies.clone()); std::thread::spawn(move || { let mut script = script.into_iter(); loop { let Some(reply) = script.next().or_else(|| then.clone()) else { return }; let Ok((mut s, _)) = l.accept() else { return }; let (head, body) = read_request(&mut s); raw2.lock().unwrap().push(format!("{head}\r\n\r\n{body}")); bodies2.lock().unwrap().push(serde_json::from_str(&body).unwrap_or(Value::Null)); answer(&mut s, format, reply); } }); Fake { port, raw, bodies } } /// OpenAI's stream; after the script, 「ok」 for ever. pub fn openai(script: Vec) -> Fake { Fake::start(Format::OpenAi, script, Some(Reply::text("ok"))) } /// Anthropic's stream; after the script, 「ok」 for ever. pub fn anthropic(script: Vec) -> Fake { Fake::start(Format::Anthropic, script, Some(Reply::text("ok"))) } /// The address to give as a provider's base URL. pub fn base(&self) -> String { format!("http://127.0.0.1:{}/v1", self.port) } pub fn requests(&self) -> usize { self.raw.lock().unwrap().len() } } fn read_request(s: &mut std::net::TcpStream) -> (String, String) { let mut req = Vec::new(); let mut buf = [0u8; 65536]; loop { let n = s.read(&mut buf).unwrap_or(0); if n == 0 { break; } req.extend_from_slice(&buf[..n]); let t = String::from_utf8_lossy(&req).to_string(); if let Some(end) = t.find("\r\n\r\n") { let len = t[..end].lines().find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::().unwrap_or(0))).unwrap_or(0); if req.len() >= end + 4 + len { break; } } } let t = String::from_utf8_lossy(&req).to_string(); match t.split_once("\r\n\r\n") { Some((h, b)) => (h.to_string(), b.to_string()), None => (t, String::new()), } } /// The stream for one reply, in the provider's format. pub fn stream(format: Format, reply: &Reply) -> String { let event = |name: &str, v: Value| format!("event: {name}\ndata: {v}\n\n"); match (format, reply) { (Format::OpenAi, Reply::Text(t)) => format!("data: {}\n\ndata: [DONE]\n\n", json!({"choices": [{"delta": {"content": t}}]})), (Format::OpenAi, Reply::Call { id, name, args }) => format!("data: {}\n\ndata: [DONE]\n\n", json!({"choices": [{"delta": {"tool_calls": [{"index": 0, "id": id, "function": {"name": name, "arguments": args.to_string()}}]}}]})), (Format::OpenAi, Reply::Empty) => "data: [DONE]\n\n".into(), (Format::Anthropic, Reply::Text(t)) => [ event("message_start", json!({"type": "message_start"})), event("content_block_start", json!({"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}})), event("content_block_delta", json!({"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": t}})), event("content_block_stop", json!({"type": "content_block_stop", "index": 0})), event("message_delta", json!({"type": "message_delta", "delta": {"stop_reason": "end_turn"}})), event("message_stop", json!({"type": "message_stop"})), ] .concat(), (Format::Anthropic, Reply::Call { id, name, args }) => [ event("message_start", json!({"type": "message_start"})), event("content_block_start", json!({"type": "content_block_start", "index": 0, "content_block": {"type": "tool_use", "id": id, "name": name, "input": {}}})), event("content_block_delta", json!({"type": "content_block_delta", "index": 0, "delta": {"type": "input_json_delta", "partial_json": args.to_string()}})), event("content_block_stop", json!({"type": "content_block_stop", "index": 0})), event("message_delta", json!({"type": "message_delta", "delta": {"stop_reason": "tool_use"}})), event("message_stop", json!({"type": "message_stop"})), ] .concat(), (Format::Anthropic, Reply::Empty) => [event("message_start", json!({"type": "message_start"})), event("message_stop", json!({"type": "message_stop"}))].concat(), (_, Reply::Raw(_, body)) => body.clone(), (_, Reply::Fail { body, .. }) => body.clone(), (_, Reply::Drop) => String::new(), } } fn answer(s: &mut std::net::TcpStream, format: Format, reply: Reply) { let (status, extra) = match &reply { Reply::Drop => return, Reply::Fail { status, retry_after, .. } => (*status, retry_after.map(|r| format!("Retry-After: {r}\r\n")).unwrap_or_default()), Reply::Raw(status, _) => (*status, String::new()), _ => (200, String::new()), }; let body = stream(format, &reply); let head = if status == 200 { "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: close\r\n\r\n".to_string() } else { format!("HTTP/1.1 {status} Error\r\nContent-Type: application/json\r\n{extra}Content-Length: {}\r\nConnection: close\r\n\r\n", body.len()) }; let _ = s.write_all(head.as_bytes()); let _ = s.write_all(body.as_bytes()); } #[cfg(test)] mod tests { use super::*; use crate::providers::{ChatRequest, ProviderKind}; use std::sync::atomic::AtomicBool; fn req(kind: ProviderKind, base: String) -> ChatRequest { ChatRequest { kind, base_url: base, api_key: "k".into(), model: "m".into(), system: String::new(), history: vec![crate::model::Message::user("hi")], tools: vec![], session: String::new(), effort: String::new() } } /// Both formats come out of the providers' own parsers as words and tool calls. #[test] fn both_streams_read_as_words_and_calls() { for (format, kind) in [(Format::OpenAi, ProviderKind::Custom), (Format::Anthropic, ProviderKind::Anthropic)] { let f = Fake::start(format, vec![Reply::text("你好"), Reply::call("c1", "list_dir", json!({"path": "x"}))], None); let cancel = AtomicBool::new(false); let out = crate::providers::run_step(&req(kind, f.base()), &cancel, &|_| {}).unwrap(); assert_eq!(out.text, "你好", "{format:?}"); let out = crate::providers::run_step(&req(kind, f.base()), &cancel, &|_| {}).unwrap(); assert_eq!((out.tool_calls[0].name.as_str(), out.tool_calls[0].args.as_str()), ("list_dir", r#"{"path":"x"}"#), "{format:?}"); assert_eq!(f.requests(), 2); assert_eq!(f.bodies.lock().unwrap()[0]["model"], "m"); } } /// An answer with nothing in it (no words, no call) is asked again, in either format. #[test] fn an_empty_answer_is_asked_again() { for (f, kind) in [(Fake::openai(vec![Reply::Empty, Reply::text("有了")]), ProviderKind::Custom), (Fake::anthropic(vec![Reply::Empty, Reply::text("有了")]), ProviderKind::Anthropic)] { let cancel = AtomicBool::new(false); let out = crate::providers::run_step(&req(kind, f.base()), &cancel, &|_| {}).unwrap(); assert_eq!(out.text, "有了", "{kind:?}"); assert_eq!(f.requests(), 2, "{kind:?}"); } } /// A busy answer with Retry-After is waited out and asked again; a dropped connection too. #[test] fn busy_and_dropped_answers_are_tried_again() { let f = Fake::start(Format::OpenAi, vec![Reply::busy(1), Reply::Drop, Reply::text("好了")], None); let cancel = AtomicBool::new(false); let retries = Mutex::new(vec![]); let t0 = std::time::Instant::now(); let out = crate::providers::run_step(&req(ProviderKind::Custom, f.base()), &cancel, &|e| { if let crate::providers::StreamEvent::Retrying(m) = e { retries.lock().unwrap().push(m); } }) .unwrap(); assert_eq!(out.text, "好了"); assert_eq!(f.requests(), 3); assert!(retries.lock().unwrap().len() >= 2, "{:?}", retries.lock().unwrap()); assert!(t0.elapsed() >= std::time::Duration::from_millis(900), "Retry-After: 1 was waited out ({:?})", t0.elapsed()); } }