aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-serve-http / src / readers.rs
| 1 | //! Eight readers (sc L371, Drake 2026-10-21: "if it's reading, it spawns eight agents at once and |
| 2 | //! reads eight different chunks at once so it can be summarized, followed up on, and connected"). |
| 3 | //! |
| 4 | //! A request to the readers model id whose long input (the last user message and the tool results |
| 5 | //! after it) passes a threshold is answered in two phases. Map: the input is split into `n` parts |
| 6 | //! on paragraph and line boundaries, equal in tokens with a small overlap, and `n` sub-requests |
| 7 | //! (system prompt + the user's request + part i, thinking off, greedy) each write notes on their |
| 8 | //! part; a batching engine seats them in the same beat ([`crate::engine::Engine::generate_group`]). |
| 9 | //! Connect: the original request, with every long segment replaced by the labelled notes, writes |
| 10 | //! the answer. Each reader sees only its part, so this is a different reading method from the |
| 11 | //! plain id, which stays exact; short inputs take the plain path unchanged. |
| 12 | //! |
| 13 | //! Everything here is pure (JSON in, JSON out, a token counter passed in): the server renders the |
| 14 | //! sub-requests through its usual `prepare`, so tool calling and every request check apply to them. |
| 15 | use serde_json::{json, Value}; |
| 16 | |
| 17 | /// The readers' settings (`AIEN_READERS_*` in `main.rs`). |
| 18 | #[derive(Debug, Clone, PartialEq)] |
| 19 | pub struct ReadersConfig { |
| 20 | /// The second id in `/v1/models`. |
| 21 | pub model_id: String, |
| 22 | /// Parts (and readers) per long input. |
| 23 | pub readers: usize, |
| 24 | /// Long-input tokens from which the readers take over. |
| 25 | pub threshold_tokens: usize, |
| 26 | /// Cap on each reader's notes. |
| 27 | pub note_tokens: usize, |
| 28 | /// Tokens each part repeats from the end of the part before it. |
| 29 | pub overlap_tokens: usize, |
| 30 | } |
| 31 | |
| 32 | impl ReadersConfig { |
| 33 | pub fn new(base_model_id: &str) -> Self { |
| 34 | Self { |
| 35 | model_id: format!("{base_model_id}-readers"), |
| 36 | readers: 8, |
| 37 | threshold_tokens: 3000, |
| 38 | note_tokens: 400, |
| 39 | overlap_tokens: 64, |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | /// The readers from the environment: `AIEN_READERS` (`1` on, `0` off; default `default_on`, |
| 44 | /// which `main` sets for a batching engine), `AIEN_READERS_N` (parts, default 8), |
| 45 | /// `AIEN_READERS_THRESHOLD` (tokens, default 3000), `AIEN_READERS_NOTE_TOKENS` (default 400), |
| 46 | /// `AIEN_READERS_OVERLAP` (tokens, default 64). |
| 47 | pub fn from_env(base_model_id: &str, default_on: bool) -> Result<Option<Self>, String> { |
| 48 | let on = match std::env::var("AIEN_READERS").as_deref() { |
| 49 | Ok("1") => true, |
| 50 | Ok("0") => false, |
| 51 | Ok(v) => return Err(format!("AIEN_READERS={v}: 0 or 1")), |
| 52 | Err(_) => default_on, |
| 53 | }; |
| 54 | if !on { |
| 55 | return Ok(None); |
| 56 | } |
| 57 | let mut c = Self::new(base_model_id); |
| 58 | for (var, field, min) in [ |
| 59 | ("AIEN_READERS_N", &mut c.readers, 1), |
| 60 | ("AIEN_READERS_THRESHOLD", &mut c.threshold_tokens, 1), |
| 61 | ("AIEN_READERS_NOTE_TOKENS", &mut c.note_tokens, 16), |
| 62 | ("AIEN_READERS_OVERLAP", &mut c.overlap_tokens, 0), |
| 63 | ] { |
| 64 | if let Ok(v) = std::env::var(var) { |
| 65 | *field = v |
| 66 | .parse::<usize>() |
| 67 | .ok() |
| 68 | .filter(|&n| n >= min) |
| 69 | .ok_or_else(|| format!("{var}={v}: a whole number >= {min}"))?; |
| 70 | } |
| 71 | } |
| 72 | Ok(Some(c)) |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | /// One part of the long input. |
| 77 | #[derive(Debug, Clone, PartialEq)] |
| 78 | pub struct Part { |
| 79 | /// The text the reader gets (the overlap included). |
| 80 | pub text: String, |
| 81 | /// Tokens of `text`. |
| 82 | pub tokens: usize, |
| 83 | /// Lines of the long input this part covers, 1-based, inclusive, the overlap excluded. |
| 84 | pub first_line: usize, |
| 85 | pub last_line: usize, |
| 86 | } |
| 87 | |
| 88 | /// What the readers do with one request. |
| 89 | #[derive(Debug, Clone, PartialEq)] |
| 90 | pub struct Plan { |
| 91 | /// The user's request as every reader and the connect phase see it. |
| 92 | pub question: String, |
| 93 | /// `question` is the beginning and end of a long user message, not the whole of it. |
| 94 | pub question_is_excerpt: bool, |
| 95 | /// Messages (indices into `messages`) whose text the parts were cut from. |
| 96 | pub long_msgs: Vec<usize>, |
| 97 | pub total_tokens: usize, |
| 98 | pub total_lines: usize, |
| 99 | pub parts: Vec<Part>, |
| 100 | } |
| 101 | |
| 102 | /// The text of a message's `content`: a string, or the text parts of an array. |
| 103 | pub fn content_text(content: &Value) -> Option<String> { |
| 104 | match content { |
| 105 | Value::String(s) => Some(s.clone()), |
| 106 | Value::Array(parts) => { |
| 107 | let mut out = String::new(); |
| 108 | for p in parts { |
| 109 | if p.get("type").and_then(Value::as_str) == Some("text") { |
| 110 | out.push_str(p.get("text").and_then(Value::as_str)?); |
| 111 | } |
| 112 | } |
| 113 | Some(out) |
| 114 | } |
| 115 | _ => None, |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | fn role(m: &Value) -> String { |
| 120 | m.get("role") |
| 121 | .and_then(Value::as_str) |
| 122 | .unwrap_or("") |
| 123 | .trim() |
| 124 | .to_ascii_lowercase() |
| 125 | } |
| 126 | |
| 127 | /// A segment counts as long input from this many tokens (an eighth of the threshold, at least 200): |
| 128 | /// a short question next to a long tool result stays the question. |
| 129 | fn long_segment_tokens(cfg: &ReadersConfig) -> usize { |
| 130 | (cfg.threshold_tokens / 8).max(200) |
| 131 | } |
| 132 | |
| 133 | /// The readers' plan for `messages`, or `None` when the long input is under the threshold (the |
| 134 | /// request takes the plain path). |
| 135 | pub fn plan( |
| 136 | messages: &[Value], |
| 137 | cfg: &ReadersConfig, |
| 138 | count: &dyn Fn(&str) -> usize, |
| 139 | ) -> Option<Plan> { |
| 140 | let n = cfg.readers.max(1); |
| 141 | let u = messages.iter().rposition(|m| role(m) == "user")?; |
| 142 | let mut segs: Vec<(usize, String, usize)> = Vec::new(); |
| 143 | for (i, m) in messages.iter().enumerate().skip(u) { |
| 144 | let r = role(m); |
| 145 | if i == u || r == "tool" || r == "function" { |
| 146 | let text = content_text(m.get("content").unwrap_or(&Value::Null))?; |
| 147 | let t = count(&text); |
| 148 | segs.push((i, text, t)); |
| 149 | } |
| 150 | } |
| 151 | let min_seg = long_segment_tokens(cfg); |
| 152 | let long: Vec<&(usize, String, usize)> = segs.iter().filter(|s| s.2 >= min_seg).collect(); |
| 153 | let total: usize = long.iter().map(|s| s.2).sum(); |
| 154 | if long.is_empty() || total < cfg.threshold_tokens { |
| 155 | return None; |
| 156 | } |
| 157 | let user_text = &segs[0].1; |
| 158 | let user_long = segs[0].2 >= min_seg; |
| 159 | let (question, question_is_excerpt) = if user_long { |
| 160 | (excerpt(user_text, 600), true) |
| 161 | } else { |
| 162 | (user_text.trim().to_string(), false) |
| 163 | }; |
| 164 | // The long input: its segments in order, each tool result under a label when there are several. |
| 165 | let several = long.len() > 1; |
| 166 | let mut doc = String::new(); |
| 167 | let mut tool_no = 0; |
| 168 | for s in &segs { |
| 169 | let is_tool = s.0 != u; |
| 170 | if is_tool { |
| 171 | tool_no += 1; |
| 172 | } |
| 173 | if s.2 < min_seg { |
| 174 | continue; |
| 175 | } |
| 176 | if several { |
| 177 | if !doc.is_empty() && !doc.ends_with('\n') { |
| 178 | doc.push('\n'); |
| 179 | } |
| 180 | if is_tool { |
| 181 | doc.push_str(&format!("[tool result {tool_no}]\n")); |
| 182 | } else { |
| 183 | doc.push_str("[user message]\n"); |
| 184 | } |
| 185 | } |
| 186 | doc.push_str(&s.1); |
| 187 | } |
| 188 | let pieces = pieces(&doc, total.div_ceil(n * 4).max(16), count); |
| 189 | let total_lines = pieces.last().map_or(0, |p| p.line); |
| 190 | let parts = split(&pieces, n, cfg.overlap_tokens); |
| 191 | Some(Plan { |
| 192 | question, |
| 193 | question_is_excerpt, |
| 194 | long_msgs: long.iter().map(|s| s.0).collect(), |
| 195 | total_tokens: pieces.iter().map(|p| p.tokens).sum(), |
| 196 | total_lines, |
| 197 | parts, |
| 198 | }) |
| 199 | } |
| 200 | |
| 201 | /// The first and last `chars` characters of a long text, cut at line ends when one is near. |
| 202 | fn excerpt(text: &str, chars: usize) -> String { |
| 203 | let t = text.trim(); |
| 204 | let len = t.chars().count(); |
| 205 | if len <= chars * 2 + 40 { |
| 206 | return t.to_string(); |
| 207 | } |
| 208 | let head_end = t.char_indices().nth(chars).map_or(t.len(), |(b, _)| b); |
| 209 | let head_end = t[..head_end] |
| 210 | .rfind('\n') |
| 211 | .filter(|&b| b > head_end / 2) |
| 212 | .unwrap_or(head_end); |
| 213 | let tail_start = t.char_indices().nth(len - chars).map_or(0, |(b, _)| b); |
| 214 | let tail_start = t[tail_start..] |
| 215 | .find('\n') |
| 216 | .map(|b| tail_start + b + 1) |
| 217 | .filter(|&b| b < t.len() - (t.len() - tail_start) / 2) |
| 218 | .unwrap_or(tail_start); |
| 219 | format!( |
| 220 | "{}\n[...]\n{}", |
| 221 | t[..head_end].trim_end(), |
| 222 | t[tail_start..].trim_start() |
| 223 | ) |
| 224 | } |
| 225 | |
| 226 | /// A cut-able piece of the long input: a line (with its newline), or part of a very long line. |
| 227 | #[derive(Debug, Clone, PartialEq)] |
| 228 | struct Piece { |
| 229 | text: String, |
| 230 | tokens: usize, |
| 231 | /// 1-based line number. |
| 232 | line: usize, |
| 233 | /// The line is empty (a paragraph boundary follows it). |
| 234 | blank: bool, |
| 235 | } |
| 236 | |
| 237 | /// The input as lines; a line over `max_tokens` is cut at spaces (or anywhere, when it has none) |
| 238 | /// into pieces of about `max_tokens`. |
| 239 | fn pieces(doc: &str, max_tokens: usize, count: &dyn Fn(&str) -> usize) -> Vec<Piece> { |
| 240 | let mut out = Vec::new(); |
| 241 | for (k, line) in doc.split_inclusive('\n').enumerate() { |
| 242 | let tokens = count(line); |
| 243 | let blank = line.trim().is_empty(); |
| 244 | if tokens <= max_tokens { |
| 245 | out.push(Piece { |
| 246 | text: line.to_string(), |
| 247 | tokens, |
| 248 | line: k + 1, |
| 249 | blank, |
| 250 | }); |
| 251 | continue; |
| 252 | } |
| 253 | let cuts = tokens.div_ceil(max_tokens); |
| 254 | let chars: Vec<(usize, char)> = line.char_indices().collect(); |
| 255 | let mut start = 0usize; |
| 256 | for c in 1..=cuts { |
| 257 | let end = if c == cuts { |
| 258 | line.len() |
| 259 | } else { |
| 260 | let goal = chars[(chars.len() * c / cuts).min(chars.len() - 1)].0; |
| 261 | // The nearest space before the goal, within a tenth of a piece. |
| 262 | let floor = goal.saturating_sub(line.len() / cuts / 10).max(start + 1); |
| 263 | line[..goal] |
| 264 | .rfind(char::is_whitespace) |
| 265 | .filter(|&b| b >= floor) |
| 266 | .map(|b| b + 1) |
| 267 | .unwrap_or(goal) |
| 268 | }; |
| 269 | if end <= start { |
| 270 | continue; |
| 271 | } |
| 272 | let text = &line[start..end]; |
| 273 | out.push(Piece { |
| 274 | text: text.to_string(), |
| 275 | tokens: count(text), |
| 276 | line: k + 1, |
| 277 | blank: false, |
| 278 | }); |
| 279 | start = end; |
| 280 | } |
| 281 | } |
| 282 | out |
| 283 | } |
| 284 | |
| 285 | /// Cuts the pieces into `n` parts of about equal tokens, preferring paragraph boundaries within a |
| 286 | /// tenth of a part of each target; each part after the first repeats up to `overlap` tokens of |
| 287 | /// the one before. |
| 288 | fn split(pieces: &[Piece], n: usize, overlap: usize) -> Vec<Part> { |
| 289 | let total: usize = pieces.iter().map(|p| p.tokens).sum(); |
| 290 | let mut cum = Vec::with_capacity(pieces.len()); |
| 291 | let mut s = 0usize; |
| 292 | for p in pieces { |
| 293 | s += p.tokens; |
| 294 | cum.push(s); |
| 295 | } |
| 296 | // cuts[k] = index of the first piece of part k. |
| 297 | let mut cuts = vec![0usize]; |
| 298 | for k in 1..n { |
| 299 | let target = total * k / n; |
| 300 | let slack = (total / n / 10).max(1); |
| 301 | let lo = *cuts.last().expect("starts with 0") + 1; |
| 302 | if lo >= pieces.len() { |
| 303 | break; |
| 304 | } |
| 305 | // Cut before piece j (j in lo..len): tokens before it = cum[j - 1]. |
| 306 | let dist = |j: usize| cum[j - 1].abs_diff(target); |
| 307 | let best_any = (lo..pieces.len()) |
| 308 | .min_by_key(|&j| dist(j)) |
| 309 | .expect("non-empty"); |
| 310 | let best_par = (lo..pieces.len()) |
| 311 | .filter(|&j| pieces[j - 1].blank && dist(j) <= slack) |
| 312 | .min_by_key(|&j| dist(j)); |
| 313 | cuts.push(best_par.unwrap_or(best_any)); |
| 314 | } |
| 315 | cuts.push(pieces.len()); |
| 316 | let mut parts = Vec::with_capacity(n); |
| 317 | for w in cuts.windows(2) { |
| 318 | let (a, b) = (w[0], w[1]); |
| 319 | if a >= b { |
| 320 | continue; |
| 321 | } |
| 322 | let mut from = a; |
| 323 | let mut extra = 0usize; |
| 324 | while from > 0 && extra + pieces[from - 1].tokens <= overlap { |
| 325 | from -= 1; |
| 326 | extra += pieces[from].tokens; |
| 327 | } |
| 328 | let text: String = pieces[from..b].iter().map(|p| p.text.as_str()).collect(); |
| 329 | parts.push(Part { |
| 330 | text, |
| 331 | tokens: pieces[from..b].iter().map(|p| p.tokens).sum(), |
| 332 | first_line: pieces[a].line, |
| 333 | last_line: pieces[b - 1].line, |
| 334 | }); |
| 335 | } |
| 336 | parts |
| 337 | } |
| 338 | |
| 339 | fn lines_label(p: &Part) -> String { |
| 340 | if p.first_line == p.last_line { |
| 341 | format!("line {}", p.first_line) |
| 342 | } else { |
| 343 | format!("lines {}-{}", p.first_line, p.last_line) |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | /// The system prompt of the request (its system and developer messages), if any. |
| 348 | fn system_text(messages: &[Value]) -> Option<String> { |
| 349 | let s: Vec<String> = messages |
| 350 | .iter() |
| 351 | .filter(|m| matches!(role(m).as_str(), "system" | "developer")) |
| 352 | .filter_map(|m| content_text(m.get("content").unwrap_or(&Value::Null))) |
| 353 | .filter(|t| !t.trim().is_empty()) |
| 354 | .collect(); |
| 355 | (!s.is_empty()).then(|| s.join("\n\n")) |
| 356 | } |
| 357 | |
| 358 | /// Reader `i`'s sub-request: the system prompt, the user's request and part `i`; notes only. |
| 359 | pub fn map_body( |
| 360 | messages: &[Value], |
| 361 | plan: &Plan, |
| 362 | i: usize, |
| 363 | base_model_id: &str, |
| 364 | cfg: &ReadersConfig, |
| 365 | ) -> Value { |
| 366 | let n = plan.parts.len(); |
| 367 | let p = &plan.parts[i]; |
| 368 | let ask = if plan.question_is_excerpt { |
| 369 | "The user's message (it holds the input below; its beginning and end are shown)" |
| 370 | } else { |
| 371 | "The user's request" |
| 372 | }; |
| 373 | let user = format!( |
| 374 | "You are reader {k} of {n}. A long input ({total} tokens, {lines} lines) was split into {n} parts; you read part {k} only. The other readers have the other parts, and a final writer will connect every reader's notes to answer the user.\n\n\ |
| 375 | {ask}:\n<<<\n{q}\n>>>\n\n\ |
| 376 | Part {k} of {n} ({range}):\n<<<\n{text}\n>>>\n\n\ |
| 377 | Write notes on this part only, under these headings, in this order (your notes may be cut short, so the request comes first):\n\ |
| 378 | For the request: every fact in this part that answers or bears on the user's request, with exact quotes, numbers, names, ids and times as written (\"nothing\" if none).\n\ |
| 379 | Key facts: other important facts, as bullet points, exact as written.\n\ |
| 380 | Summary: 2 to 4 sentences.\n\ |
| 381 | Open questions: what this part leaves unclear, or points to elsewhere, worth following up.\n\ |
| 382 | Links: names, terms, ids and references that may connect to other parts.\n\ |
| 383 | Be concise. Write nothing that is not in the part.", |
| 384 | k = i + 1, |
| 385 | total = plan.total_tokens, |
| 386 | lines = plan.total_lines, |
| 387 | q = plan.question, |
| 388 | range = lines_label(p), |
| 389 | text = p.text.trim_end(), |
| 390 | ); |
| 391 | let mut msgs = Vec::new(); |
| 392 | if let Some(s) = system_text(messages) { |
| 393 | msgs.push(json!({"role": "system", "content": s})); |
| 394 | } |
| 395 | msgs.push(json!({"role": "user", "content": user})); |
| 396 | json!({ |
| 397 | "model": base_model_id, |
| 398 | "messages": msgs, |
| 399 | "max_tokens": cfg.note_tokens, |
| 400 | "temperature": 0.0, |
| 401 | "chat_template_kwargs": {"enable_thinking": false}, |
| 402 | }) |
| 403 | } |
| 404 | |
| 405 | /// The labelled notes block the connect phase reads. |
| 406 | pub fn notes_block(plan: &Plan, notes: &[String]) -> String { |
| 407 | let n = plan.parts.len(); |
| 408 | let mut s = format!( |
| 409 | "The long input ({} tokens, {} lines) was read in {n} parts by {n} readers. Their notes, in order:\n", |
| 410 | plan.total_tokens, plan.total_lines |
| 411 | ); |
| 412 | for (k, (p, note)) in plan.parts.iter().zip(notes).enumerate() { |
| 413 | s.push_str(&format!( |
| 414 | "\n## Part {} of {n} ({})\n{}\n", |
| 415 | k + 1, |
| 416 | lines_label(p), |
| 417 | note.trim() |
| 418 | )); |
| 419 | } |
| 420 | s.push_str( |
| 421 | "\nAnswer the user's request from these notes. Connect facts across the parts, say which part a fact comes from when it matters, and say so when the notes do not cover something. The parts are different stretches of the input: events or items reported by different parts with different times or ids are different events; count each once.", |
| 422 | ); |
| 423 | s |
| 424 | } |
| 425 | |
| 426 | /// The connect request: the original request with every long segment replaced by a pointer, the |
| 427 | /// last one carrying the notes (and, when it was the user message, the user's request first). |
| 428 | pub fn connect_body(raw: &Value, plan: &Plan, notes: &[String], base_model_id: &str) -> Value { |
| 429 | let mut body = raw.clone(); |
| 430 | body["model"] = Value::String(base_model_id.into()); |
| 431 | if let Some(obj) = body.as_object_mut() { |
| 432 | obj.remove("aien_show_notes"); |
| 433 | } |
| 434 | let last = *plan.long_msgs.last().expect("a plan has long input"); |
| 435 | if let Some(msgs) = body.get_mut("messages").and_then(Value::as_array_mut) { |
| 436 | for &i in &plan.long_msgs { |
| 437 | let is_user = role(&msgs[i]) == "user"; |
| 438 | let mut text = if is_user { |
| 439 | format!("{}\n\n", plan.question) |
| 440 | } else { |
| 441 | String::from("(This tool result was long; it was read in parts with the rest of the long input.)\n\n") |
| 442 | }; |
| 443 | if i == last { |
| 444 | text.push_str(¬es_block(plan, notes)); |
| 445 | } else { |
| 446 | text.truncate(text.trim_end().len()); |
| 447 | } |
| 448 | msgs[i]["content"] = Value::String(text); |
| 449 | } |
| 450 | } |
| 451 | body |
| 452 | } |
| 453 | |
| 454 | /// The collapsed preface `aien_show_notes` puts before the answer. |
| 455 | pub fn notes_preface(plan: &Plan, notes: &[String]) -> String { |
| 456 | let n = plan.parts.len(); |
| 457 | let mut s = format!( |
| 458 | "<details>\n<summary>Notes from {n} readers ({} tokens read in {n} parts)</summary>\n", |
| 459 | plan.total_tokens |
| 460 | ); |
| 461 | for (k, (p, note)) in plan.parts.iter().zip(notes).enumerate() { |
| 462 | s.push_str(&format!( |
| 463 | "\n**Part {} of {n} ({}, {} tokens)**\n\n{}\n", |
| 464 | k + 1, |
| 465 | lines_label(p), |
| 466 | p.tokens, |
| 467 | note.trim() |
| 468 | )); |
| 469 | } |
| 470 | s.push_str("\n</details>\n\n"); |
| 471 | s |
| 472 | } |
| 473 | |
| 474 | /// A reader's notes from its reply text: a stray thinking block dropped, trimmed. |
| 475 | pub fn clean_notes(reply: &str) -> String { |
| 476 | let t = match reply.find("</think>") { |
| 477 | Some(e) => &reply[e + "</think>".len()..], |
| 478 | None => reply, |
| 479 | }; |
| 480 | t.trim().to_string() |
| 481 | } |
| 482 | |
| 483 | #[cfg(test)] |
| 484 | mod tests; |