aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / crates / allen-courier / src / bin / allen-scene.rs
| 1 | //! allen-scene: asks the model server for scenes, the way Allen's canvas will |
| 2 | //! (native/kernel/svc/allen_scene.h, docs/ALLEN_CANVAS.md), and keeps every raw |
| 3 | //! reply for the host test (scripts/ck_allen_canvas_test.sh --live). |
| 4 | //! |
| 5 | //! For each question (one per line of --questions; blank lines and lines |
| 6 | //! starting with '#' are skipped) it sends the system prompt |
| 7 | //! (crates/allen-courier/scene_prompt.txt, the same file the relay can |
| 8 | //! include) and the question to `POST /v1/chat/completions`, and writes |
| 9 | //! `NN-slug.txt` (the reply exactly as the model wrote it), `ask-NN-slug.txt` |
| 10 | //! (the question) and one line of `log.tsv` (status, time, tokens, finish). |
| 11 | //! |
| 12 | //! The server makes one answer at a time and says 503 while it is busy with |
| 13 | //! someone else's: this waits exactly as its Retry-After asks (1 to 15 s; 2 s |
| 14 | //! without one) for at most --wait-max seconds per question, and never sends |
| 15 | //! two requests at once. A reply already kept is not asked again, so a |
| 16 | //! round that was cut off resumes where it stopped. A server that is not |
| 17 | //! listening (restarting) is waited for the same way. |
| 18 | //! Standard library only: hand-built HTTP and JSON, as in the relay. |
| 19 | use std::io::{Read, Write}; |
| 20 | use std::net::TcpStream; |
| 21 | use std::path::PathBuf; |
| 22 | use std::time::{Duration, Instant}; |
| 23 | |
| 24 | /// The system prompt, built in so the relay and this tool can never disagree. |
| 25 | pub const SCENE_PROMPT: &str = include_str!("../../scene_prompt.txt"); |
| 26 | |
| 27 | struct Args { |
| 28 | model: String, |
| 29 | questions: PathBuf, |
| 30 | out: PathBuf, |
| 31 | prompt: Option<PathBuf>, |
| 32 | max_tokens: u32, |
| 33 | wait_max: u64, |
| 34 | temperature: String, |
| 35 | } |
| 36 | |
| 37 | fn usage() -> ! { |
| 38 | eprintln!( |
| 39 | "usage: allen-scene --questions FILE --out DIR [--model HOST:PORT] [--prompt FILE] [--max-tokens N] \ |
| 40 | [--wait-max SECS] [--temperature T]" |
| 41 | ); |
| 42 | std::process::exit(2) |
| 43 | } |
| 44 | |
| 45 | fn parse_args() -> Args { |
| 46 | let mut a = Args { |
| 47 | model: "127.0.0.1:18091".into(), |
| 48 | questions: PathBuf::new(), |
| 49 | out: PathBuf::new(), |
| 50 | prompt: None, |
| 51 | max_tokens: 400, |
| 52 | wait_max: 1800, |
| 53 | temperature: "0.3".into(), |
| 54 | }; |
| 55 | let mut it = std::env::args().skip(1); |
| 56 | while let Some(k) = it.next() { |
| 57 | let v = it.next().unwrap_or_else(|| usage()); |
| 58 | match k.as_str() { |
| 59 | "--model" => a.model = v, |
| 60 | "--questions" => a.questions = PathBuf::from(v), |
| 61 | "--out" => a.out = PathBuf::from(v), |
| 62 | "--prompt" => a.prompt = Some(PathBuf::from(v)), |
| 63 | "--max-tokens" => a.max_tokens = v.parse().unwrap_or_else(|_| usage()), |
| 64 | "--wait-max" => a.wait_max = v.parse().unwrap_or_else(|_| usage()), |
| 65 | "--temperature" => a.temperature = v, |
| 66 | _ => usage(), |
| 67 | } |
| 68 | } |
| 69 | if a.questions.as_os_str().is_empty() || a.out.as_os_str().is_empty() { |
| 70 | usage() |
| 71 | } |
| 72 | a |
| 73 | } |
| 74 | |
| 75 | fn json_str(s: &str) -> String { |
| 76 | let mut o = String::with_capacity(s.len() + 2); |
| 77 | o.push('"'); |
| 78 | for c in s.chars() { |
| 79 | match c { |
| 80 | '"' => o.push_str("\\\""), |
| 81 | '\\' => o.push_str("\\\\"), |
| 82 | '\n' => o.push_str("\\n"), |
| 83 | '\r' => o.push_str("\\r"), |
| 84 | '\t' => o.push_str("\\t"), |
| 85 | c if (c as u32) < 0x20 => o.push_str(&format!("\\u{:04x}", c as u32)), |
| 86 | c => o.push(c), |
| 87 | } |
| 88 | } |
| 89 | o.push('"'); |
| 90 | o |
| 91 | } |
| 92 | |
| 93 | fn json_read_str(s: &[u8], mut i: usize) -> Option<(String, usize)> { |
| 94 | if s.get(i) != Some(&b'"') { |
| 95 | return None; |
| 96 | } |
| 97 | i += 1; |
| 98 | let mut out: Vec<u8> = Vec::new(); |
| 99 | while i < s.len() { |
| 100 | match s[i] { |
| 101 | b'"' => return String::from_utf8(out).ok().map(|t| (t, i + 1)), |
| 102 | b'\\' => { |
| 103 | let e = *s.get(i + 1)?; |
| 104 | i += 2; |
| 105 | match e { |
| 106 | b'n' => out.push(b'\n'), |
| 107 | b't' => out.push(b'\t'), |
| 108 | b'r' => out.push(b'\r'), |
| 109 | b'b' | b'f' => out.push(b' '), |
| 110 | b'u' => { |
| 111 | let hex = std::str::from_utf8(s.get(i..i + 4)?).ok()?; |
| 112 | let mut cp = u32::from_str_radix(hex, 16).ok()?; |
| 113 | i += 4; |
| 114 | if (0xd800..0xdc00).contains(&cp) && s.get(i..i + 2) == Some(b"\\u") { |
| 115 | let lo = u32::from_str_radix( |
| 116 | std::str::from_utf8(s.get(i + 2..i + 6)?).ok()?, |
| 117 | 16, |
| 118 | ) |
| 119 | .ok()?; |
| 120 | if (0xdc00..0xe000).contains(&lo) { |
| 121 | cp = 0x10000 + ((cp - 0xd800) << 10) + (lo - 0xdc00); |
| 122 | i += 6; |
| 123 | } |
| 124 | } |
| 125 | let c = char::from_u32(cp).unwrap_or('?'); |
| 126 | let mut b = [0u8; 4]; |
| 127 | out.extend_from_slice(c.encode_utf8(&mut b).as_bytes()); |
| 128 | } |
| 129 | c => out.push(c), |
| 130 | } |
| 131 | } |
| 132 | c => { |
| 133 | out.push(c); |
| 134 | i += 1; |
| 135 | } |
| 136 | } |
| 137 | } |
| 138 | None |
| 139 | } |
| 140 | |
| 141 | fn find(h: &[u8], n: &[u8], from: usize) -> Option<usize> { |
| 142 | if n.is_empty() || h.len() < n.len() || from > h.len() - n.len() { |
| 143 | return None; |
| 144 | } |
| 145 | (from..=h.len() - n.len()).find(|&i| &h[i..i + n.len()] == n) |
| 146 | } |
| 147 | |
| 148 | /// The first JSON string value after `"key"` in body. |
| 149 | fn string_after(body: &[u8], key: &str) -> Option<String> { |
| 150 | let needle = format!("\"{}\"", key); |
| 151 | let mut from = 0; |
| 152 | while let Some(p) = find(body, needle.as_bytes(), from) { |
| 153 | let mut i = p + needle.len(); |
| 154 | while i < body.len() && matches!(body[i], b' ' | b':' | b'\n' | b'\r' | b'\t') { |
| 155 | i += 1; |
| 156 | } |
| 157 | if let Some((s, _)) = json_read_str(body, i) { |
| 158 | return Some(s); |
| 159 | } |
| 160 | from = p + 1; |
| 161 | } |
| 162 | None |
| 163 | } |
| 164 | |
| 165 | /// The first number after `"key"` in body. |
| 166 | fn number_after(body: &[u8], key: &str) -> Option<u64> { |
| 167 | let needle = format!("\"{}\"", key); |
| 168 | let p = find(body, needle.as_bytes(), 0)? + needle.len(); |
| 169 | let digits: String = body[p..] |
| 170 | .iter() |
| 171 | .skip_while(|c| matches!(c, b' ' | b':')) |
| 172 | .take_while(|c| c.is_ascii_digit()) |
| 173 | .map(|&c| c as char) |
| 174 | .collect(); |
| 175 | digits.parse().ok() |
| 176 | } |
| 177 | |
| 178 | fn dechunk(b: &[u8]) -> Vec<u8> { |
| 179 | let mut out = Vec::new(); |
| 180 | let mut i = 0; |
| 181 | while let Some(e) = find(b, b"\r\n", i) { |
| 182 | let n = usize::from_str_radix(String::from_utf8_lossy(&b[i..e]).trim(), 16).unwrap_or(0); |
| 183 | if n == 0 { |
| 184 | break; |
| 185 | } |
| 186 | let s = e + 2; |
| 187 | if s + n > b.len() { |
| 188 | break; |
| 189 | } |
| 190 | out.extend_from_slice(&b[s..s + n]); |
| 191 | i = s + n + 2; |
| 192 | } |
| 193 | out |
| 194 | } |
| 195 | |
| 196 | /// One HTTP exchange: (status, head, body). |
| 197 | fn http( |
| 198 | host: &str, |
| 199 | method: &str, |
| 200 | path: &str, |
| 201 | body: &str, |
| 202 | ) -> std::io::Result<(u16, String, Vec<u8>)> { |
| 203 | let mut s = TcpStream::connect(host)?; |
| 204 | s.set_read_timeout(Some(Duration::from_secs(300)))?; |
| 205 | write!( |
| 206 | s, |
| 207 | "{} {} HTTP/1.1\r\nHost: {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n\ |
| 208 | Connection: close\r\n\r\n{}", |
| 209 | method, |
| 210 | path, |
| 211 | host, |
| 212 | body.len(), |
| 213 | body |
| 214 | )?; |
| 215 | let mut raw = Vec::new(); |
| 216 | s.read_to_end(&mut raw)?; |
| 217 | let end = find(&raw, b"\r\n\r\n", 0).ok_or_else(|| std::io::Error::other("no http head"))?; |
| 218 | let head = String::from_utf8_lossy(&raw[..end]).to_string(); |
| 219 | let status = head |
| 220 | .split_whitespace() |
| 221 | .nth(1) |
| 222 | .and_then(|s| s.parse().ok()) |
| 223 | .unwrap_or(0); |
| 224 | let mut b = raw[end + 4..].to_vec(); |
| 225 | if head |
| 226 | .to_ascii_lowercase() |
| 227 | .contains("transfer-encoding: chunked") |
| 228 | { |
| 229 | b = dechunk(&b); |
| 230 | } |
| 231 | Ok((status, head, b)) |
| 232 | } |
| 233 | |
| 234 | fn retry_after(head: &str) -> Option<u64> { |
| 235 | head.lines() |
| 236 | .find_map(|l| { |
| 237 | l.to_ascii_lowercase() |
| 238 | .strip_prefix("retry-after:") |
| 239 | .map(|v| v.trim().to_string()) |
| 240 | }) |
| 241 | .and_then(|v| v.parse().ok()) |
| 242 | } |
| 243 | |
| 244 | /// "what's 17% of 240" -> "whats-17-of-240" (at most five words). |
| 245 | fn slug(q: &str) -> String { |
| 246 | let words: Vec<String> = q |
| 247 | .split_whitespace() |
| 248 | .map(|w| { |
| 249 | w.chars() |
| 250 | .filter(|c| c.is_ascii_alphanumeric()) |
| 251 | .collect::<String>() |
| 252 | .to_ascii_lowercase() |
| 253 | }) |
| 254 | .filter(|w| !w.is_empty()) |
| 255 | .take(5) |
| 256 | .collect(); |
| 257 | words.join("-") |
| 258 | } |
| 259 | |
| 260 | fn main() { |
| 261 | let a = parse_args(); |
| 262 | let prompt = match &a.prompt { |
| 263 | Some(p) => std::fs::read_to_string(p).unwrap_or_else(|e| { |
| 264 | eprintln!("allen-scene: prompt {}: {}", p.display(), e); |
| 265 | std::process::exit(1) |
| 266 | }), |
| 267 | None => SCENE_PROMPT.to_string(), |
| 268 | }; |
| 269 | let questions = std::fs::read_to_string(&a.questions).unwrap_or_else(|e| { |
| 270 | eprintln!("allen-scene: questions {}: {}", a.questions.display(), e); |
| 271 | std::process::exit(1) |
| 272 | }); |
| 273 | std::fs::create_dir_all(&a.out).ok(); |
| 274 | // the served model's id, sent back exactly (the server refuses any other) |
| 275 | let model_id = http(&a.model, "GET", "/v1/models", "") |
| 276 | .ok() |
| 277 | .filter(|(s, _, _)| *s == 200) |
| 278 | .and_then(|(_, _, b)| string_after(&b, "id")); |
| 279 | println!( |
| 280 | "allen-scene: model {} at {}", |
| 281 | model_id.as_deref().unwrap_or("(unnamed)"), |
| 282 | a.model |
| 283 | ); |
| 284 | let mut log = std::fs::OpenOptions::new() |
| 285 | .create(true) |
| 286 | .append(true) |
| 287 | .open(a.out.join("log.tsv")) |
| 288 | .expect("log.tsv"); |
| 289 | let mut n = 0; |
| 290 | let mut answered = 0; |
| 291 | for q in questions |
| 292 | .lines() |
| 293 | .map(str::trim) |
| 294 | .filter(|l| !l.is_empty() && !l.starts_with('#')) |
| 295 | { |
| 296 | n += 1; |
| 297 | let name = format!("{:02}-{}", n, slug(q)); |
| 298 | let model_field = model_id |
| 299 | .as_ref() |
| 300 | .map(|m| format!("\"model\":{},", json_str(m))) |
| 301 | .unwrap_or_default(); |
| 302 | let body = format!( |
| 303 | "{{{}\"messages\":[{{\"role\":\"system\",\"content\":{}}},{{\"role\":\"user\",\"content\":{}}}],\ |
| 304 | \"max_tokens\":{},\"temperature\":{},\"stream\":false}}", |
| 305 | model_field, |
| 306 | json_str(&prompt), |
| 307 | json_str(q), |
| 308 | a.max_tokens, |
| 309 | a.temperature |
| 310 | ); |
| 311 | if a.out.join(format!("{}.txt", name)).exists() { |
| 312 | println!("allen-scene: {} already answered, kept", name); |
| 313 | answered += 1; |
| 314 | continue; // a round cut off part way resumes where it stopped |
| 315 | } |
| 316 | let t0 = Instant::now(); |
| 317 | let mut wait = 5u64; |
| 318 | let mut waited = 0u64; |
| 319 | let mut busy = 0u32; |
| 320 | let result = loop { |
| 321 | match http(&a.model, "POST", "/v1/chat/completions", &body) { |
| 322 | Ok((503, head, _)) if waited < a.wait_max => { |
| 323 | busy += 1; |
| 324 | // exactly as the server asks (its Retry-After, 1 s today; 2 s without one; at most 15 s): a busy |
| 325 | // answer costs it nothing, and a slower poll loses every free moment to faster callers |
| 326 | let w = retry_after(&head).unwrap_or(2).clamp(1, 15); |
| 327 | std::thread::sleep(Duration::from_secs(w)); |
| 328 | waited += w; |
| 329 | } |
| 330 | Err(_) if waited < a.wait_max => { |
| 331 | // the server is not there (restarting): wait for it, 5 s doubling to 60 s |
| 332 | busy += 1; |
| 333 | std::thread::sleep(Duration::from_secs(wait)); |
| 334 | waited += wait; |
| 335 | wait = (wait * 2).min(60); |
| 336 | } |
| 337 | other => break other, |
| 338 | } |
| 339 | }; |
| 340 | let ms = t0.elapsed().as_millis(); |
| 341 | match result { |
| 342 | Ok((200, _, b)) => { |
| 343 | let reply = string_after(&b, "content").unwrap_or_default(); |
| 344 | let finish = string_after(&b, "finish_reason").unwrap_or_default(); |
| 345 | let toks = number_after(&b, "completion_tokens").unwrap_or(0); |
| 346 | std::fs::write(a.out.join(format!("{}.txt", name)), &reply).expect("write reply"); |
| 347 | std::fs::write(a.out.join(format!("ask-{}.txt", name)), format!("{}\n", q)) |
| 348 | .expect("write question"); |
| 349 | let _ = writeln!( |
| 350 | log, |
| 351 | "{}\t200\t{} ms\t{} tokens\tfinish {}\t{} busy answers waited out\t{}", |
| 352 | name, ms, toks, finish, busy, q |
| 353 | ); |
| 354 | println!( |
| 355 | "allen-scene: {} -> {} chars, {} tokens, {} ms ({} busy)", |
| 356 | name, |
| 357 | reply.len(), |
| 358 | toks, |
| 359 | ms, |
| 360 | busy |
| 361 | ); |
| 362 | answered += 1; |
| 363 | } |
| 364 | Ok((code, _, b)) => { |
| 365 | let _ = writeln!( |
| 366 | log, |
| 367 | "{}\t{}\t{} ms\t\t\t{} busy answers waited out\t{}", |
| 368 | name, code, ms, busy, q |
| 369 | ); |
| 370 | println!( |
| 371 | "allen-scene: {} -> status {} ({})", |
| 372 | name, |
| 373 | code, |
| 374 | String::from_utf8_lossy(&b) |
| 375 | .chars() |
| 376 | .take(160) |
| 377 | .collect::<String>() |
| 378 | ); |
| 379 | } |
| 380 | Err(e) => { |
| 381 | let _ = writeln!(log, "{}\terror\t{} ms\t\t\t{}\t{}", name, ms, e, q); |
| 382 | println!("allen-scene: {} -> {}", name, e); |
| 383 | } |
| 384 | } |
| 385 | std::thread::sleep(Duration::from_secs(1)); // gentle: never back to back |
| 386 | } |
| 387 | println!("allen-scene: {} of {} questions answered", answered, n); |
| 388 | if answered == 0 { |
| 389 | std::process::exit(1) |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | #[cfg(test)] |
| 394 | mod tests { |
| 395 | use super::*; |
| 396 | |
| 397 | #[test] |
| 398 | fn the_prompt_is_plain_and_names_every_kind() { |
| 399 | assert!(SCENE_PROMPT.is_ascii()); |
| 400 | for k in [ |
| 401 | "say", |
| 402 | "mood", |
| 403 | "note:", |
| 404 | "list:", |
| 405 | "number:", |
| 406 | "quote:", |
| 407 | "person to:", |
| 408 | "timer:", |
| 409 | "picture:", |
| 410 | "video:", |
| 411 | ] { |
| 412 | assert!(SCENE_PROMPT.contains(k), "{k}"); |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | #[test] |
| 417 | fn replies_and_numbers_are_read_from_a_completion() { |
| 418 | let b = br#"{"choices":[{"message":{"role":"assistant","content":"say hi\nnumber: 2"},"finish_reason":"stop"}],"usage":{"completion_tokens": 7}}"#; |
| 419 | assert_eq!(string_after(b, "content").unwrap(), "say hi\nnumber: 2"); |
| 420 | assert_eq!(string_after(b, "finish_reason").unwrap(), "stop"); |
| 421 | assert_eq!(number_after(b, "completion_tokens"), Some(7)); |
| 422 | } |
| 423 | |
| 424 | #[test] |
| 425 | fn slugs_and_waits() { |
| 426 | assert_eq!(slug("what's 17% of 240"), "whats-17-of-240"); |
| 427 | assert_eq!(retry_after("HTTP/1.1 503 Busy\r\nRetry-After: 4"), Some(4)); |
| 428 | assert_eq!(retry_after("HTTP/1.1 503 Busy"), None); |
| 429 | } |
| 430 | } |