From 908433967a8069156bff7c5cde2ad6c8cb13fe41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=80=A7=E9=A9=8A?= Date: Thu, 12 Nov 2026 00:02:32 +0800 Subject: [PATCH] =?UTF-8?q?=E9=95=B7=E5=B0=8D=E8=A9=B1:=20old=20step=20res?= =?UTF-8?q?ults=20are=20set=20aside=20first;=20a=20summary=20only=20if=20t?= =?UTF-8?q?hat=20isn't=20enough,=20written=20by=20the=20quick=20model?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - at 70% of the context, results of older steps longer than 600 characters keep their first 200 for the model (the newest 6 messages stay whole): no model call, no wait — 20 file reads went from about 128k to 22k tokens in 10 ms in the test - the chat keeps every result whole for the person; the mark (Message::folded) is kept, so the model reads the same thing each turn - the summary, when still needed, is written by the bot's step model when it has one Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Uirha3QxSfoydRPM9mjj6d --- FEATURES.md | 3 ++ src/agent.rs | 75 ++++++++++++++++++++++++++++++++++++++++++++++-- src/app.rs | 10 +++++++ src/model.rs | 4 +++ src/providers.rs | 3 ++ 5 files changed, 93 insertions(+), 2 deletions(-) diff --git a/FEATURES.md b/FEATURES.md index ced7e94..4978d34 100644 --- a/FEATURES.md +++ b/FEATURES.md @@ -637,6 +637,9 @@ AnyBot 是一個桌面聊天 App,介面和運作方式照 Grok Bot 重做。 ## 14. 長對話整理成摘要 +- **先收起舊的步驟結果,不夠才寫摘要**:對話用到模型容量的 7 成時,先把較早步驟的長結果(網頁全文、指令輸出、讀過的檔案;超過 600 字的)收起來,只留開頭 200 字給模型,最新 6 則訊息的結果不動。這一步不叫模型、不用等(實測 20 個讀檔結果:約 128,000 → 22,000 token,10 毫秒)。聊天裡還是完整的,滑過步驟照樣看得到全部;收起來的結果之後每一輪都一樣,所以模型的快取不受影響。收完還是超過 7 成,才像下面那樣寫摘要。模型自己說對話太長時,兩樣都做。 +- **摘要用快速模型寫**:Bot 有「執行步驟用的模型」時,摘要交給它(整理不是思考,快很多也便宜);沒有就用 Bot 自己的模型。 + - **可讀長度**:每個 Bot 可以設,預設 128,000 tokens(估計值)。 - **怎麼估長度**:英數約 4 個字元算 1 token,中文每個字算 1 token。每則訊息另外加 4,工具參數也算進去。 - **門檻** diff --git a/src/agent.rs b/src/agent.rs index f9fc898..fc6b404 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -700,19 +700,60 @@ fn flatten(h: &[Message]) -> String { .join("\n\n") } -/// Fold older messages into one summary when the chat is over `percent` of the context. -/// Returns how many messages were replaced. +/// A step's result longer than this may be set aside once it is old (estimated). +const FOLD_MIN_CHARS: usize = 600; +/// What stays of a result that was set aside: its first words. +const FOLD_HEAD_CHARS: usize = 200; + +/// What the model reads in place of an old, long result. +pub fn folded_text(text: &str) -> String { + let head: String = text.split_whitespace().collect::>().join(" ").chars().take(FOLD_HEAD_CHARS).collect(); + format!("(這一步較早的結果已收起,只留開頭;需要完整內容就再做一次這一步){head}…") +} + +/// The first, free way to make room: old steps' long results (a page's text, a command's output, +/// a file) are most of a long chat, and the bot has already used them. All but the newest +/// messages' results shrink to their first words — no model call, no waiting. Returns the calls +/// whose results were set aside. +pub fn fold_results(history: &mut [Message]) -> Vec { + let keep_from = history.len().saturating_sub(KEEP_RECENT_MESSAGES); + let mut ids = vec![]; + for m in history[..keep_from].iter_mut().filter(|m| m.role == Role::Tool && !m.folded && !m.summary) { + if m.text.chars().count() > FOLD_MIN_CHARS { + m.text = folded_text(&m.text); + m.images.clear(); + m.folded = true; + ids.push(m.tool_call_id.clone()); + } + } + ids +} + +/// Make room when the chat is over `percent` of the context: first set old results aside +/// (fold_results); only if that isn't enough, fold older messages into one summary, written by +/// the quick model when the bot has one (it is a tidy-up, not thinking). `percent` 0: the model +/// itself said the chat is too long — do both. Returns how many messages the summary replaced. fn maybe_compact(job: &Job, history: &mut Vec, percent: u64, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Option { let used = history_tokens(&job.req.system, history); if used * 100 < job.context_tokens * percent { return None; } + let set_aside = fold_results(history); + if !set_aside.is_empty() { + let now = history_tokens(&job.req.system, history); + eprintln!("AnyBot:對話很長,先收起 {} 個較早的步驟結果(約 {used} → {now} token)", set_aside.len()); + send(StreamEvent::Folded(set_aside)); + if percent > 0 && now * 100 < job.context_tokens * percent { + return None; + } + } let cut = compaction_cut(history)?; send(StreamEvent::Retrying("對話很長了,正在把較早的內容整理成摘要…".into())); let req = ChatRequest { system: "你負責把一段對話整理成摘要,讓之後的對話能接著進行。請用條列寫下:使用者的目標與偏好、已經做出的決定、重要的事實與數字、提到的檔案路徑與指令結果、還沒完成的事。不要加入對話裡沒有的內容。".into(), history: vec![Message::user(&format!("請整理下面這段對話:\n\n{}", flatten(&history[..cut])))], tools: vec![], + model: job.step_model.clone().unwrap_or_else(|| job.req.model.clone()), ..job.req.clone() }; let quiet = |ev: StreamEvent| { @@ -2158,6 +2199,36 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< mod tests { use super::*; + /// A long working chat: old results are most of it, and setting them aside (no model call) + /// makes the room a summary used to be needed for. + #[test] + fn old_results_are_set_aside_before_any_summary() { + let mut h = vec![Message::user("整理這個專案")]; + for i in 0..20 { + let mut a = Message::assistant("", ""); + a.tool_calls = vec![ToolCall { id: format!("c{i}"), name: "read_file".into(), args: format!(r#"{{"path":"src/f{i}.rs"}}"#), status: ToolStatus::Done }]; + h.push(a); + h.push(Message::tool_result(&format!("c{i}"), "read_file", &format!("fn f{i}() {{}}\n{}", "// 很長的檔案內容 ".repeat(800)))); + } + h.push(Message::tool_result("short", "shell", "ok")); + let before = history_tokens("", &h); + let t0 = std::time::Instant::now(); + let ids = fold_results(&mut h); + let after = history_tokens("", &h); + eprintln!("fold: {before} → {after} tokens, {} results, {:?}", ids.len(), t0.elapsed()); + // The newest messages keep their results whole; the rest keep their first words. + assert_eq!(ids.len(), 17); + assert!(after * 4 < before, "{before} → {after}"); + assert!(h[2].folded && h[2].text.contains("fn f0()") && h[2].text.contains("已收起")); + assert!(!h[h.len() - 2].folded && h[h.len() - 2].text.len() > 5000); + assert!(!h.last().unwrap().folded, "a short result stays"); + // Done once: a second pass finds nothing, so the model reads the same thing every turn. + assert!(fold_results(&mut h).is_empty()); + // The window's copy keeps the whole result and gives the model the same words. + let whole = format!("fn f0() {{}}\n{}", "// 很長的檔案內容 ".repeat(800)); + assert_eq!(folded_text(&whole), h[2].text); + } + #[test] fn the_words_that_mean_money_sending_deleting_are_sensitive() { assert!(computer::sensitive_words("傳送")); diff --git a/src/app.rs b/src/app.rs index dc5f657..1a94fde 100644 --- a/src/app.rs +++ b/src/app.rs @@ -1915,6 +1915,12 @@ impl App { StreamEvent::NextStep(via) => b.messages.push(Message::assistant("", &via)), StreamEvent::ToolResult(m) => b.messages.push(m), StreamEvent::Compacted(n, summary, boundary) => crate::model::fold_in(&mut b.messages, n, summary, boundary), + // Old results set aside from the model's view: marked here, whole for the person. + StreamEvent::Folded(ids) => { + for m in b.messages.iter_mut().filter(|m| m.role == Role::Tool && ids.contains(&m.tool_call_id)) { + m.folded = true; + } + } StreamEvent::ToolStatus(call_id, st) => { if let Some(c) = b.messages.iter_mut().rev().flat_map(|m| m.tool_calls.iter_mut()).find(|c| c.id == call_id) { c.status = st; @@ -4809,6 +4815,10 @@ fn group_history(messages: &[Message], speaker: Option, st: &State) -> Vec< m.context = if m.context.is_empty() { line } else { format!("{}\n{line}", m.context) }; } } + // A result set aside in a long chat: the model reads its first words (as it did then). + if m.role == Role::Tool && m.folded { + m.text = agent::folded_text(&m.text); + } if !m.attachments.is_empty() { let (extra, images) = crate::attach::for_model(&m.attachments); m.text = format!("{}{extra}", m.text); diff --git a/src/model.rs b/src/model.rs index 45d30cb..60cffa7 100644 --- a/src/model.rs +++ b/src/model.rs @@ -96,6 +96,10 @@ pub struct Message { /// 「還沒達成」 that starts the next turn. The model reads it after the words (goal::context_line). #[serde(default, skip_serializing_if = "String::is_empty")] pub goal: String, + /// A step's result set aside from what the model reads (a long chat: see agent::fold_results). + /// The chat keeps the whole result for the person; the model gets its first words. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub folded: bool, /// A line AnyBot itself wrote in the chat (how a goal stands): shown small in the middle, /// never sent to the model. #[serde(default, skip_serializing_if = "std::ops::Not::not")] diff --git a/src/providers.rs b/src/providers.rs index 407669f..da4c995 100644 --- a/src/providers.rs +++ b/src/providers.rs @@ -217,6 +217,9 @@ pub enum StreamEvent { /// 自己進化: after the turn, the way that worked was kept as a skill (with the time of the /// reply it learned from, which gets a line saying so). Learned(crate::memory::Skill, i64), + /// Old step results were set aside from the model's view (their call ids): the chat marks + /// them, so the model reads them the same way next turn. + Folded(Vec), /// 目標: the check after a turn has spoken (for the goal set at this time, ms). Goal(i64, crate::goal::Judged), Done,