AnyBot/src/testkit.rs

273 lines
14 KiB
Rust
Raw Normal View History

//! 測試工具: 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<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,
}
/// 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(),
(_, 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");
}
}
feat: 每一次模型呼叫都記用量;/usage 看最近一天和一週 工程基礎計畫 E8,參考 grok-build 的 `grok usage`。 - providers.rs:StepOutput 多一個 usage(輸入、輸出、快取讀、快取寫、花費)。OpenAI 系的串流最後一段的 usage(OpenAI、xAI、OpenRouter 的請求加 stream_options.include_usage;其他有給也讀);Anthropic 從 message_start 和 message_delta 讀。OpenAI 的 prompt_tokens 包含快取讀的,拆開,兩家的「輸入」同一個意思。OpenRouter 回的 cost 記成百萬分之一美元。拿掉沒人讀的 CACHE_STATS。 - usage.rs:run_step_as_written(每一次模型呼叫都經過)之後寫一行到資料夾的 usage/YYYY-MM.jsonl:時間、供應商、模型、session(看得出哪個 Bot、做什麼:回合、發布前檢查、目標檢查、支線)、token、花費。沒回報用量的呼叫不寫。 - 「/usage」(電腦、螢幕、手機):最近 24 小時和 7 天的呼叫次數、輸入、輸出、快取讀了幾成、花費(有回報才寫),依 Bot、依模型各列前 8 名。不猜價錢。 - / 清單、手機的指令清單多一個 usage;功能地圖 chat.md、FEATURES.md。 已驗證:cargo test 全過、cargo clippy -D warnings 過。新測試:兩種串流的用量讀得對(OpenAI 的快取拆出來、OpenRouter 的花費、Anthropic 的四種),只對認得的服務送 stream_options;session 看得出是誰的;一天和一週的加總、依 Bot 和依模型、七天前的不算;寫一行再讀回來,沒用量的不寫。 未驗證:真的 OpenAI/xAI/OpenRouter 回的 usage(照它們的文件寫,假模型測過格式)。 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:27:34 +00:00
/// 用量: 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());
}
}