diff --git a/src/agent.rs b/src/agent.rs index dd702c0..fde59b6 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -941,13 +941,15 @@ pub fn fold_results(history: &mut [Message]) -> Vec { /// 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); + // (The tools' descriptions go with every request too: ~12 000 tokens for a bot with all.) + let tools = tools_tokens(&job.req.tools); + let used = history_tokens(&job.req.system, history) + tools; 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); + let now = history_tokens(&job.req.system, history) + tools; eprintln!("AnyBot:對話很長,先收起 {} 個較早的步驟結果(約 {used} → {now} token)", set_aside.len()); send(StreamEvent::Folded(set_aside)); if percent > 0 && now * 100 < job.context_tokens * percent { @@ -983,6 +985,175 @@ fn maybe_compact(job: &Job, history: &mut Vec, percent: u64, cancel: &A Some(cut) } +/// What the tools' descriptions take of every request (estimated like the rest). +fn tools_tokens(tools: &[serde_json::Value]) -> u64 { + tools.iter().map(|t| estimate_tokens(&t.to_string())).sum() +} + +/// A way to make room when the model says the request is too long, in the order they're tried. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum RoomWay { + /// Take the pictures out (one screenshot was 160 000 tokens to a gateway that reads it as text). + Pictures, + /// Set aside every result but the newest few (not only the old ones). + Results, + /// Fold earlier messages into a summary — inside this turn too, when it has only one request. + Summary, +} + +/// What this turn has done to make room (since the person last wrote). +#[derive(Default)] +struct Room { + tried: Vec, + /// The way the coming retry rides on (None once a request went through). + last: Option, + /// The pictures taken out cost far more than pictures do (read as text): when the retry + /// without them goes through, this model gets none from now on. + pictures_as_text: bool, +} + +/// More than this per picture beyond our estimate, and the model is reading pictures as text (a +/// model that sees takes a few thousand; jenny-Host's gateway took ~155 000 for one). +const PICTURE_AS_TEXT_TOKENS: u64 = 20_000; + +/// Whether the pictures are what made the request so long: the model's count (from its error) +/// beyond our estimate, per picture sent, is far more than any picture costs a model that sees. +/// A model that only went a little over with its pictures is not stopped from seeing. +fn pictures_read_as_text(error: &str, job: &Job, history: &[Message]) -> bool { + let Some(prompt) = providers::overflow_prompt(error) else { return false }; + let pictures: u64 = history.iter().map(|m| m.images.len() as u64).sum(); + if pictures == 0 { + return false; + } + let ours = history_tokens(&job.req.system, history) + tools_tokens(&job.req.tools); + prompt.saturating_sub(ours) / pictures > PICTURE_AS_TEXT_TOKENS +} + +/// Results kept whole when every other one is set aside to make room. +const ROOM_KEEP_RESULTS: usize = 2; + +/// Make room the next way not yet tried that changes anything. None: nothing is left to take. +fn make_room(job: &Job, history: &mut Vec, room: &mut Room, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Option { + for way in [RoomWay::Pictures, RoomWay::Results, RoomWay::Summary] { + if room.tried.contains(&way) { + continue; + } + room.tried.push(way); + let made = match way { + RoomWay::Pictures => { + let n = drop_pictures(history); + if n > 0 { + eprintln!("AnyBot:對話太長,先拿掉 {n} 張圖片再試"); + send(StreamEvent::Retrying(format!("對話太長了,先拿掉 {n} 張截圖再試一次…"))); + send(StreamEvent::PicturesDropped); + } + n > 0 + } + RoomWay::Results => { + let ids = fold_all_but_newest(history, ROOM_KEEP_RESULTS); + if !ids.is_empty() { + send(StreamEvent::Retrying(format!("對話太長了,先收起 {} 個步驟的結果再試一次…", ids.len()))); + send(StreamEvent::Folded(ids.clone())); + } + !ids.is_empty() + } + RoomWay::Summary => maybe_compact(job, history, 0, cancel, send).is_some() || compact_within_turn(job, history, cancel, send).is_some(), + }; + if made { + room.last = Some(way); + return Some(way); + } + } + None +} + +/// Take every picture out of what the model reads (in its place, a line saying so). How many. +fn drop_pictures(history: &mut [Message]) -> usize { + let mut n = 0; + for m in history.iter_mut().filter(|m| !m.images.is_empty()) { + n += m.images.len(); + m.images.clear(); + m.text.push_str(if m.role == Role::Tool { "\n(這一步的截圖已拿掉:對話太長了。需要再看就重新截圖。)" } else { "\n(附的圖片已拿掉:對話太長了。)" }); + } + n +} + +/// Set aside every long result but the newest `keep` (fold_results spares the newest messages; +/// this, for when the model said it is too long, spares only these). The ids set aside. +fn fold_all_but_newest(history: &mut [Message], keep: usize) -> Vec { + let results: Vec = history.iter().enumerate().filter(|(_, m)| m.role == Role::Tool && !m.summary).map(|(i, _)| i).collect(); + let spare = results.len().saturating_sub(keep); + let mut ids = vec![]; + for &i in &results[..spare] { + let m = &mut history[i]; + if !m.folded && 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 +} + +/// Where a turn with one request from the person can be summarized: just before a step of the +/// bot's (its calls and their results stay together), leaving the newest messages. None when +/// there is no such place. +fn turn_cut(h: &[Message]) -> Option<(usize, usize)> { + let ask = h.iter().rposition(|m| m.role == Role::User && !m.summary)?; + let last = h.len().checked_sub(KEEP_RECENT_MESSAGES)?; + let cut = (ask + 2..=last).rev().find(|&i| h[i].role == Role::Assistant && h[i - 1].role != Role::Assistant)?; + Some((ask, cut)) +} + +/// Summarize a long turn's earlier steps when there is no earlier request of the person's to cut +/// at (one routine, a hundred steps): the request stays word for word, then the summary of what +/// was done so far, then the newest steps. For this turn only: the chat keeps its steps (set +/// aside as they are), and the next turn has the person's new message to summarize at. +fn compact_within_turn(job: &Job, history: &mut Vec, cancel: &AtomicBool, send: &dyn Fn(StreamEvent)) -> Option { + let (ask, cut) = turn_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()), + effort: String::new(), + ..job.req.clone() + }; + let quiet = |ev: StreamEvent| { + if matches!(ev, StreamEvent::Alive | StreamEvent::Retrying(_)) { + send(StreamEvent::Alive); + } + }; + job.note(crate::oplog::Record::StepAttempt { op: job.op.clone(), step: "compaction".into(), attempt: 1 }); + let out = providers::run_step(&req, cancel, &quiet).ok()?; + if out.text.trim().is_empty() || cancel.load(Ordering::Relaxed) { + return None; + } + let summary = Message { role: Role::Assistant, text: out.text.trim().to_string(), summary: true, via: job.via.clone(), at: crate::model::now_ms(), ..Default::default() }; + let request = history[ask].clone(); + history.splice(..cut, [summary, request]); + Some(cut) +} + +/// Said with the error when every way of making room was tried: what is still big. +fn still_too_long(job: &Job, history: &[Message], room: &Room) -> String { + let done: Vec<&str> = room.tried.iter().map(|w| match w { + RoomWay::Pictures => "拿掉圖片", + RoomWay::Results => "收起較早的步驟結果", + RoomWay::Summary => "把較早的內容整理成摘要", + }).collect(); + format!( + "(已經試過{},還是太長。現在大約:指示 {} tokens、工具說明 {} tokens、對話 {} tokens;這個模型可讀約 {} tokens。可以在 Bot 設定裡關掉用不到的能力,或換一個能讀更長的模型。)", + done.join("、"), + estimate_tokens(&job.req.system), + tools_tokens(&job.req.tools), + history_tokens("", history), + job.context_tokens + ) +} + /// Wait for the person's answer; stopping the reply counts as a no. /// 拒絕後停下: the answer to a step the person already refused this turn. const REFUSED_ALREADY: &str = "沒有執行,也沒有再問使用者:這個操作他剛才已經拒絕過了。在他傳下一則訊息之前不要再試同樣的操作,也不要換個寫法做同一件事。告訴他你停在哪裡,問他想怎麼做。"; @@ -1241,9 +1412,9 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< prompt: history.last().filter(|m| m.role == Role::User).map(|m| crate::oplog::Prompt { at: m.at, text: m.text.clone() }), }); let mut closing = Closing { log: job.log.clone(), op: job.op.clone(), cancel: cancel.clone(), written: false }; - // Folding the chat because the model said it was too long: once per thing the person - // said (a second time means folding didn't help). - let mut overflow_folded = false; + // Making room because the model said it was too long: each way once per thing the person + // said (see make_room), and which one this step's retry rides on. + let mut room = Room::default(); maybe_compact(&job, &mut history, COMPACT_THRESHOLD_PERCENT, &cancel, &send); let mut plan = StepPlan::new(job.step_model.clone()); // A quick step's answer was set aside: its (empty) message in the chat is reused. @@ -1294,7 +1465,7 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< if step > 0 { maybe_compact(&job, &mut history, COMPACT_THRESHOLD_PERCENT + COMPACT_TOLERANCE_PERCENT, &cancel, &send); if drain_steer(&job, &mut history, &send) { - overflow_folded = false; + room = Room::default(); // The person wrote: what they refused before is theirs to allow again. refused.borrow_mut().clear(); } @@ -1340,20 +1511,39 @@ pub fn spawn(job: Job, bot_id: u64, tx: Sender<(u64, StreamEvent)>, cancel: Arc< None => providers::run_step(&main_req, &cancel, &send), }; match got { - Ok(o) => break o, - // Too long for the model: that answer is thrown away, older messages are - // folded into a summary (however full the chat looks by our estimate), and - // the same step is asked again. - Err(e) if providers::is_context_overflow(&e) && !overflow_folded && !cancel.load(Ordering::Relaxed) => { - overflow_folded = true; - if maybe_compact(&job, &mut history, 0, &cancel, &send).is_none() { - closing.close(crate::oplog::Outcome::Failed); - send(StreamEvent::Error(e)); - return; + Ok(o) => { + // Taking the pictures out is what made it fit: this model gets none from + // now on (its screenshots in words instead). + if room.last == Some(RoomWay::Pictures) && room.pictures_as_text { + providers::mark_pictures_too_costly(&job.req); + } + room.last = None; + break o; + } + // Too long for the model: that answer is thrown away, room is made — the + // pictures, then old results, then a summary — and the same step is asked + // again, however full the chat looks by our estimate. + Err(e) if providers::is_context_overflow(&e) && !cancel.load(Ordering::Relaxed) => { + // The size it named is the bot's from now on (summarized in time next). + if let Some(limit) = providers::overflow_limit(&e).filter(|l| *l < job.context_tokens) { + job.context_tokens = limit; + send(StreamEvent::ContextLimit(limit)); + } + let as_text = pictures_read_as_text(&e, &job, &history); + let way = make_room(&job, &mut history, &mut room, &cancel, &send); + if way == Some(RoomWay::Pictures) { + room.pictures_as_text = as_text; + } + match way { + Some(_) => {} + None => { + closing.close(crate::oplog::Outcome::Failed); + send(StreamEvent::Error(format!("{e}\n{}", still_too_long(&job, &history, &room)))); + return; + } } } Err(e) => { - let e = if providers::is_context_overflow(&e) && overflow_folded { format!("{e}\n(已經把較早的對話整理成摘要再試過一次,還是太長。)") } else { e }; closing.close(crate::oplog::Outcome::Failed); send(StreamEvent::Error(e)); return; @@ -4793,6 +4983,8 @@ echo 'done送出了' > done.html; (setsid pyt let (evs, _) = drive(job, ApprovalAnswer::Reject); assert!(matches!(evs.last(), Some(StreamEvent::Done)), "{:?}", evs.iter().filter_map(|e| if let StreamEvent::Error(e) = e { Some(e.clone()) } else { None }).collect::>()); assert!(evs.iter().any(|e| matches!(e, StreamEvent::Compacted(..)))); + // The size the error named is kept (it is smaller than the bot was told). + assert!(evs.iter().any(|e| matches!(e, StreamEvent::ContextLimit(8192)))); let texts: Vec = evs.iter().filter_map(|e| if let StreamEvent::StepDone(m) = e { Some(m.text.clone()) } else { None }).collect(); assert_eq!(texts, vec!["好了"]); let seen = seen.lock().unwrap(); @@ -4800,6 +4992,104 @@ echo 'done送出了' > done.html; (setsid pyt assert!(seen[2].contains("摘要:問過六個問題") && !seen[2].contains("第 0 個問題"), "{}", seen[2]); } + /// jenny-Host, 2026-11-14 18:10: one screenshot took a request to a gateway that reads it as + /// text from ~18 000 to 178 553 tokens. The picture goes, the step is asked again — no summary + /// needed — the model's size is kept, and it gets no pictures from now on. + #[test] + fn a_screenshot_too_big_for_the_model_is_taken_out_and_the_step_asked_again() { + let husky = r#"{"error":{"message":"Prompt is 178553 tokens; the context limit on 'husky' for you is 131072 tokens."}}"#; + let (port, seen) = fake_http(vec![(400, husky.into()), sse_text("好了")]); + let shot = ToolCall { id: "s1".into(), name: "browser_screenshot".into(), args: "{}".into(), status: ToolStatus::Done }; + let picture = "QUJD".repeat(50_000); + let history = vec![ + Message::user("看一下這頁"), + Message { tool_calls: vec![shot], ..Message::assistant("", "test") }, + Message { images: vec![picture.clone()], ..Message::tool_result("s1", "browser_screenshot", "AnyBot 瀏覽器分頁的截圖:貓抓板") }, + ]; + let req = ChatRequest { kind: ProviderKind::Custom, base_url: format!("http://127.0.0.1:{port}/v1"), api_key: String::new(), model: "husky".into(), system: String::new(), history, tools: vec![], session: String::new(), effort: String::new() }; + // (The bot was told the model reads more than it does.) + let job = Job { req: req.clone(), context_tokens: 200_000, ..test_job() }; + let (evs, _) = drive(job, ApprovalAnswer::Reject); + assert!(matches!(evs.last(), Some(StreamEvent::Done)), "{:?}", evs.iter().filter_map(|e| if let StreamEvent::Error(e) = e { Some(e.clone()) } else { None }).collect::>()); + assert!(evs.iter().any(|e| matches!(e, StreamEvent::PicturesDropped))); + assert!(evs.iter().any(|e| matches!(e, StreamEvent::ContextLimit(131072)))); + assert!(!evs.iter().any(|e| matches!(e, StreamEvent::Compacted(..))), "no summary was needed"); + let seen = seen.lock().unwrap(); + assert_eq!(seen.len(), 2, "the step was asked again, once"); + assert!(seen[0].contains(&picture[..400]) && !seen[1].contains(&picture[..400]), "the picture went"); + assert!(seen[1].contains("截圖已拿掉")); + assert!(!providers::sees_images(&req), "no more pictures for this model"); + } + + /// One request and many steps (a routine): old results are set aside first, then the turn's + /// earlier steps are summarized inside it — the request stays, the newest steps stay. + #[test] + fn a_long_turn_with_one_request_is_summarized_inside_itself() { + let (port, seen) = fake_http(vec![(400, OVERFLOW_BODY.into()), (400, OVERFLOW_BODY.into()), sse_text("摘要:前面的步驟做完了"), sse_text("完成")]); + let mut history = vec![Message::user("把十件事做完")]; + for i in 0..10 { + let call = ToolCall { id: format!("c{i}"), name: "shell".into(), args: serde_json::json!({"command": format!("echo step-{i}")}).to_string(), status: ToolStatus::Done }; + history.push(Message { tool_calls: vec![call], ..Message::assistant("", "test") }); + history.push(Message::tool_result(&format!("c{i}"), "shell", &format!("結果 {i}:{}", "很長的輸出 ".repeat(200)))); + } + let job = Job { req: ChatRequest { kind: ProviderKind::Custom, base_url: format!("http://127.0.0.1:{port}/v1"), api_key: String::new(), model: "m".into(), system: String::new(), history, tools: vec![], session: String::new(), effort: String::new() }, ..test_job() }; + let (evs, _) = drive(job, ApprovalAnswer::Reject); + assert!(matches!(evs.last(), Some(StreamEvent::Done)), "{:?}", evs.iter().filter_map(|e| if let StreamEvent::Error(e) = e { Some(e.clone()) } else { None }).collect::>()); + assert!(evs.iter().any(|e| matches!(e, StreamEvent::Folded(ids) if ids.len() == 8)), "all but the newest two results set aside"); + let seen = seen.lock().unwrap(); + assert_eq!(seen.len(), 4); + // After the fold: the newest two results whole, the others short. + assert!(seen[1].contains("結果 9") && seen[1].contains("較早的結果已收起")); + // After the summary: the request, the summary, the newest steps — not the first ones. + assert!(seen[3].contains("把十件事做完") && seen[3].contains("摘要:前面的步驟做完了"), "{}", &seen[3][..seen[3].len().min(600)]); + assert!(seen[3].contains("step-9") && !seen[3].contains("step-0")); + } + + /// A model that sees, a little over with its pictures: they go for this step, but it keeps + /// getting pictures (only one reading them as text is stopped from it). + #[test] + fn a_model_that_sees_keeps_its_pictures_after_going_a_little_over() { + let over = r#"{"error":{"message":"This model's maximum context length is 32768 tokens. However, your messages resulted in 33500 tokens."}}"#; + let (port, _) = fake_http(vec![(400, over.into()), sse_text("好了")]); + let shot = ToolCall { id: "s1".into(), name: "computer_use_screenshot".into(), args: "{}".into(), status: ToolStatus::Done }; + let history = vec![ + Message::user("看螢幕"), + Message { tool_calls: vec![shot], ..Message::assistant("", "test") }, + Message { images: vec!["QUJD".repeat(50_000)], ..Message::tool_result("s1", "computer_use_screenshot", &"螢幕上的字 ".repeat(5_000)) }, + ]; + let req = ChatRequest { kind: ProviderKind::Custom, base_url: format!("http://127.0.0.1:{port}/v1"), api_key: String::new(), model: "sees".into(), system: String::new(), history, tools: vec![], session: String::new(), effort: String::new() }; + let (evs, _) = drive(Job { req: req.clone(), ..test_job() }, ApprovalAnswer::Reject); + assert!(matches!(evs.last(), Some(StreamEvent::Done))); + assert!(evs.iter().any(|e| matches!(e, StreamEvent::PicturesDropped))); + assert!(providers::sees_images(&req), "it still gets pictures"); + } + + #[test] + fn making_room_takes_what_is_there_in_order() { + // Pictures first, only when there are some; a result-only chat goes to results. + let mut h = vec![Message::user("x"), Message { images: vec!["QUJD".into()], ..Message::tool_result("a", "computer_use_screenshot", "截圖") }]; + assert_eq!(drop_pictures(&mut h), 1); + assert!(h[1].images.is_empty() && h[1].text.contains("截圖已拿掉")); + assert_eq!(drop_pictures(&mut h), 0); + // Every long result but the newest two. + let mut h: Vec = (0..5).map(|i| Message::tool_result(&format!("r{i}"), "shell", &"字".repeat(700))).collect(); + assert_eq!(fold_all_but_newest(&mut h, 2), vec!["r0", "r1", "r2"]); + assert!(!h[3].folded && !h[4].folded); + // A turn's cut: before a step of the bot's, leaving the newest messages; none if short. + let call = |i: usize| Message { tool_calls: vec![ToolCall { id: format!("c{i}"), name: "shell".into(), args: "{}".into(), status: ToolStatus::Done }], ..Message::assistant("", "t") }; + let mut t = vec![Message::user("做事")]; + for i in 0..8 { + t.push(call(i)); + t.push(Message::tool_result(&format!("c{i}"), "shell", "ok")); + } + let (ask, cut) = turn_cut(&t).unwrap(); + assert_eq!(ask, 0); + assert!(t[cut].role == Role::Assistant && t.len() - cut >= KEEP_RECENT_MESSAGES); + assert_eq!(turn_cut(&t[..5]), None); + // The tools' descriptions count toward what a request takes. + assert!(tools_tokens(&tools::specs()) > 1_000); + } + /// Still too long after folding once: the turn ends with a clear error (no loop of folds). #[test] fn a_second_overflow_ends_the_turn() { diff --git a/src/app.rs b/src/app.rs index a015600..acd77fc 100644 --- a/src/app.rs +++ b/src/app.rs @@ -2479,6 +2479,19 @@ impl App { m.images.clear(); } } + // The model said how much it reads: this bot summarizes in time from now on. + StreamEvent::ContextLimit(n) => { + b.context_tokens = n; + self.dirty = true; + } + // Pictures taken out to make room: not sent again next turn (they stayed in + // memory here — one screenshot kept a chat over the limit turn after turn). + StreamEvent::PicturesDropped => { + let from = crate::model::model_view_start(&b.messages); + for m in b.messages[from..].iter_mut().filter(|m| m.role == Role::Tool) { + m.images.clear(); + } + } 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; diff --git a/src/providers.rs b/src/providers.rs index c5d4cc6..60ea6a6 100644 --- a/src/providers.rs +++ b/src/providers.rs @@ -247,6 +247,12 @@ pub enum StreamEvent { /// 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 model said how much it can read (its "too long" error named it): kept as the bot's + /// context size, so it is summarized in time from now on. + ContextLimit(u64), + /// The pictures were taken out of the chat to make room: the chat lets go of them too, so + /// the next turn doesn't send them again. + PicturesDropped, /// 目標: the check after a turn has spoken (for the goal set at this time, ms). Goal(i64, crate::goal::Judged), Done, @@ -433,6 +439,81 @@ const BUSY_RETRY_MS: u64 = 8_000; /// summary before asking once more, instead of giving up. pub const CONTEXT_OVERFLOW: &str = "對話太長了,超過這個模型能讀的長度。"; +/// The model's own size, as its "too long" error states it: "the context limit on 'husky' for +/// you is 131072 tokens", "maximum context length is 128000 tokens", "210000 tokens > 200000 +/// maximum". None when it doesn't say. +pub fn overflow_limit(msg: &str) -> Option { + let low = msg.to_lowercase().replace([',', '_'], ""); + // Every number of four digits or more, with where it is. + let mut nums: Vec<(usize, usize, u64)> = vec![]; + let b = low.as_bytes(); + let mut i = 0; + while i < b.len() { + if b[i].is_ascii_digit() { + let start = i; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + if let Ok(n) = low[start..i].parse::() { + if (1_000..=10_000_000).contains(&n) { + nums.push((start, i, n)); + } + } + } else { + i += 1; + } + } + let mut found: Vec = vec![]; + for kw in ["limit", "maximum context length", "context length", "context window", "max context", "maximum", "上限"] { + for (at, _) in low.match_indices(kw) { + let after = at + kw.len(); + // A number of tokens shortly after the word ("limit … is 131072 tokens") … + let of_tokens = |e: usize| low[e..].trim_start().starts_with("tok"); + if let Some(n) = nums.iter().find(|(s, e, _)| *s >= after && *s - after <= 40 && of_tokens(*e)) { + found.push(n.2); + } + // … or right before it ("200000 maximum"). + if let Some(n) = nums.iter().find(|(_, e, _)| *e <= at && at - *e <= 3) { + found.push(n.2); + } + } + } + found.into_iter().min() +} + +/// How long the request was, as the "too long" error states it ("Prompt is 178553 tokens", +/// "resulted in 130512 tokens", "210000 tokens > 200000 maximum"): the largest number of tokens +/// it names other than the limit. None when it names no other. +pub fn overflow_prompt(msg: &str) -> Option { + let low = msg.to_lowercase().replace([',', '_'], ""); + let limit = overflow_limit(msg); + let mut best: Option = None; + let b = low.as_bytes(); + let mut i = 0; + while i < b.len() { + if b[i].is_ascii_digit() { + let start = i; + while i < b.len() && b[i].is_ascii_digit() { + i += 1; + } + let n = low[start..i].parse::().unwrap_or(0); + if (1_000..=100_000_000).contains(&n) && low[i..].trim_start().starts_with("tok") && Some(n) != limit { + best = best.max(Some(n)); + } + } else { + i += 1; + } + } + best +} + +/// This model is sent no pictures from now on (this run): one made a request too long for it +/// (a gateway that reads a screenshot as text — 160 000 tokens for one). Its screenshots are +/// described in words instead (看圖小幫手), like a model that can't see. +pub fn mark_pictures_too_costly(req: &ChatRequest) { + mark_blind(req); +} + /// The request didn't fit the model's context (a retry as-is would fail the same way). pub fn is_context_overflow(msg: &str) -> bool { msg.starts_with(CONTEXT_OVERFLOW) @@ -1519,6 +1600,26 @@ pub fn list_models(kind: ProviderKind, base_url: &str, api_key: &str) -> Result< #[cfg(test)] mod tests { + #[test] + fn a_too_long_error_says_how_much_the_model_reads() { + // jenny-Host's model, 2026-11-14 18:10. + assert_eq!(overflow_limit("Prompt is 178553 tokens; the context limit on 'husky' for you is 131072 tokens."), Some(131072)); + // OpenAI / vLLM: the limit, not the other numbers. + assert_eq!(overflow_limit("This model's maximum context length is 128000 tokens. However, your messages resulted in 130512 tokens."), Some(128000)); + assert_eq!(overflow_limit("This model's maximum context length is 32768 tokens. However, you requested 40000 tokens (35000 in the messages, 5000 in the completion)."), Some(32768)); + // Anthropic: "N tokens > M maximum". + assert_eq!(overflow_limit("prompt is too long: 210000 tokens > 200000 maximum"), Some(200000)); + assert_eq!(overflow_limit("context_length_exceeded: context window of 131,072 tokens"), Some(131072)); + // How long the request was: the largest count that isn't the limit. + assert_eq!(overflow_prompt("Prompt is 178553 tokens; the context limit on 'husky' for you is 131072 tokens."), Some(178553)); + assert_eq!(overflow_prompt("This model's maximum context length is 32768 tokens. However, you requested 40000 tokens (35000 in the messages, 5000 in the completion)."), Some(40000)); + assert_eq!(overflow_prompt("prompt is too long: 210000 tokens > 200000 maximum"), Some(210000)); + assert_eq!(overflow_prompt("context window of 131072 tokens"), None); + // Nothing said: nothing learned. + assert_eq!(overflow_limit("Prompt is too long"), None); + assert_eq!(overflow_limit("context length exceeded (request 2024-11-14)"), None); + } + use super::*; use std::io::{Read, Write}; use std::net::TcpListener;