diff --git a/crates/openplotva-llm/src/aifarm.rs b/crates/openplotva-llm/src/aifarm.rs index d5e358e..fbca3d5 100644 --- a/crates/openplotva-llm/src/aifarm.rs +++ b/crates/openplotva-llm/src/aifarm.rs @@ -6612,6 +6612,7 @@ pub fn build_session_history_with_limit( } history.push(turn); } + cap_stored_tool_outputs(&mut history); history.push(HistoryMessage { role: ROLE_USER.to_owned(), kind: MESSAGE_KIND_TEXT.to_owned(), @@ -6630,6 +6631,90 @@ pub fn build_session_history_with_limit( history } +/// Stored tool outputs re-enter every later prompt while their message stays in +/// the history window, and the window counts visible messages, not tool results. +/// One turn with a dozen web searches once kept a chat over the model context +/// until the window slid past it, so stored outputs share a character budget, +/// newest first. +const STORED_TOOL_OUTPUT_MAX_CHARS: usize = 3_000; +const STORED_TOOL_OUTPUTS_TOTAL_MAX_CHARS: usize = 12_000; + +fn cap_stored_tool_outputs(history: &mut [HistoryMessage]) { + let mut total_remaining = STORED_TOOL_OUTPUTS_TOTAL_MAX_CHARS; + for tool_call in history + .iter_mut() + .rev() + .filter_map(|turn| turn.tool_call.as_mut()) + { + if total_remaining == 0 { + tool_call.output = None; + continue; + } + let Some(output) = tool_call.output.as_mut() else { + continue; + }; + let budget = STORED_TOOL_OUTPUT_MAX_CHARS.min(total_remaining); + let mut lengths = Vec::new(); + collect_json_string_lengths(output, &mut lengths); + let cap = fair_string_cap(lengths, budget); + let kept = cap_json_strings(output, cap); + total_remaining -= if cap == usize::MAX { kept } else { budget }; + } +} + +fn collect_json_string_lengths(value: &Value, lengths: &mut Vec) { + match value { + Value::String(text) => lengths.push(text.chars().count()), + Value::Array(items) => items + .iter() + .for_each(|item| collect_json_string_lengths(item, lengths)), + Value::Object(fields) => fields + .values() + .for_each(|field| collect_json_string_lengths(field, lengths)), + Value::Null | Value::Bool(_) | Value::Number(_) => {} + } +} + +/// Largest per-string length that keeps the strings within `budget`, so short +/// fields such as a status or a query stay whole and only long ones are cut. +fn fair_string_cap(mut lengths: Vec, budget: usize) -> usize { + lengths.sort_unstable(); + let mut remaining = budget; + let count = lengths.len(); + for (index, length) in lengths.into_iter().enumerate() { + let share = remaining / (count - index); + if length > share { + return share; + } + remaining -= length; + } + usize::MAX +} + +fn cap_json_strings(value: &mut Value, cap: usize) -> usize { + match value { + Value::String(text) => { + let chars = text.chars().count(); + if chars <= cap { + return chars; + } + let mut kept: String = text.chars().take(cap).collect(); + kept.push('…'); + *text = kept; + cap + } + Value::Array(items) => items + .iter_mut() + .map(|item| cap_json_strings(item, cap)) + .sum(), + Value::Object(fields) => fields + .values_mut() + .map(|field| cap_json_strings(field, cap)) + .sum(), + Value::Null | Value::Bool(_) | Value::Number(_) => 0, + } +} + pub fn build_default_initial_messages( input: &DialogInput, ) -> Result, AifarmMessageError> { @@ -11270,6 +11355,89 @@ mod tests { Ok(()) } + #[test] + fn stored_tool_outputs_share_a_budget_newest_first() -> Result<(), AifarmMessageError> { + let mut input = base_input(); + input.message = DialogMessage { + id: 6, + text: "плотва нарисуй свинью".to_owned(), + ..DialogMessage::default() + }; + let search = |call: usize| HistoryMessage { + role: ROLE_TOOL.to_owned(), + kind: MESSAGE_KIND_TOOL_RESPONSE.to_owned(), + message_id: 5, + tool_call: Some(ToolCall { + name: "web_search".to_owned(), + r#ref: format!("call-1-{call}"), + output: Some(json!({ + "data": {"query": format!("query {call}"), "results": "р".repeat(20_000)}, + "status": "ok", + })), + ..ToolCall::default() + }), + ..HistoryMessage::default() + }; + let mut history = (0..12).rev().map(search).collect::>(); + history.push(HistoryMessage { + role: ROLE_USER.to_owned(), + kind: MESSAGE_KIND_TEXT.to_owned(), + name: "User".to_owned(), + text: "найди всё про неё".to_owned(), + message_id: 5, + ..HistoryMessage::default() + }); + input.history = history; + + let history = build_session_history_with_limit(&input, DEFAULT_CONTEXT_HISTORY_LIMIT); + let outputs = history + .iter() + .filter_map(|turn| turn.tool_call.as_ref()) + .map(|call| (call.r#ref.as_str(), call.output.clone())) + .collect::>(); + assert_eq!(outputs.len(), 12); + let kept = outputs + .iter() + .filter(|(_, output)| output.is_some()) + .map(|(call_ref, _)| *call_ref) + .collect::>(); + assert_eq!(kept, ["call-1-8", "call-1-9", "call-1-10", "call-1-11"]); + let newest = outputs[11].1.as_ref().expect("newest output kept"); + assert_eq!(newest["status"], "ok"); + let results = newest["data"]["results"].as_str().unwrap_or_default(); + assert!(results.ends_with('…')); + assert!(results.chars().count() < STORED_TOOL_OUTPUT_MAX_CHARS); + + let messages = build_initial_messages_with_options(&input, &history, true)?; + let history_chars = messages[1..] + .iter() + .map(|message| message.content.chars().count()) + .sum::(); + assert!( + history_chars < 20_000, + "history rendered {history_chars} chars" + ); + Ok(()) + } + + #[test] + fn small_stored_tool_outputs_stay_whole() { + let mut turns = vec![HistoryMessage { + role: ROLE_TOOL.to_owned(), + kind: MESSAGE_KIND_TOOL_RESPONSE.to_owned(), + message_id: 3, + tool_call: Some(ToolCall { + name: "draw_image".to_owned(), + output: Some(json!({"data": {"status": "scheduled", "queue": [1, 2]}})), + ..ToolCall::default() + }), + ..HistoryMessage::default() + }]; + let before = turns.clone(); + cap_stored_tool_outputs(&mut turns); + assert_eq!(turns, before); + } + #[test] fn session_history_uses_shared_context_limit() { let now = at(12, 0);