290 lines
15 KiB
Rust
290 lines
15 KiB
Rust
//! 測試工具: 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, Anthropic's messages stream and OpenAI's Responses stream (ChatGPT 方案),
|
|
//! 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<u64> },
|
|
/// 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,
|
|
/// OpenAI's Responses API (ChatGPT 方案).
|
|
Responses,
|
|
}
|
|
|
|
/// A running fake model service.
|
|
pub struct Fake {
|
|
pub port: u16,
|
|
/// Every request as it came (headers and body).
|
|
pub raw: Arc<Mutex<Vec<String>>>,
|
|
/// Every request's body as JSON (Null when it wasn't).
|
|
pub bodies: Arc<Mutex<Vec<Value>>>,
|
|
}
|
|
|
|
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<Reply>, then: Option<Reply>) -> 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<Reply>) -> Fake {
|
|
Fake::start(Format::OpenAi, script, Some(Reply::text("ok")))
|
|
}
|
|
|
|
/// Anthropic's stream; after the script, 「ok」 for ever.
|
|
pub fn anthropic(script: Vec<Reply>) -> 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::<usize>().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(),
|
|
(Format::Responses, Reply::Text(t)) => [
|
|
event("response.created", json!({"type": "response.created", "response": {"status": "in_progress"}})),
|
|
event("response.output_text.delta", json!({"type": "response.output_text.delta", "delta": t})),
|
|
event("response.completed", json!({"type": "response.completed", "response": {"status": "completed", "usage": {"input_tokens": 120, "input_tokens_details": {"cached_tokens": 20}, "output_tokens": 7}}})),
|
|
]
|
|
.concat(),
|
|
(Format::Responses, Reply::Call { id, name, args }) => [
|
|
event("response.output_item.added", json!({"type": "response.output_item.added", "item": {"type": "function_call", "call_id": id, "name": name, "arguments": ""}})),
|
|
event("response.function_call_arguments.delta", json!({"type": "response.function_call_arguments.delta", "delta": args.to_string()})),
|
|
event("response.output_item.done", json!({"type": "response.output_item.done", "item": {"type": "function_call", "call_id": id, "name": name, "arguments": args.to_string()}})),
|
|
event("response.completed", json!({"type": "response.completed", "response": {"status": "completed"}})),
|
|
]
|
|
.concat(),
|
|
(Format::Responses, Reply::Empty) => event("response.completed", json!({"type": "response.completed", "response": {"status": "completed"}})),
|
|
(_, 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");
|
|
}
|
|
}
|
|
|
|
/// 用量: what a step used comes back from both streams (OpenAI's cached tokens taken out of
|
|
/// its input; a cost when the provider gives one), and only the services known to take it
|
|
/// are asked for it.
|
|
#[test]
|
|
fn usage_comes_back_from_both_streams() {
|
|
use crate::providers::Usage;
|
|
let oa = "data: {\"choices\":[{\"delta\":{\"content\":\"hi\"}}]}\n\ndata: {\"choices\":[],\"usage\":{\"prompt_tokens\":120,\"completion_tokens\":7,\"prompt_tokens_details\":{\"cached_tokens\":100},\"cost\":0.0015}}\n\ndata: [DONE]\n\n";
|
|
let f = Fake::start(Format::OpenAi, vec![Reply::Raw(200, oa.into()), Reply::text("x")], None);
|
|
let cancel = AtomicBool::new(false);
|
|
let out = crate::providers::run_step(&req(ProviderKind::OpenRouter, f.base()), &cancel, &|_| {}).unwrap();
|
|
assert_eq!(out.usage, Usage { input: 20, output: 7, cache_read: 100, cache_write: 0, cost_micros: 1_500 });
|
|
crate::providers::run_step(&req(ProviderKind::Custom, f.base()), &cancel, &|_| {}).unwrap();
|
|
let bodies = f.bodies.lock().unwrap().clone();
|
|
assert_eq!(bodies[0]["stream_options"]["include_usage"], true);
|
|
assert!(bodies[1].get("stream_options").is_none(), "an unknown service isn't sent it");
|
|
let an = [
|
|
"event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":50,\"cache_read_input_tokens\":400,\"cache_creation_input_tokens\":30,\"output_tokens\":1}}}\n\n",
|
|
"event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"hi\"}}\n\n",
|
|
"event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":12}}\n\n",
|
|
"event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n",
|
|
]
|
|
.concat();
|
|
let f = Fake::start(Format::Anthropic, vec![Reply::Raw(200, an)], None);
|
|
let out = crate::providers::run_step(&req(ProviderKind::Anthropic, f.base()), &cancel, &|_| {}).unwrap();
|
|
assert_eq!(out.usage, Usage { input: 50, output: 12, cache_read: 400, cache_write: 30, cost_micros: 0 });
|
|
}
|
|
|
|
/// R1: a turn nobody is watching waits out a busy model longer (more tries); one the person
|
|
/// watches gives up after RETRY_MAX_ATTEMPTS tries.
|
|
#[test]
|
|
fn a_turn_nobody_watches_waits_longer_for_a_busy_model() {
|
|
let busy = || (0..4).map(|_| Reply::busy(0)).chain([Reply::text("終於")]).collect::<Vec<_>>();
|
|
let cancel = AtomicBool::new(false);
|
|
let f = Fake::start(Format::OpenAi, busy(), None);
|
|
assert!(crate::providers::run_step(&req(ProviderKind::Custom, f.base()), &cancel, &|_| {}).is_err(), "watched: 3 tries in all");
|
|
assert_eq!(f.requests(), crate::providers::RETRY_MAX_ATTEMPTS as usize);
|
|
let f = Fake::start(Format::OpenAi, busy(), None);
|
|
crate::providers::set_patient(true);
|
|
let out = crate::providers::run_step(&req(ProviderKind::Custom, f.base()), &cancel, &|_| {});
|
|
crate::providers::set_patient(false);
|
|
assert_eq!(out.unwrap().text, "終於");
|
|
assert_eq!(f.requests(), 5);
|
|
}
|
|
|
|
/// 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());
|
|
}
|
|
}
|