From 706912ba33a331b3e34629629dc953c10c32c144 Mon Sep 17 00:00:00 2001 From: uiharuayako <2451602772@qq.com> Date: Mon, 23 Nov 2026 15:59:10 +0800 Subject: [PATCH] fix: budget tool images against the selected model context window --- Cargo.lock | 1 + .../cargo-dependency-boundaries.mjs | 7 + .../core-boundaries/rules/feature-rules.mjs | 1 + src/crates/adapters/ai-adapters/AGENTS.md | 6 +- src/crates/adapters/ai-adapters/Cargo.toml | 2 + src/crates/adapters/ai-adapters/src/client.rs | 91 ++- .../ai-adapters/src/client/image_budget.rs | 9 + .../src/client/image_budget/context.rs | 609 ++++++++++++++++++ .../src/client/image_budget/context_tests.rs | 579 +++++++++++++++++ src/crates/adapters/ai-adapters/src/lib.rs | 2 + .../src/providers/gemini/message_converter.rs | 68 +- .../src/providers/openai/message_converter.rs | 178 ++--- .../src/providers/openai/responses.rs | 2 + .../ai-adapters/src/providers/shared.rs | 3 + .../adapters/ai-adapters/src/vision_tokens.rs | 482 ++++++++++++++ .../src/vision_tokens/openai_patches.rs | 104 +++ src/crates/assembly/core/Cargo.toml | 1 + .../src/agentic/coordination/coordinator.rs | 2 + .../assembly/core/src/agentic/core/message.rs | 128 +++- .../core/src/agentic/core/messages_helper.rs | 16 +- .../src/agentic/execution/compression_job.rs | 8 +- .../src/agentic/execution/context_budget.rs | 8 +- .../src/agentic/execution/execution_engine.rs | 336 ++++++++-- .../agentic/execution/prompt_suggestion.rs | 17 +- .../src/agentic/execution/round_executor.rs | 32 +- .../assembly/core/src/util/token_counter.rs | 97 +-- .../contracts/config-contracts/src/types.rs | 17 +- src/crates/contracts/core-types/src/ai.rs | 6 + src/crates/contracts/core-types/src/lib.rs | 1 + .../core-types/src/token_estimate.rs | 114 ++++ 30 files changed, 2615 insertions(+), 312 deletions(-) create mode 100644 src/crates/adapters/ai-adapters/src/client/image_budget/context.rs create mode 100644 src/crates/adapters/ai-adapters/src/client/image_budget/context_tests.rs create mode 100644 src/crates/adapters/ai-adapters/src/vision_tokens.rs create mode 100644 src/crates/adapters/ai-adapters/src/vision_tokens/openai_patches.rs create mode 100644 src/crates/contracts/core-types/src/token_estimate.rs diff --git a/Cargo.lock b/Cargo.lock index 8dfff09b2a..b1e1976ac2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5822,6 +5822,7 @@ dependencies = [ "fs2", "futures", "hex", + "image 0.25.10", "keyring-core", "libc", "log", diff --git a/scripts/core-boundaries/cargo-dependency-boundaries.mjs b/scripts/core-boundaries/cargo-dependency-boundaries.mjs index 97a60f5bdf..d5b970a021 100644 --- a/scripts/core-boundaries/cargo-dependency-boundaries.mjs +++ b/scripts/core-boundaries/cargo-dependency-boundaries.mjs @@ -546,6 +546,13 @@ const THIRD_PARTY_CAPABILITY_PROFILES = new Map([ ['image', { label: 'Image', packages: new Map([ + ['openbitfun-ai-adapters', dependencyProfile([], { + optional: true, + useDefaultFeatures: false, + ownerFeatureCapabilities: new Map([ + ['vision-input', ['bmp', 'gif', 'jpeg', 'png', 'webp']], + ]), + })], ['openbitfun-computer-use', dependencyProfile(['jpeg', 'png'], { useDefaultFeatures: false })], ['openbitfun-services-core', dependencyProfile([], { optional: true, diff --git a/scripts/core-boundaries/rules/feature-rules.mjs b/scripts/core-boundaries/rules/feature-rules.mjs index 97703a78a3..d49f8c4f4b 100644 --- a/scripts/core-boundaries/rules/feature-rules.mjs +++ b/scripts/core-boundaries/rules/feature-rules.mjs @@ -896,6 +896,7 @@ export const coreClosedFeatureProfileRules = [ requiredFeatureRefs: [ 'ai-adapter-runtime', 'openbitfun-ai-adapters/local-tokenizer', + 'openbitfun-ai-adapters/vision-input', 'dep:openbitfun-agent-runtime', 'openbitfun-agent-runtime/agent-runtime', 'dep:openbitfun-agent-content', diff --git a/src/crates/adapters/ai-adapters/AGENTS.md b/src/crates/adapters/ai-adapters/AGENTS.md index a20cf6c80d..76f9dc47bb 100644 --- a/src/crates/adapters/ai-adapters/AGENTS.md +++ b/src/crates/adapters/ai-adapters/AGENTS.md @@ -40,8 +40,10 @@ provider-neutral contracts owned by `openbitfun-agent-stream`. the shared AIClient send boundary, including single-attempt Responses calls. Count user image parts and tool attachments together; preserve durable history, tool-result identities, opaque tool text and non-image media. Newer messages - keep their pixels first, with explicit omission text for older pixels. Verify - with `cargo test --locked -p openbitfun-ai-adapters --lib client::image_budget::tests`. + keep their pixels first, with explicit omission text for older pixels. + With `vision-input`, the selected client's context window also determines + whether older pixels must be omitted or current screenshots resized. + Verify with `cargo test --locked -p openbitfun-ai-adapters --features vision-input --lib -- client::image_budget vision_tokens`. - Normalize explicitly reported response models into the typed stream `response_model` observation. Responses/Codex lifecycle metadata is emitted before an associated error, and Chat Completions model identifiers remain diff --git a/src/crates/adapters/ai-adapters/Cargo.toml b/src/crates/adapters/ai-adapters/Cargo.toml index 547888c604..7fd5a1c293 100644 --- a/src/crates/adapters/ai-adapters/Cargo.toml +++ b/src/crates/adapters/ai-adapters/Cargo.toml @@ -38,6 +38,7 @@ serde = { workspace = true } serde_json = { workspace = true } sha2 = { workspace = true } hex = { workspace = true } +image = { workspace = true, optional = true } tokio = { workspace = true, features = ["macros", "rt", "sync", "time"] } tokio-stream = { workspace = true } tokio-tungstenite = { workspace = true, features = ["handshake"] } @@ -61,6 +62,7 @@ zbus-secret-service-keyring-store = { workspace = true, optional = true } [features] local-tokenizer = ["dep:tokenizers"] +vision-input = ["dep:base64", "dep:image", "image/bmp", "image/gif", "image/jpeg", "image/png", "image/webp"] image-generation = ["dep:base64"] subscription-auth = [ "dep:apple-native-keyring-store", diff --git a/src/crates/adapters/ai-adapters/src/client.rs b/src/crates/adapters/ai-adapters/src/client.rs index 0c8e8055a8..9ad8f82e42 100644 --- a/src/crates/adapters/ai-adapters/src/client.rs +++ b/src/crates/adapters/ai-adapters/src/client.rs @@ -379,7 +379,10 @@ impl AIClient { extra_body: Option, trace: Option, ) -> Result { - self.send_message_stream_with_extra_body_and_max_attempts( + let messages = self + .prepare_message_inputs(messages, tools.as_deref(), None, extra_body.as_ref()) + .await?; + self.send_prepared_message_stream( messages, tools, extra_body, @@ -415,15 +418,16 @@ impl AIClient { trace: Option, ) -> Result { let custom_body = self.config.custom_request_body.clone(); - self.send_message_stream_with_extra_body_and_max_attempts( - messages, - tools, - custom_body, - 1, - trace, - request_context, - ) - .await + let messages = self + .prepare_message_inputs( + messages, + tools.as_deref(), + request_context.as_ref(), + custom_body.as_ref(), + ) + .await?; + self.send_prepared_message_stream(messages, tools, custom_body, 1, trace, request_context) + .await } pub async fn send_message( @@ -537,9 +541,17 @@ impl AIClient { ) -> Result { let request_context = crate::providers::shared::prepare_request_context(self, request_context); + let messages = self + .prepare_message_inputs( + messages, + tools.as_deref(), + request_context.as_ref(), + extra_body.as_ref(), + ) + .await?; for attempt in 0..max_attempts { let stream_response = match self - .send_message_stream_with_extra_body_and_max_attempts( + .send_prepared_message_stream( messages.clone(), tools.clone(), extra_body.clone(), @@ -608,7 +620,55 @@ impl AIClient { unreachable!("send_message retry loop always returns") } - async fn send_message_stream_with_extra_body_and_max_attempts( + async fn prepare_message_inputs( + &self, + messages: Vec, + tools: Option<&[ToolDefinition]>, + request_context: Option<&ModelRequestContext>, + extra_body: Option<&serde_json::Value>, + ) -> Result> { + #[cfg(not(feature = "vision-input"))] + let _ = (tools, request_context); + // Project only the outgoing copy, against the actual selected client. + responses_websocket::validate(self)?; + // Account/channel failover and direct analysis calls share this boundary. + let messages = image_budget::project(messages, self.config.max_images_per_request)?; + image_budget::validate_extra_body(self.config.max_images_per_request, extra_body)?; + #[cfg(feature = "vision-input")] + let replaced = image_budget::context::validate_override( + &self.config, + &messages, + tools, + request_context, + extra_body, + )?; + #[cfg(feature = "vision-input")] + let messages = if !replaced + && messages + .iter() + .any(image_budget::context::may_contain_images) + { + let budget = image_budget::context::Budget::for_request( + &self.config, + tools, + request_context, + extra_body, + ); + // Decoding and resampling a large screenshot can occupy a CPU for + // a full scheduling slice. Keep it off the async transport worker. + tokio::task::spawn_blocking(move || -> Result<_> { + let mut messages = messages; + image_budget::context::apply(&mut messages, budget)?; + Ok(messages) + }) + .await?? + } else { + messages + }; + Ok(messages) + } + + async fn send_prepared_message_stream( &self, messages: Vec, tools: Option>, @@ -617,11 +677,6 @@ impl AIClient { trace: Option, request_context: Option, ) -> Result { - // Project only the outgoing copy, against the actual selected client. - responses_websocket::validate(self)?; - // Account/channel failover and direct analysis calls share this boundary. - let messages = image_budget::project(messages, self.config.max_images_per_request)?; - image_budget::validate_extra_body(self.config.max_images_per_request, extra_body.as_ref())?; match ApiFormat::parse(&self.config.format)? { ApiFormat::OpenAIChat => { openai::chat::send_stream( @@ -953,6 +1008,7 @@ mod tests { "type": "object", "properties": { "summary": { "type": "string" } } })), + ..Default::default() } } @@ -962,6 +1018,7 @@ mod tests { conversation_scope: None, prompt_cache_route_key: Some("lineage-1".to_string()), output_schema: None, + ..Default::default() }; let official = openai::chat::build_request_body_with_context( &make_test_client("openai", None), diff --git a/src/crates/adapters/ai-adapters/src/client/image_budget.rs b/src/crates/adapters/ai-adapters/src/client/image_budget.rs index c9eeb8aa4a..7d679ade3c 100644 --- a/src/crates/adapters/ai-adapters/src/client/image_budget.rs +++ b/src/crates/adapters/ai-adapters/src/client/image_budget.rs @@ -1,5 +1,10 @@ //! Model-specific image input budgets for an outgoing request copy. +#[cfg(feature = "vision-input")] +pub(super) mod context; +#[cfg(all(test, feature = "vision-input"))] +mod context_tests; + use crate::types::Message; use anyhow::Result; use openbitfun_core_types::errors::{AiProviderError, ErrorCategory}; @@ -480,6 +485,10 @@ mod tests { let mut selected = initial.clone(); selected.config.max_images_per_request = Some(3); let mut history = vec![tool_images("batch", 4)]; + // Use actual one-pixel images so the 4K window exercises the count limit. + for image in history[0].tool_image_attachments.as_mut().unwrap() { + image.data_base64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVR4nGNgAAIAAAUAAXpeqz8AAAAASUVORK5CYII=".into(); + } tokio::time::timeout(std::time::Duration::from_secs(5), async { initial .send_message_once_with_trace_and_request_context(history.clone(), None, None, None) diff --git a/src/crates/adapters/ai-adapters/src/client/image_budget/context.rs b/src/crates/adapters/ai-adapters/src/client/image_budget/context.rs new file mode 100644 index 0000000000..463b828f14 --- /dev/null +++ b/src/crates/adapters/ai-adapters/src/client/image_budget/context.rs @@ -0,0 +1,609 @@ +//! Pixel projection for one outgoing request. All positions refer to the +//! provider-neutral messages before the adapter merges roles and tool results. + +use super::{inline_media, is_content_part, is_image_part}; +use crate::client::format::ApiFormat; +use crate::providers::openai::OpenAIMessageConverter; +use crate::types::{AIConfig, Message, ModelRequestContext, ToolDefinition}; +use crate::vision_tokens::{ + inline_image_dimensions, ResizedInlineImage, VisionTokenPolicy, UNKNOWN_IMAGE_DIMENSIONS, +}; +use anyhow::Result; +use openbitfun_core_types::errors::{AiProviderError, ErrorCategory}; +use openbitfun_core_types::token_estimate::{ + automatic_max_output_tokens, TokenCounter, INPUT_SAFETY_RESERVE, +}; +use serde_json::{json, Value}; +use std::collections::BTreeMap; + +const OMITTED: &str = "[Earlier image omitted to fit the context window.]"; + +struct Image { + message: usize, + part: usize, + dimensions: Option<(u32, u32)>, + policy: VisionTokenPolicy, + cost: usize, + minimum: usize, + target: usize, +} + +impl Image { + fn new( + policy: VisionTokenPolicy, + message: usize, + part: usize, + inline: Option<(&str, &str)>, + resizable: bool, + ) -> Self { + let dimensions = inline.and_then(|(mime, data)| inline_image_dimensions(mime, data)); + // Opaque URLs/file IDs are never fetched here. Budget an ordinary + // full-size input and retain it intact whenever it is current. + let (w, h) = dimensions.unwrap_or(UNKNOWN_IMAGE_DIMENSIONS); + let cost = policy.estimate(w, h); + let minimum = if dimensions.is_some() && resizable { + policy.min_readable_tokens(w, h) + } else { + cost + }; + Self { + message, + part, + dimensions, + policy, + cost, + minimum, + target: cost, + } + } + + fn preview_note(&self, width: u32, height: u32) -> String { + let (w, h) = self.dimensions.expect("resizable image dimensions"); + format!( + "[Image {} preview {width}x{height} from {w}x{h}.]", + self.part + 1 + ) + } +} + +fn part_policy(policy: VisionTokenPolicy, part: &Value) -> VisionTokenPolicy { + let detail = part["image_url"]["detail"] + .as_str() + .or_else(|| part["detail"].as_str()); + policy.with_detail(detail) +} + +fn part_payload(part: &Value) -> Option<(&str, &str)> { + if let Some(source) = part.get("source") { + if let (Some(mime), Some(data)) = (source["media_type"].as_str(), source["data"].as_str()) { + return Some((mime, data)); + } + } + if let Some(inline) = inline_media(part) { + return Some(inline); + } + let value = part + .get("image_url") + .or_else(|| part.get("source")?.get("url"))?; + let url = value.as_str().or_else(|| value.get("url")?.as_str())?; + let (mime, data) = url.strip_prefix("data:")?.split_once(";base64,")?; + Some((mime, data)) +} + +fn replace_payload(part: &mut Value, image: ResizedInlineImage) { + if let Some(source) = part + .get_mut("source") + .filter(|source| source.get("data").is_some()) + { + source["media_type"] = image.mime_type.into(); + source["data"] = image.data_base64.into(); + } else if let Some(key) = ["inline_data", "inlineData"] + .into_iter() + .find(|k| part.get(k).is_some()) + { + let data = &mut part[key]; + let mime_key = if data.get("mimeType").is_some() { + "mimeType" + } else { + "mime_type" + }; + data[mime_key] = image.mime_type.into(); + data["data"] = image.data_base64.into(); + } else { + let data_url = Value::String(format!( + "data:{};base64,{}", + image.mime_type, image.data_base64 + )); + if let Some(value) = part.get_mut("image_url") { + if value.is_object() { + value["url"] = data_url; + } else { + *value = data_url; + } + } else { + part["source"]["url"] = data_url; + } + } +} + +fn image_budget_error(message: String) -> anyhow::Error { + // Provider context overflows trigger session compaction. This request + // needs a different image or a smaller batch, so return the crop guidance. + AiProviderError::classified(message, ErrorCategory::InvalidRequest).into() +} + +fn resize_preview( + policy: VisionTokenPolicy, + mime: &str, + data: &str, + target: usize, +) -> Result { + policy.resize(mime, data, target).map_err(|error| { + AiProviderError::classified( + format!("Unable to prepare a smaller image preview: {error}. Supply a still image or a crop of the relevant region."), + ErrorCategory::InvalidRequest, + ).into() + }) +} + +fn output_reserve(config: &AIConfig, extra: Option<&Value>) -> usize { + let default = if config.format.eq_ignore_ascii_case("anthropic") { + 32_000 + } else { + automatic_max_output_tokens(config.context_window) + }; + let configured = config.max_tokens.unwrap_or(default) as usize; + // Custom request bodies can raise the wire output cap on compatible gateways. + [ + "/max_tokens", + "/max_completion_tokens", + "/max_output_tokens", + "/generationConfig/maxOutputTokens", + ] + .into_iter() + .filter_map(|path| extra?.pointer(path)?.as_u64()) + .fold(configured, |cap, value| { + cap.max(usize::try_from(value).unwrap_or(usize::MAX)) + }) +} + +/// Admission facts captured from the client selected for *this* send. +pub(in crate::client) struct Budget { + format: Option, + policy: VisionTokenPolicy, + limit: usize, + tools: usize, + schema: usize, + text_floor: usize, + turn_start: Option, +} + +impl Budget { + pub(in crate::client) fn for_request( + config: &AIConfig, + tools: Option<&[ToolDefinition]>, + context: Option<&ModelRequestContext>, + extra: Option<&Value>, + ) -> Self { + let window = config.context_window as usize; + // Leave input space for clients whose entire window is smaller than + // the ordinary compression safety reserve. + let limit = window + .saturating_sub(output_reserve(config, extra)) + .saturating_sub(INPUT_SAFETY_RESERVE.min(window / 3)); + let wire_overhead = |value: &Value| TokenCounter::estimate_tokens(&value.to_string()); + let schema = context + .and_then(|ctx| ctx.output_schema.as_ref()) + .map_or(0, wire_overhead); + let schema = schema + + [ + "/instructions", + "/system", + "/systemInstruction", + "/response_format", + "/text/format", + "/generationConfig/responseSchema", + ] + .into_iter() + .filter_map(|p| extra?.pointer(p)) + .map(wire_overhead) + .sum::(); + let tools = tools + .map_or(0, TokenCounter::estimate_tool_definitions_tokens) + .max( + extra + .and_then(|body| body.get("tools")) + .map_or(0, wire_overhead), + ); + let format = ApiFormat::parse(&config.format).ok(); + let body_selects_model = !crate::client::utils::is_trim_custom_request_body_mode(config) + && matches!( + format, + Some(ApiFormat::OpenAIChat | ApiFormat::OpenAIResponses | ApiFormat::Anthropic) + ); + let model = if body_selects_model { + extra + .and_then(|body| body["model"].as_str()) + .unwrap_or(&config.model) + } else { + &config.model + }; + let mut policy = VisionTokenPolicy::for_model(model); + if matches!( + format, + Some(ApiFormat::Gemini | ApiFormat::GeminiCodeAssist) + ) { + let generation = extra.and_then(|body| { + body.get("generationConfig") + .or_else(|| body.get("generation_config")) + }); + policy = policy.with_gemini_media_resolution(generation.and_then(|config| { + config + .get("mediaResolution") + .or_else(|| config.get("media_resolution"))? + .as_str() + })); + } + Self { + format, + policy, + limit, + tools, + schema, + text_floor: context.map_or(0, |ctx| ctx.minimum_non_image_input_tokens), + turn_start: context.and_then(|ctx| ctx.image_turn_start), + } + } +} + +/// A raw provider message override has no application turn or attachment identity. +/// Keep it intact when it fits; report oversized image overrides before transport. +pub(in crate::client) fn validate_override( + config: &AIConfig, + messages: &[Message], + tools: Option<&[ToolDefinition]>, + context: Option<&ModelRequestContext>, + body: Option<&Value>, +) -> Result { + let Some(body) = body else { return Ok(false) }; + let (key, system_key) = match ApiFormat::parse(&config.format)? { + ApiFormat::OpenAIChat => ("messages", None), + ApiFormat::Anthropic => ("messages", Some("system")), + ApiFormat::OpenAIResponses => ("input", Some("instructions")), + ApiFormat::Gemini | ApiFormat::GeminiCodeAssist => ("contents", Some("systemInstruction")), + }; + let Some(override_messages) = body.get(key) else { + return Ok(false); + }; + if crate::client::utils::is_trim_custom_request_body_mode(config) { + return Ok(false); + } + fn count( + value: &Value, + policy: VisionTokenPolicy, + gemini: bool, + saw_image: &mut bool, + ) -> usize { + let file_image = gemini + && value + .get("fileData") + .or_else(|| value.get("file_data")) + .and_then(|file| file.get("mimeType").or_else(|| file.get("mime_type"))) + .and_then(Value::as_str) + .is_some_and(|mime| mime.starts_with("image/")); + if is_image_part(value) || file_image { + *saw_image = true; + let policy = if gemini { + let resolution = value + .get("mediaResolution") + .or_else(|| value.get("media_resolution")) + .and_then(|setting| setting["level"].as_str()); + policy.with_gemini_media_resolution(resolution) + } else { + part_policy(policy, value) + }; + return Image::new(policy, 0, 0, part_payload(value), false).cost; + } + match value { + Value::String(s) => TokenCounter::estimate_tokens(s) + 1, + Value::Array(items) => items + .iter() + .map(|item| count(item, policy, gemini, saw_image)) + .sum(), + Value::Object(fields) => fields + .iter() + .map(|(k, v)| { + TokenCounter::estimate_tokens(k) + 1 + count(v, policy, gemini, saw_image) + }) + .sum(), + _ => 1, + } + } + let budget = Budget::for_request(config, tools, context, Some(body)); + let mut saw_image = false; + let gemini = matches!( + budget.format, + Some(ApiFormat::Gemini | ApiFormat::GeminiCodeAssist) + ); + let cost = count(override_messages, budget.policy, gemini, &mut saw_image); + if saw_image { + // Responses, Anthropic and Gemini send system messages in a separate + // field, which survives an override of just input/messages/contents. + let preserved_system = if system_key.is_some_and(|key| body.get(key).is_none()) { + messages + .iter() + .filter(|message| message.role == "system") + .map(TokenCounter::estimate_message_tokens) + .sum() + } else { + 0 + }; + if cost + .saturating_add(preserved_system) + .saturating_add(budget.tools + budget.schema + 3) + > budget.limit + { + return Err(image_budget_error("Custom image messages exceed the input budget after reserving output. Use ordinary image attachments to allow automatic resizing.".into())); + } + } + Ok(true) +} + +pub(in crate::client) fn may_contain_images(message: &Message) -> bool { + message + .tool_image_attachments + .as_ref() + .is_some_and(|images| !images.is_empty()) + || (message.role == "user" + && message + .content + .as_deref() + .is_some_and(|s| s.trim_start().starts_with('['))) +} + +#[cfg(test)] +pub(super) fn project( + messages: &mut [Message], + config: &AIConfig, + tools: Option<&[ToolDefinition]>, + context: Option<&ModelRequestContext>, + extra: Option<&Value>, +) -> Result<()> { + apply(messages, Budget::for_request(config, tools, context, extra)) +} + +// Desktop and browser control actions reuse the exact coordinates of their +// screenshots. A deferred call retains its gateway name on the wire. +fn can_resize_tool(message: &Message, history: &[Message]) -> bool { + let mut name = message.name.as_deref(); + if name == Some("CallDeferredTool") { + name = message.tool_call_id.as_deref().and_then(|id| { + history + .iter() + .rev() + .flat_map(|message| message.tool_calls.iter().flatten()) + .find(|call| call.id == id && call.name == "CallDeferredTool") + .and_then(|call| call.arguments["tool_name"].as_str()) + }); + } + !matches!(name, None | Some("ComputerUse" | "ControlHub")) +} + +pub(in crate::client) fn apply(messages: &mut [Message], budget: Budget) -> Result<()> { + let mut users = BTreeMap::new(); + let mut images = Vec::new(); + for (index, message) in messages.iter().enumerate() { + if message.role == "tool" { + if message + .tool_image_attachments + .as_ref() + .is_none_or(Vec::is_empty) + { + continue; + } + let resizable = can_resize_tool(message, &messages[..index]); + for (part, image) in message.tool_image_attachments.iter().flatten().enumerate() { + images.push(Image::new( + budget.policy, + index, + part, + Some((&image.mime_type, &image.data_base64)), + resizable, + )); + } + } else if message.role == "user" { + let Some(content) = message + .content + .as_deref() + .filter(|text| text.trim_start().starts_with('[')) + else { + continue; + }; + let Ok(parts) = serde_json::from_str::>(content) else { + continue; + }; + if matches!( + budget.format, + Some(ApiFormat::OpenAIChat | ApiFormat::OpenAIResponses) + ) && !parts.iter().all(is_content_part) + { + // OpenAI renders unrecognized JSON arrays as literal user text. + continue; + } + let before = images.len(); + for (part, value) in parts + .iter() + .enumerate() + .filter(|(_, value)| is_image_part(value)) + { + images.push(Image::new( + part_policy(budget.policy, value), + index, + part, + part_payload(value), + true, + )); + } + if images.len() > before { + if let Some(format @ (ApiFormat::OpenAIChat | ApiFormat::OpenAIResponses)) = + budget.format + { + if let Some(part) = parts.iter().position(|part| { + !OpenAIMessageConverter::can_render_user_part(part, format) + }) { + return Err(AiProviderError::classified( + format!("Unsupported user content part at index {part} in an OpenAI image message. Use supported text and image parts."), + ErrorCategory::InvalidRequest, + ).into()); + } + } + users.insert(index, parts); + } + } + } + if images.is_empty() { + return Ok(()); + } + + let mut text = 3 + budget.tools; + for (index, message) in messages.iter().enumerate() { + let tokens = match users.get(&index) { + None => TokenCounter::estimate_message_tokens(message), + Some(parts) => { + let text: usize = parts + .iter() + .filter(|p| !is_image_part(p)) + .map(|part| { + part["text"].as_str().map_or_else( + || TokenCounter::estimate_tokens(&part.to_string()), + TokenCounter::estimate_tokens, + ) + }) + .sum(); + TokenCounter::estimate_message_overhead(message) + text + } + }; + text = text.saturating_add(tokens); + } + let text = text.max(budget.text_floor).saturating_add(budget.schema); + let input_limit = budget.limit; + let mut total = images + .iter() + .fold(text, |n, img| n.saturating_add(img.cost)); + if total <= input_limit { + return Ok(()); + } + + let turn_start = budget + .turn_start + .or_else(|| messages.iter().rposition(|message| message.role == "user")) + .unwrap_or(0) + .min(messages.len()); + // Each assistant call batch starts a new model round, even when several + // rounds answer the same user. Older observations were already sent. + let current_start = messages[turn_start..] + .iter() + .rposition(|message| { + message.role == "assistant" + && message + .tool_calls + .as_ref() + .is_some_and(|calls| !calls.is_empty()) + }) + .map_or(turn_start, |index| turn_start + index); + let marker_cost = 4 + TokenCounter::estimate_tokens(OMITTED); + for image in images + .iter_mut() + .take_while(|img| img.message < current_start) + { + image.target = 0; + total = total.saturating_sub(image.cost).saturating_add(marker_cost); + if total <= input_limit { + break; + } + } + if total > input_limit { + // Reserve the readable minimum of each current image first, then share + // the remaining detail across them. Small images keep every pixel. + let mut adjustable = Vec::new(); + let mut required = total; + for (index, img) in images + .iter() + .enumerate() + .filter(|(_, img)| img.target > img.minimum) + { + required = required.saturating_sub(img.cost - img.minimum); + if messages[img.message].role == "tool" { + let (w, h) = img.dimensions.expect("resizable image dimensions"); + required += TokenCounter::estimate_tokens(&img.preview_note(w, h)) + 4; + } + adjustable.push(index); + } + if required > input_limit { + return Err(image_budget_error(format!( + "Cannot fit the images and conversation in the model's context window with the requested output reserved ({required} estimated input tokens needed, {input_limit} available). Crop the relevant area, use fewer images, or shorten the conversation." + ))); + } + let mut spare = input_limit - required; + adjustable.sort_by_key(|&i| images[i].cost - images[i].minimum); + let mut count = adjustable.len(); + for index in adjustable { + let image = &mut images[index]; + let extra = (spare / count).min(image.cost - image.minimum); + image.target = image.minimum + extra; + spare -= extra; + count -= 1; + } + } + + let mut edited_users = std::collections::BTreeSet::new(); + // Remove tool attachments from the back so original positions stay valid. + for image in images.iter().rev().filter(|img| img.target != img.cost) { + let message = &mut messages[image.message]; + if let Some(parts) = users.get_mut(&image.message) { + let part = &mut parts[image.part]; + if image.target == 0 { + *part = json!({"type": "text", "text": OMITTED}); + } else { + let (mime, data) = + part_payload(part).expect("resizable user image has inline data"); + replace_payload( + part, + resize_preview(image.policy, mime, data, image.target)?, + ); + } + edited_users.insert(image.message); + } else { + let attachments = message + .tool_image_attachments + .as_mut() + .expect("tool image group"); + let note = if image.target == 0 { + attachments.remove(image.part); + OMITTED.to_owned() + } else { + let attachment = &mut attachments[image.part]; + let preview = resize_preview( + image.policy, + &attachment.mime_type, + &attachment.data_base64, + image.target, + )?; + let note = image.preview_note(preview.width, preview.height); + attachment.mime_type = preview.mime_type; + attachment.data_base64 = preview.data_base64; + note + }; + if attachments.is_empty() { + message.tool_image_attachments = None; + } + let content = message.content.get_or_insert_with(String::new); + content.push('\n'); + content.push_str(¬e); + } + } + for index in edited_users { + messages[index].content = Some(serde_json::to_string(&users[&index])?); + } + Ok(()) +} diff --git a/src/crates/adapters/ai-adapters/src/client/image_budget/context_tests.rs b/src/crates/adapters/ai-adapters/src/client/image_budget/context_tests.rs new file mode 100644 index 0000000000..d66705cd1f --- /dev/null +++ b/src/crates/adapters/ai-adapters/src/client/image_budget/context_tests.rs @@ -0,0 +1,579 @@ +use super::context::project; +use crate::types::{AIConfig, Message, ModelRequestContext, ToolImageAttachment}; +use crate::vision_tokens::{inline_image_dimensions, VisionTokenPolicy}; +use base64::{engine::general_purpose::STANDARD, Engine}; +use openbitfun_core_types::token_estimate::INPUT_SAFETY_RESERVE; +use serde_json::{json, Value}; +use std::io::Cursor; + +fn config() -> AIConfig { + serde_json::from_value(json!({ + "name": "vision", "base_url": "http://localhost", "request_url": "http://localhost", + "api_key": "synthetic", "model": "test-vl", "format": "openai", + "context_window": 262144, "max_tokens": 16384, + "inline_think_in_text": false, "skip_ssl_verify": false + })) + .unwrap() +} + +fn with_remaining_input( + config: &AIConfig, + turn_start: usize, + remaining: usize, +) -> ModelRequestContext { + ModelRequestContext { + image_turn_start: Some(turn_start), + minimum_non_image_input_tokens: config.context_window as usize + - config.max_tokens.unwrap() as usize + - INPUT_SAFETY_RESERVE + - remaining, + ..Default::default() + } +} + +fn png(width: u32, height: u32) -> String { + encode_png(image::GrayImage::new(width, height)) +} + +fn encode_png(pixels: image::GrayImage) -> String { + let mut bytes = Cursor::new(Vec::new()); + image::DynamicImage::ImageLuma8(pixels) + .write_to(&mut bytes, image::ImageFormat::Png) + .unwrap(); + STANDARD.encode(bytes.into_inner()) +} + +fn screenshot_with_small_text() -> String { + let mut page = image::GrayImage::from_pixel(2048, 2048, image::Luma([255])); + // Draw "Hi" in 15-pixel-high letters in the middle of the screenshot. + for (y, row) in ["# # #", "# # ", "### #", "# # #", "# # #"] + .iter() + .enumerate() + { + for (x, _) in row.bytes().enumerate().filter(|(_, c)| *c == b'#') { + for dy in 0..3 { + for dx in 0..3 { + page.put_pixel( + 1024 + 3 * x as u32 + dx, + 1024 + 3 * y as u32 + dy, + image::Luma([0]), + ); + } + } + } + } + encode_png(page) +} + +fn uploaded(data: &str) -> Message { + Message::user( + json!([ + {"type": "text", "text": "Inspect this page."}, + {"type": "image_url", "image_url": {"url": format!("data:image/png;base64,{data}")}} + ]) + .to_string(), + ) +} + +fn tool_result(name: &str, data: &str) -> Message { + let mut message = Message::user("Screenshot available.".into()); + message.role = "tool".into(); + message.name = Some(name.into()); + message.tool_call_id = Some("capture".into()); + message.tool_image_attachments = Some(vec![ToolImageAttachment { + mime_type: "image/png".into(), + data_base64: data.into(), + }]); + message +} + +fn user_image_size(message: &Message) -> Option<(u32, u32)> { + let parts: Vec = serde_json::from_str(message.content.as_ref()?).ok()?; + let url = parts + .iter() + .find_map(|part| part["image_url"]["url"].as_str())?; + inline_image_dimensions("image/png", url.strip_prefix("data:image/png;base64,")?) +} + +#[test] +fn openai_preserves_literal_json_and_validates_explicit_image_parts() { + use crate::providers::openai::OpenAIMessageConverter; + let url = format!("data:image/png;base64,{}", png(4, 4)); + let image = json!({"type": "input_image", "image_url": url}); + for format in ["openai", "responses"] { + let mut config = config(); + config.format = format.into(); + let mut mixed = [Message::user( + json!([image, {"type":"unsupported"}]).to_string(), + )]; + let original = mixed[0].content.clone(); + project(&mut mixed, &config, None, None, None).unwrap(); + assert_eq!(mixed[0].content, original); + + let mut unsupported = [Message::user( + json!([image, {"type":"audio", "data":"audio"}]).to_string(), + )]; + let error = project(&mut unsupported, &config, None, None, None).unwrap_err(); + assert!(error + .to_string() + .contains("Unsupported user content part at index 1")); + assert!(!error.to_string().contains(&url)); + + let mut supported = vec![Message::user( + json!([image, {"type": "input_text", "text":"Inspect"}]).to_string(), + )]; + project(&mut supported, &config, None, None, None).unwrap(); + if format == "openai" { + let wire = OpenAIMessageConverter::convert_messages(supported); + assert_eq!(wire[0]["content"][0]["image_url"]["url"], url); + assert_eq!(wire[0]["content"][1]["text"], "Inspect"); + } else { + let (_, wire) = OpenAIMessageConverter::convert_messages_to_responses_input(supported); + assert_eq!(wire[0]["content"][0]["image_url"], url); + assert_eq!(wire[0]["content"][1]["text"], "Inspect"); + } + } +} + +#[test] +fn omit_history_before_resizing_the_current_screenshot_and_preserve_originals() { + let config = config(); + let data = screenshot_with_small_text(); + let original = vec![uploaded(&png(1536, 1536)), tool_result("view_image", &data)]; + let mut roomy = original.clone(); + project(&mut roomy, &config, None, None, None).unwrap(); + assert_eq!( + serde_json::to_value(roomy).unwrap(), + serde_json::to_value(&original).unwrap() + ); + + let mut limited = original.clone(); + let context = with_remaining_input( + &config, + 1, + VisionTokenPolicy::for_model("test-vl").estimate(2048, 2048) + 1000, + ); + project(&mut limited, &config, None, Some(&context), None).unwrap(); + assert!(user_image_size(&limited[0]).is_none()); + assert!(limited[0] + .content + .as_deref() + .unwrap() + .contains("Inspect this page.")); + assert_eq!(limited[1].tool_call_id.as_deref(), Some("capture")); + assert_eq!( + limited[1].tool_image_attachments.as_ref().unwrap()[0].data_base64, + data + ); + let mut tight = original.clone(); + let remaining = 1200; + let context = with_remaining_input(&config, 1, remaining); + project(&mut tight, &config, None, Some(&context), None).unwrap(); + assert!(user_image_size(&tight[0]).is_none()); + let preview = &tight[1].tool_image_attachments.as_ref().unwrap()[0]; + let (width, height) = + inline_image_dimensions(&preview.mime_type, &preview.data_base64).unwrap(); + assert_eq!(width, height); + assert!((512..2048).contains(&width)); + assert!(VisionTokenPolicy::for_model(&config.model).estimate(width, height) <= remaining); + assert_eq!(tight[1].tool_call_id.as_deref(), Some("capture")); + + let decoded = image::load_from_memory(&STANDARD.decode(&preview.data_base64).unwrap()) + .unwrap() + .into_luma8(); + let center = image::imageops::crop_imm(&decoded, width / 2, height / 2, 10, 10).to_image(); + assert!( + center.pixels().any(|p| p[0] < 96), + "the preview retains the dark letters" + ); + assert!( + center.pixels().any(|p| p[0] > 230), + "the preview retains the white background" + ); + assert_eq!(user_image_size(&original[0]), Some((1536, 1536))); + assert_eq!( + original[1].tool_image_attachments.as_ref().unwrap()[0].data_base64, + data + ); +} + +#[test] +fn earlier_tool_round_yields_before_the_latest_parallel_results() { + let config = config(); + let data = png(1024, 1024); + let call = |id: &str| crate::ToolCall { + id: id.into(), + name: "view_image".into(), + arguments: json!({}), + raw_arguments: None, + }; + let result = |id: &str| { + let mut result = tool_result("view_image", &data); + result.tool_call_id = Some(id.into()); + result + }; + let mut messages = vec![ + Message::user("Compare the screenshots.".into()), + Message::assistant_with_tools(vec![call("old")]), + result("old"), + Message::assistant_with_tools(vec![call("new-a"), call("new-b")]), + result("new-a"), + result("new-b"), + ]; + let pair = 2 * VisionTokenPolicy::for_model(&config.model).estimate(1024, 1024); + let context = with_remaining_input(&config, 0, pair + 100); + project(&mut messages, &config, None, Some(&context), None).unwrap(); + assert!(messages[2].tool_image_attachments.is_none()); + assert_eq!(messages[2].tool_call_id.as_deref(), Some("old")); + for message in &messages[4..] { + assert_eq!( + message.tool_image_attachments.as_ref().unwrap()[0].data_base64, + data + ); + } +} + +#[test] +fn text_only_tool_round_can_omit_the_upload_and_last_rounds_screenshot() { + let config = config(); + let data = png(1024, 1024); + let batch = |id: &str, tool: &str| { + Message::assistant_with_tools(vec![crate::ToolCall { + id: id.into(), + name: tool.into(), + arguments: json!({}), + raw_arguments: None, + }]) + }; + let mut text_result = Message::user("Done".into()); + text_result.role = "tool".into(); + text_result.name = Some("ExecCommand".into()); + text_result.tool_call_id = Some("exec".into()); + let mut messages = vec![ + uploaded(&data), + batch("capture", "view_image"), + tool_result("view_image", &data), + batch("exec", "ExecCommand"), + text_result, + ]; + // Both earlier images have already been seen. This round fits placeholders only. + let context = with_remaining_input(&config, 0, 100); + project(&mut messages, &config, None, Some(&context), None).unwrap(); + assert!(user_image_size(&messages[0]).is_none()); + assert!(messages[2].tool_image_attachments.is_none()); + assert_eq!(messages[2].tool_call_id.as_deref(), Some("capture")); + assert_eq!(messages[4].content.as_deref(), Some("Done")); +} + +#[test] +fn openai_low_detail_fits_at_the_selected_models_base_cost() { + let mut config = config(); + config.model = "gpt-4o".into(); + let data = png(1024, 1024); + let url = format!("data:image/png;base64,{data}"); + let context = with_remaining_input(&config, 0, 85); + for part in [ + json!({"type":"image_url","image_url":{"url": url,"detail":"low"}}), + json!({"type":"input_image","image_url":url,"detail":"low"}), + ] { + let content = json!([part]).to_string(); + let mut messages = [Message::user(content.clone())]; + project(&mut messages, &config, None, Some(&context), None).unwrap(); + assert_eq!(messages[0].content.as_deref(), Some(content.as_str())); + } + let extra = json!({"model":"gpt-4o"}); + config.model = "test-vl".into(); + let mut overridden = [Message::user( + json!([{"type":"image_url","image_url":{"url":url,"detail":"low"}}]).to_string(), + )]; + project(&mut overridden, &config, None, Some(&context), Some(&extra)).unwrap(); + config.custom_request_body_mode = Some("trim".into()); + assert!(project(&mut overridden, &config, None, Some(&context), Some(&extra)).is_err()); + config.model = "gpt-4o".into(); + let mut auto = [uploaded(&data)]; + let error = project(&mut auto, &config, None, Some(&context), None).unwrap_err(); + assert!(error.to_string().contains("Crop the relevant area")); + assert_eq!( + error + .downcast_ref::() + .unwrap() + .category, + openbitfun_core_types::ErrorCategory::InvalidRequest + ); +} + +#[test] +fn gemini_uses_global_resolution_for_projected_images_and_override_parts_on_the_wire() { + let mut config = config(); + config.model = "gemini-3.6-flash".into(); + config.format = "gemini".into(); + let context = with_remaining_input(&config, 0, 600); + let data = png(32, 32); + let messages = vec![Message::user( + json!([{ + "inlineData": {"mimeType": "image/png", "data": data}, + // Normal message conversion drops this field. + "mediaResolution": {"level": "MEDIA_RESOLUTION_LOW"} + }]) + .to_string(), + )]; + assert!(project(&mut messages.clone(), &config, None, Some(&context), None).is_err()); + let global = json!({"generationConfig": {"mediaResolution": "MEDIA_RESOLUTION_MEDIUM"}}); + project( + &mut messages.clone(), + &config, + None, + Some(&context), + Some(&global), + ) + .unwrap(); + + // A raw contents override goes to the provider as written. 1600 input + // tokens allow the default resolution but not an ultra-high image part. + config.context_window = 6000; + config.max_tokens = Some(2400); + let mut raw = json!({ + "generationConfig": {"mediaResolution": "MEDIA_RESOLUTION_MEDIUM"}, + "contents": [{"role":"user", "parts": [{ + "fileData": {"fileUri":"gs://test/screenshot.png", "mimeType":"image/png"}, + "mediaResolution": {"level":"MEDIA_RESOLUTION_ULTRA_HIGH"} + }]}] + }); + assert!(super::context::validate_override(&config, &[], None, None, Some(&raw)).is_err()); + raw["contents"][0]["parts"][0] + .as_object_mut() + .unwrap() + .remove("mediaResolution"); + assert!(super::context::validate_override(&config, &[], None, None, Some(&raw)).unwrap()); +} + +#[test] +fn current_upload_and_tool_share_remaining_visual_tokens() { + let config = config(); + let data = png(1920, 1080); + let mut messages = vec![uploaded(&data), tool_result("view_image", &data)]; + let remaining = 3000; + let context = with_remaining_input(&config, 0, remaining); + project(&mut messages, &config, None, Some(&context), None).unwrap(); + let user = user_image_size(&messages[0]).expect("current user image kept"); + let tool_image = &messages[1] + .tool_image_attachments + .as_ref() + .expect("current tool image kept")[0]; + let tool = inline_image_dimensions(&tool_image.mime_type, &tool_image.data_base64).unwrap(); + assert!(user.0 >= 512 && tool.0 >= 512); + assert!( + VisionTokenPolicy::for_model("test-vl").estimate(user.0, user.1) + + VisionTokenPolicy::for_model("test-vl").estimate(tool.0, tool.1) + <= remaining + ); + assert_eq!(messages[1].tool_call_id.as_deref(), Some("capture")); +} + +#[test] +fn output_reserve_messages_and_tool_definitions_share_the_input_window() { + let config = config(); + let data = png(640, 640); + let mut messages = vec![uploaded(&data)]; + let context = with_remaining_input(&config, 0, 1); + assert!(project(&mut messages, &config, None, Some(&context), None).is_err()); + + let mut small = config.clone(); + small.context_window = 18000; + small.max_tokens = Some(4000); + let mut messages = vec![ + Message::user("review these details ".repeat(10000)), + uploaded(&data), + ]; + assert!(project(&mut messages, &small, None, None, None).is_err()); + + let tools = [crate::types::ToolDefinition { + name: "lookup".into(), + description: "Look up one of the available entries".into(), + parameters: json!({"type":"string", "enum": (0..5000).map(|index| format!("entry-{index}")).collect::>() }), + }]; + let mut image_only = [uploaded(&data)]; + project(&mut image_only, &small, None, None, None).unwrap(); + assert!(project(&mut image_only, &small, Some(&tools), None, None).is_err()); +} + +#[test] +fn current_computer_use_frame_keeps_its_coordinate_system() { + let config = config(); + let data = png(1920, 1080); + let mut messages = vec![tool_result("ComputerUse", &data)]; + project(&mut messages, &config, None, None, None).unwrap(); + let original = &messages[0].tool_image_attachments.as_ref().unwrap()[0]; + assert_eq!(original.data_base64, data); + assert_eq!( + inline_image_dimensions(&original.mime_type, &original.data_base64), + Some((1920, 1080)) + ); + let context = with_remaining_input(&config, 0, 1200); + assert!(project(&mut messages, &config, None, Some(&context), None).is_err()); + assert_eq!( + messages[0].tool_image_attachments.as_ref().unwrap()[0].data_base64, + data + ); +} + +#[test] +fn resized_native_image_parts_survive_anthropic_and_gemini_serialization() { + use crate::providers::{ + anthropic::message_converter::AnthropicMessageConverter, + gemini::message_converter::GeminiMessageConverter, + }; + + let data = png(1200, 900); + let remaining = 1000; + for (format, part) in [ + ( + "anthropic", + json!({"type":"image", "source":{"type":"base64","media_type":"image/png","data":data}}), + ), + ( + "gemini", + json!({"inline_data":{"mime_type":"image/png","data":data}}), + ), + ( + "gemini", + json!({"inlineData":{"mimeType":"image/png","data":data}}), + ), + ] { + let mut config = config(); + config.format = format.into(); + let context = with_remaining_input(&config, 0, remaining); + let mut messages = vec![Message::user(json!([part]).to_string())]; + project(&mut messages, &config, None, Some(&context), None).unwrap(); + let (encoded, mime_key) = if format == "anthropic" { + let (_, wire) = AnthropicMessageConverter::convert_messages(messages); + (wire[0]["content"][0]["source"].clone(), "media_type") + } else { + let (_, wire) = GeminiMessageConverter::convert_messages(messages, &config.model); + (wire[0]["parts"][0]["inlineData"].clone(), "mimeType") + }; + let mime = encoded[mime_key].as_str().unwrap(); + assert_eq!(mime, "image/png"); + let (w, h) = inline_image_dimensions(mime, encoded["data"].as_str().unwrap()).unwrap(); + assert!(w >= 512 && w < 1200); + assert!(VisionTokenPolicy::for_model("test-vl").estimate(w, h) <= remaining); + } +} + +#[tokio::test] +async fn selected_model_window_controls_pixels_on_the_wire() { + use axum::{routing::post, Json, Router}; + use std::sync::{Arc, Mutex}; + + let observed = Arc::new(Mutex::new(Vec::new())); + let received = observed.clone(); + let app = Router::new().route("/chat/completions", post(move |Json(body): Json| { + let received = received.clone(); + async move { + let data = body["messages"][0]["content"].as_array().unwrap().iter() + .find_map(|part| part["image_url"]["url"].as_str()).unwrap() + .strip_prefix("data:image/png;base64,").unwrap(); + let dimensions = inline_image_dimensions("image/png", data).unwrap(); + received.lock().unwrap().push(dimensions); + let chunk = json!({"id":"test","object":"chat.completion.chunk","created":1,"model":"test-vl", + "choices":[{"index":0,"delta":{"content":"ok"},"finish_reason":"stop"}]}); + ([("content-type", "text/event-stream")], format!("data: {chunk}\n\ndata: [DONE]\n\n")) + } + })); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let url = format!("http://{}/chat/completions", listener.local_addr().unwrap()); + let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + let mut roomy = config(); + roomy.base_url = url.clone(); + roomy.request_url = url; + let mut limited = roomy.clone(); + limited.context_window = 128_000; + let context = with_remaining_input(&limited, 0, 1500); + let impossible = with_remaining_input(&limited, 0, 1); + let messages = vec![uploaded(&png(1920, 1080))]; + for selected in [roomy, limited.clone()] { + crate::AIClient::new(selected) + .send_message_once_with_trace_and_request_context( + messages.clone(), + None, + Some(context.clone()), + None, + ) + .await + .unwrap(); + } + let result = crate::AIClient::new(limited) + .send_message_once_with_trace_and_request_context(messages, None, Some(impossible), None) + .await; + assert!(result.is_err()); + server.abort(); + let requests = observed.lock().unwrap(); + assert_eq!( + requests.len(), + 2, + "the infeasible third request must fail before HTTP" + ); + assert_eq!(requests[0], (1920, 1080)); + let (width, height) = requests[1]; + assert!( + width >= 512 && VisionTokenPolicy::for_model("test-vl").estimate(width, height) <= 1500 + ); +} + +#[test] +fn custom_image_payload_must_fit_the_actual_output_reserve() { + let mut config = config(); + config.context_window = 32_000; + config.max_tokens = Some(8_000); + let native: Value = + serde_json::from_str(uploaded(&png(1024, 1024)).content.as_deref().unwrap()).unwrap(); + let mut body = json!({"messages": [{"role": "user", "content": native}]}); + super::context::validate_override(&config, &[], None, None, Some(&body)).unwrap(); + body["max_completion_tokens"] = json!(21_999); + let error = + super::context::validate_override(&config, &[], None, None, Some(&body)).unwrap_err(); + assert_eq!( + error + .downcast_ref::() + .unwrap() + .category, + openbitfun_core_types::ErrorCategory::InvalidRequest + ); + config.format = "responses".into(); + let native = body["messages"].take(); + let responses = json!({"input": native, "max_output_tokens": 20_500}); + assert!(super::context::validate_override(&config, &[], None, None, Some(&responses)).unwrap()); + let system = Message::system("long instruction ".repeat(500)); + assert!( + super::context::validate_override(&config, &[system], None, None, Some(&responses)) + .is_err() + ); + config.format = "openai".into(); + body["messages"] = json!([{"role":"user","content":"hello"}]); + assert!(super::context::validate_override(&config, &[], None, None, Some(&body)).is_ok()); +} + +#[test] +fn deferred_tool_preserves_only_coordinate_bound_frames() { + let config = config(); + let pixels = png(1800, 900); + let budget = with_remaining_input(&config, 0, 1200); + for (name, should_fit) in [ + ("ComputerUse", false), + ("view_image", true), + ("DocumentPreview", true), + ] { + let call = crate::ToolCall { + id: "capture".into(), + name: "CallDeferredTool".into(), + arguments: json!({"tool_name":name}), + raw_arguments: None, + }; + let mut messages = vec![ + Message::assistant_with_tools(vec![call]), + tool_result("CallDeferredTool", &pixels), + ]; + let result = project(&mut messages, &config, None, Some(&budget), None); + assert_eq!(result.is_ok(), should_fit, "{name}: {result:?}"); + } +} diff --git a/src/crates/adapters/ai-adapters/src/lib.rs b/src/crates/adapters/ai-adapters/src/lib.rs index c7e6c273ec..62e9469792 100644 --- a/src/crates/adapters/ai-adapters/src/lib.rs +++ b/src/crates/adapters/ai-adapters/src/lib.rs @@ -16,6 +16,8 @@ pub mod subscription_auth; pub mod tool_call_accumulator; pub mod trace; pub mod types; +#[cfg(feature = "vision-input")] +pub mod vision_tokens; pub use client::{AIClient, StreamOptions, StreamResponse}; pub use model_selector::{ diff --git a/src/crates/adapters/ai-adapters/src/providers/gemini/message_converter.rs b/src/crates/adapters/ai-adapters/src/providers/gemini/message_converter.rs index 4803645e84..5c7bc97e2d 100644 --- a/src/crates/adapters/ai-adapters/src/providers/gemini/message_converter.rs +++ b/src/crates/adapters/ai-adapters/src/providers/gemini/message_converter.rs @@ -385,17 +385,52 @@ impl GeminiMessageConverter { let mut parts = Vec::new(); if let Some(items) = parsed.as_array() { + // Untyped {text: ...} also occurs in ordinary user-supplied JSON. + // Interpret it as a native Gemini part only in a recognized part list. + let user_parts = !is_model_role + && items.iter().any(|item| { + item.get("inline_data").is_some() + || item.get("inlineData").is_some() + || matches!( + item["type"].as_str(), + Some( + "text" + | "input_text" + | "output_text" + | "image" + | "image_url" + | "input_image" + ) + ) + }); for item in items { let item_type = item.get("type").and_then(Value::as_str); match item_type { - Some("text") | Some("input_text") | Some("output_text") => { + Some("text" | "input_text" | "output_text") => { if let Some(text) = item.get("text").and_then(Value::as_str) { if !text.is_empty() { parts.push(json!({ "text": text })); } } } - Some("image_url") if !is_model_role => { + None if user_parts => { + if let Some(inline) = + item.get("inline_data").or_else(|| item.get("inlineData")) + { + let mime = inline + .get("mime_type") + .or_else(|| inline.get("mimeType")) + .and_then(Value::as_str); + if let (Some(mime), Some(data)) = (mime, inline["data"].as_str()) { + parts.push(json!({"inlineData": {"mimeType": mime, "data": data}})); + } + } else if let Some(text) = + item["text"].as_str().filter(|text| !text.is_empty()) + { + parts.push(json!({"text": text})); + } + } + Some("image_url" | "input_image") if !is_model_role => { if let Some(url) = item.get("image_url").and_then(|value| { value .get("url") @@ -885,6 +920,35 @@ mod tests { ); } + #[test] + fn native_user_images_stay_in_order_with_text_on_the_gemini_wire() { + let png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a1j8AAAAASUVORK5CYII="; + let message = Message::user( + json!([ + {"inline_data": {"mime_type": "image/png", "data": png}}, + {"text": "Compare the two images"}, + {"inlineData": {"mimeType": "image/png", "data": png}}, + {"text": "Report the differences"} + ]) + .to_string(), + ); + let (_, contents) = GeminiMessageConverter::convert_messages(vec![message], "gemini"); + assert_eq!( + contents, + vec![json!({"role": "user", "parts": [ + {"inlineData": {"mimeType": "image/png", "data": png}}, + {"text": "Compare the two images"}, + {"inlineData": {"mimeType": "image/png", "data": png}}, + {"text": "Report the differences"} + ]})] + ); + + let literal = r#"[{"text":"example JSON"}]"#; + let (_, contents) = + GeminiMessageConverter::convert_messages(vec![Message::user(literal.into())], "gemini"); + assert_eq!(contents[0]["parts"], json!([{"text": literal}])); + } + #[test] fn converts_data_url_images_to_inline_data() { let messages = vec![Message { diff --git a/src/crates/adapters/ai-adapters/src/providers/openai/message_converter.rs b/src/crates/adapters/ai-adapters/src/providers/openai/message_converter.rs index a0b6e93b54..1d57f679c3 100644 --- a/src/crates/adapters/ai-adapters/src/providers/openai/message_converter.rs +++ b/src/crates/adapters/ai-adapters/src/providers/openai/message_converter.rs @@ -1,5 +1,6 @@ //! OpenAI message format converter +use crate::client::format::ApiFormat; use crate::stream::types::responses::OPENAI_RESPONSES_REPLAY_PROTOCOL; use crate::types::{Message, ToolDefinition}; use log::{error, warn}; @@ -9,6 +10,76 @@ use std::collections::{HashMap, HashSet}; pub struct OpenAIMessageConverter; +enum ContentPart<'a> { + Text(&'a str), + ImageUrl { + url: &'a str, + detail: Option<&'a str>, + }, + ImageFile { + id: &'a str, + detail: Option<&'a str>, + }, +} + +impl<'a> ContentPart<'a> { + fn parse(part: &'a Value, role: &str, format: ApiFormat) -> Option { + match part["type"].as_str()? { + "text" | "input_text" | "output_text" => Some(Self::Text(part["text"].as_str()?)), + "image_url" | "input_image" + if role == "user" + || (format == ApiFormat::OpenAIResponses && role != "assistant") => + { + let image = &part["image_url"]; + let detail = image["detail"].as_str().or_else(|| part["detail"].as_str()); + if let Some(url) = image["url"].as_str().or_else(|| image.as_str()) { + return Some(Self::ImageUrl { url, detail }); + } + if format == ApiFormat::OpenAIResponses && part["type"] == "input_image" { + return Some(Self::ImageFile { + id: part["file_id"].as_str()?, + detail, + }); + } + None + } + _ => None, + } + } + + fn wire(self, role: &str, format: ApiFormat) -> Value { + let responses = format == ApiFormat::OpenAIResponses; + let (mut item, detail) = match self { + Self::Text(text) => { + let kind = if responses { + OpenAIMessageConverter::responses_text_item_type(role) + } else { + "text" + }; + return json!({"type": kind, "text": text}); + } + Self::ImageUrl { url, detail } if responses => { + (json!({"type": "input_image", "image_url": url}), detail) + } + Self::ImageUrl { url, detail } => ( + json!({"type": "image_url", "image_url": {"url": url}}), + detail, + ), + Self::ImageFile { id, detail } => { + (json!({"type": "input_image", "file_id": id}), detail) + } + }; + if let Some(detail) = detail { + if responses { + item["detail"] = json!(detail); + } else { + item["image_url"]["detail"] = json!(detail); + } + } + item + } +} + impl OpenAIMessageConverter { pub fn convert_messages_to_responses_input( messages: Vec, @@ -328,12 +399,14 @@ impl OpenAIMessageConverter { } Some( - Self::parse_responses_content_parts(role, content).unwrap_or_else(|| { - vec![json!({ - "type": text_item_type, - "text": content, - })] - }), + Self::parse_content_parts(role, content, ApiFormat::OpenAIResponses).unwrap_or_else( + || { + vec![json!({ + "type": text_item_type, + "text": content, + })] + }, + ), ) } @@ -345,93 +418,24 @@ impl OpenAIMessageConverter { } } - fn parse_responses_content_parts(role: &str, content: &str) -> Option> { - let items = serde_json::from_str::(content) - .ok()? - .as_array()? - .clone(); - if items.is_empty() { - return None; - } - let text_item_type = Self::responses_text_item_type(role); - let mut content_items = Vec::with_capacity(items.len()); - - for item in items { - let item_type = item.get("type").and_then(Value::as_str)?; - match item_type { - "text" | "input_text" | "output_text" => { - let text = item.get("text").and_then(Value::as_str)?; - content_items.push(json!({ - "type": text_item_type, - "text": text, - })); - } - "image_url" if role != "assistant" => { - let image_url = Self::extract_image_url_value(item.get("image_url")?)?; - content_items.push(json!({ - "type": "input_image", - "image_url": image_url, - })); - } - _ => return None, - } - } - - Some(content_items) + #[cfg(feature = "vision-input")] + pub(crate) fn can_render_user_part(part: &Value, format: ApiFormat) -> bool { + ContentPart::parse(part, "user", format).is_some() } - fn parse_chat_completions_content_parts(role: &str, content: &str) -> Option> { - // Tool text is opaque, even when it happens to contain JSON content parts. - // Keeping it a string also works with providers that reject text arrays. + fn parse_content_parts(role: &str, content: &str, format: ApiFormat) -> Option> { + // Tool text is opaque, including JSON that happens to resemble content parts. if role == "tool" { return None; } - let items = serde_json::from_str::(content) - .ok()? - .as_array()? - .clone(); - if items.is_empty() { + let parts: Vec = serde_json::from_str(content).ok()?; + if parts.is_empty() { return None; } - let mut content_items = Vec::with_capacity(items.len()); - - for item in items { - let item_type = item.get("type").and_then(Value::as_str)?; - match item_type { - "text" | "input_text" | "output_text" => { - let text = item.get("text").and_then(Value::as_str)?; - content_items.push(json!({ - "type": "text", - "text": text, - })); - } - "image_url" if role == "user" => { - let image_url_value = item.get("image_url")?; - let image_url = Self::extract_image_url_value(image_url_value)?; - let mut content_item = json!({ - "type": "image_url", - "image_url": { - "url": image_url, - } - }); - if let Some(detail) = image_url_value.get("detail").and_then(Value::as_str) { - content_item["image_url"]["detail"] = Value::String(detail.to_string()); - } - content_items.push(content_item); - } - _ => return None, - } - } - - Some(content_items) - } - - fn extract_image_url_value(value: &Value) -> Option { - value - .get("url") - .and_then(Value::as_str) - .or_else(|| value.as_str()) - .map(ToString::to_string) + parts + .iter() + .map(|part| Some(ContentPart::parse(part, role, format)?.wire(role, format))) + .collect() } fn convert_single_message(mut msg: Message) -> Value { @@ -466,7 +470,7 @@ impl OpenAIMessageConverter { } } else { if let Some(content_parts) = - Self::parse_chat_completions_content_parts(&msg.role, &content) + Self::parse_content_parts(&msg.role, &content, ApiFormat::OpenAIChat) { openai_msg["content"] = Value::Array(content_parts); } else { diff --git a/src/crates/adapters/ai-adapters/src/providers/openai/responses.rs b/src/crates/adapters/ai-adapters/src/providers/openai/responses.rs index bb2eb66b02..700d260e26 100644 --- a/src/crates/adapters/ai-adapters/src/providers/openai/responses.rs +++ b/src/crates/adapters/ai-adapters/src/providers/openai/responses.rs @@ -535,6 +535,7 @@ mod tests { conversation_scope: None, prompt_cache_route_key: Some("lineage-1".to_string()), output_schema: None, + ..Default::default() }; let request_body = build_request_body_with_context( &client, @@ -558,6 +559,7 @@ mod tests { conversation_scope: None, prompt_cache_route_key: None, output_schema: Some(schema.clone()), + ..Default::default() }; let request_body = build_request_body_with_context( &test_client(), diff --git a/src/crates/adapters/ai-adapters/src/providers/shared.rs b/src/crates/adapters/ai-adapters/src/providers/shared.rs index 173543ee5d..87e161f7f4 100644 --- a/src/crates/adapters/ai-adapters/src/providers/shared.rs +++ b/src/crates/adapters/ai-adapters/src/providers/shared.rs @@ -638,6 +638,7 @@ mod tests { conversation_scope: None, prompt_cache_route_key: Some("runtime-lineage".into()), output_schema: Some(serde_json::json!({"type": "object"})), + ..Default::default() }), ] { assert_eq!( @@ -696,6 +697,7 @@ mod tests { conversation_scope: None, prompt_cache_route_key: Some(" ".into()), output_schema: Some(serde_json::json!({"type":"object"})), + ..Default::default() }), Some(ModelRequestContext { conversation_scope: None, @@ -864,6 +866,7 @@ mod tests { conversation_scope: None, prompt_cache_route_key: Some(" ".into()), output_schema: Some(serde_json::json!({"type": "object"})), + ..Default::default() }), ] { let schema = initial diff --git a/src/crates/adapters/ai-adapters/src/vision_tokens.rs b/src/crates/adapters/ai-adapters/src/vision_tokens.rs new file mode 100644 index 0000000000..3057db4e73 --- /dev/null +++ b/src/crates/adapters/ai-adapters/src/vision_tokens.rs @@ -0,0 +1,482 @@ +//! Geometry-based estimates and resizing for inline vision inputs. + +use anyhow::{anyhow, ensure, Context, Result}; +use base64::{engine::general_purpose::STANDARD, Engine}; +use image::codecs::{gif::GifDecoder, jpeg::JpegEncoder, png::PngDecoder, webp::WebPDecoder}; +use image::{ + imageops::FilterType, AnimationDecoder, DynamicImage, GenericImageView, ImageDecoder, + ImageFormat, ImageReader, Limits, +}; +use std::io::Cursor; + +mod openai_patches; +use openai_patches::OpenAiPatches; + +/// Size reserved for path-only history, opaque URLs or unreadable headers. +pub const UNKNOWN_IMAGE_DIMENSIONS: (u32, u32) = (2048, 2048); + +fn grid(width: u32, height: u32, edge: u32) -> u64 { + u64::from(width.div_ceil(edge)) * u64::from(height.div_ceil(edge)) +} + +/// Model-neutral estimate used before the runtime selects a provider. +pub fn estimate_image_tokens(width: u32, height: u32) -> usize { + usize::try_from(50 + 200 * grid(width, height, 512)).unwrap_or(usize::MAX) +} + +/// Estimates for known vision processors. A custom model ID retains the +/// model-neutral tile estimate when its processor is unknown. +#[derive(Clone, Copy)] +pub(crate) enum VisionTokenPolicy { + Generic, + OpenAiTiles { base: u64, tile: u64 }, + OpenAiPatches(OpenAiPatches), + Fixed(u64), + Gemini(u64), + Claude { max_edge: u32, max_tokens: u64 }, + Patches { edge: u32, max: u64, percent: u64 }, +} + +impl VisionTokenPolicy { + pub(crate) fn for_model(model: &str) -> Self { + let name = model + .rsplit('/') + .next() + .unwrap_or(model) + .to_ascii_lowercase(); + // OpenAI snapshot names end in a date, e.g. gpt-4o-2024-08-06. + let family = name.split_once("-20").map_or(name.as_str(), |(id, _)| id); + if let Some(patches) = OpenAiPatches::for_model(family) { + return Self::OpenAiPatches(patches); + } + match family { + // https://developers.openai.com/api/docs/guides/images-vision + "gpt-4.1" | "gpt-4o" => Self::OpenAiTiles { + base: 85, + tile: 170, + }, + "gpt-4o-mini" => Self::OpenAiTiles { + base: 2833, + tile: 5667, + }, + "gpt-5" | "gpt-5.1" => Self::OpenAiTiles { + base: 70, + tile: 140, + }, + "o1" | "o1-pro" | "o3" => Self::OpenAiTiles { + base: 75, + tile: 150, + }, + "gpt-4.1-nano" | "o4-mini" => { + let percent = if family == "gpt-4.1-nano" { 246 } else { 172 }; + Self::Patches { + edge: 32, + max: 1536, + percent, + } + } + // A patch upper bound before any deployment-specific resize. + // https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct + id if id.starts_with("qwen2.5-vl") || id.starts_with("qwen2-vl") => Self::Patches { + edge: 28, + max: u64::MAX, + percent: 100, + }, + // https://ai.google.dev/gemini-api/docs/media-resolution + id if id.starts_with("gemini-3.") + || id.starts_with("gemini-3-") + || id.starts_with("gemini-4.") + || id.starts_with("gemini-4-") => + { + Self::Gemini(1120) + } + // https://platform.claude.com/docs/en/build-with-claude/vision + id if id.starts_with("claude-") => { + let id = id.strip_suffix("-latest").unwrap_or(id); + let standard = id.starts_with("claude-3-") + || matches!( + id, + "claude-opus-4" + | "claude-sonnet-4" + | "claude-opus-4-1" + | "claude-opus-4-5" + | "claude-sonnet-4-5" + | "claude-haiku-4-5" + | "claude-opus-4-6" + | "claude-sonnet-4-6" + ); + let (max_edge, max_tokens) = if standard { (1568, 1568) } else { (2576, 4784) }; + Self::Claude { + max_edge, + max_tokens, + } + } + _ => Self::Generic, + } + } + + pub(crate) fn with_detail(self, detail: Option<&str>) -> Self { + match (self, detail) { + (Self::OpenAiPatches(patches), detail) => { + Self::OpenAiPatches(patches.with_detail(detail)) + } + (Self::OpenAiTiles { base, .. }, Some("low")) => Self::Fixed(base), + _ => self, + } + } + + pub(crate) fn with_gemini_media_resolution(self, resolution: Option<&str>) -> Self { + if !matches!(self, Self::Gemini(_)) { + return self; + } + match resolution { + Some("MEDIA_RESOLUTION_LOW") => Self::Gemini(280), + Some("MEDIA_RESOLUTION_MEDIUM") => Self::Gemini(560), + Some("MEDIA_RESOLUTION_HIGH" | "MEDIA_RESOLUTION_UNSPECIFIED") => Self::Gemini(1120), + Some("MEDIA_RESOLUTION_ULTRA_HIGH") => Self::Gemini(2240), + _ => self, + } + } + + pub(crate) fn estimate(self, width: u32, height: u32) -> usize { + let cost = match self { + Self::Generic => return estimate_image_tokens(width, height), + Self::OpenAiPatches(patches) => patches.estimate(width, height), + Self::Fixed(tokens) | Self::Gemini(tokens) => tokens, + Self::Claude { + max_edge, + max_tokens, + } => { + let longest = width.max(height); + let (w, h) = scale_long_edge(width, height, longest.min(max_edge)); + grid(w, h, 28).min(max_tokens) + } + + Self::Patches { edge, max, percent } => { + (grid(width, height, edge).min(max) * percent).div_ceil(100) + } + Self::OpenAiTiles { base, tile } => { + let scale = (2048.0 / f64::from(width.max(height))) + .min(768.0 / f64::from(width.min(height))) + .min(1.0); + let resize = |side| ((f64::from(side) * scale) as u32).max(1); + base + tile * grid(resize(width), resize(height), 512) + } + }; + usize::try_from(cost).unwrap_or(usize::MAX) + } +} + +/// Read header metadata without decoding a pixel buffer. Most screenshots and +/// photos expose dimensions near the start, even when their payload is large. +pub fn inline_image_dimensions(mime_type: &str, data_base64: &str) -> Option<(u32, u32)> { + let format = ImageFormat::from_mime_type(mime_type)?; + let dimensions = |bytes: &[u8]| { + ImageReader::with_format(Cursor::new(bytes), format) + .into_dimensions() + .ok() + .filter(|&(w, h)| w > 0 && h > 0) + }; + let encoded = data_base64.as_bytes(); + const PREFIX: usize = 4096; // Complete base64 quartets. + if encoded.len() > PREFIX { + if let Some(size) = dimensions(&STANDARD.decode(&encoded[..PREFIX]).ok()?) { + return Some(size); + } + } + dimensions(&STANDARD.decode(encoded).ok()?) +} + +pub(crate) struct ResizedInlineImage { + pub mime_type: String, + pub data_base64: String, + pub width: u32, + pub height: u32, +} + +fn scale_long_edge(width: u32, height: u32, edge: u32) -> (u32, u32) { + let longest = u64::from(width.max(height).max(1)); + let scale = |side| ((u64::from(side) * u64::from(edge) + longest / 2) / longest).max(1) as u32; + (scale(width), scale(height)) +} + +impl VisionTokenPolicy { + /// Reserve a preview with a 512-pixel long edge, or the entire smaller input. + pub(crate) fn min_readable_tokens(self, width: u32, height: u32) -> usize { + let (w, h) = scale_long_edge(width, height, width.max(height).min(512)); + self.estimate(w, h) + } + + /// Find the largest proportional pixel dimensions that fit before resampling. + fn fit_dimensions(self, width: u32, height: u32, budget: usize) -> Result<(u32, u32)> { + let minimum = self.min_readable_tokens(width, height); + ensure!( + budget >= minimum, + "A readable image preview needs at least {minimum} estimated tokens; {budget} available. Crop the image or shorten the context." + ); + let longest = width.max(height); + let (mut lo, mut hi) = (longest.min(512), longest); + while lo < hi { + let mid = lo + (hi - lo).div_ceil(2); + let (w, h) = scale_long_edge(width, height, mid); + if self.estimate(w, h) <= budget { + lo = mid; + } else { + hi = mid - 1; + } + } + Ok(scale_long_edge(width, height, lo)) + } +} + +/// Avoid silently substituting one animation frame for an entire visual input. +fn decode_still( + bytes: &[u8], + format: ImageFormat, +) -> Result<(DynamicImage, image::metadata::Orientation)> { + let input = Cursor::new(bytes); + let mut decoder: Box = match format { + ImageFormat::Png => { + let png = PngDecoder::with_limits(input, Limits::default())?; + ensure!( + !png.is_apng()?, + "Cannot resize an animated PNG as a still image" + ); + Box::new(png) + } + ImageFormat::WebP => { + let webp = WebPDecoder::new(input)?; + ensure!( + !webp.has_animation(), + "Cannot resize an animated WebP as a still image" + ); + Box::new(webp) + } + ImageFormat::Gif => { + let mut gif = GifDecoder::new(input)?; + gif.set_limits(Limits::default())?; + let mut frames = gif.into_frames(); + let first = frames.next().context("GIF has no frames")??; + ensure!( + frames.next().transpose()?.is_none(), + "Cannot resize an animated GIF as a still image" + ); + return Ok(( + first.into_buffer().into(), + image::metadata::Orientation::NoTransforms, + )); + } + ImageFormat::Jpeg | ImageFormat::Bmp => { + Box::new(ImageReader::with_format(input, format).into_decoder()?) + } + _ => anyhow::bail!("Unsupported inline image format {format:?}"), + }; + let orientation = decoder.orientation()?; + let mut limits = Limits::default(); + limits.reserve(decoder.total_bytes())?; + decoder.set_limits(limits)?; + Ok((DynamicImage::from_decoder(decoder)?, orientation)) +} + +impl VisionTokenPolicy { + /// Resize only the outgoing image, retaining text edges and transparency. + pub(crate) fn resize( + self, + mime_type: &str, + data_base64: &str, + target_tokens: usize, + ) -> Result { + let format = ImageFormat::from_mime_type(mime_type) + .ok_or_else(|| anyhow!("Unsupported inline image type {mime_type}"))?; + let (width, height) = inline_image_dimensions(mime_type, data_base64) + .context("Cannot read inline image dimensions")?; + if self.estimate(width, height) <= target_tokens { + return Ok(ResizedInlineImage { + mime_type: mime_type.to_owned(), + data_base64: data_base64.to_owned(), + width, + height, + }); + } + let (w, h) = self.fit_dimensions(width, height, target_tokens)?; + let bytes = STANDARD + .decode(data_base64) + .context("Invalid inline image base64")?; + let (source, orientation) = decode_still(&bytes, format)?; + let mut resized = source.resize_exact(w, h, FilterType::Lanczos3); + resized.apply_orientation(orientation); + let (width, height) = resized.dimensions(); + let mut output = Cursor::new(Vec::new()); + let output_format = match format { + ImageFormat::Jpeg => { + JpegEncoder::new_with_quality(&mut output, 90).encode_image(&resized)?; + ImageFormat::Jpeg + } + _ => { + let format = if format == ImageFormat::WebP { + ImageFormat::WebP + } else { + ImageFormat::Png + }; + resized.write_to(&mut output, format)?; + format + } + }; + Ok(ResizedInlineImage { + mime_type: output_format.to_mime_type().to_owned(), + data_base64: STANDARD.encode(output.into_inner()), + width, + height, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn selected_model_and_image_detail_determine_the_visual_estimate() { + let tiles = VisionTokenPolicy::for_model("openai/gpt-4o-2024-08-06"); + assert_eq!(tiles.estimate(2048, 2048), 765); + assert_eq!(tiles.with_detail(Some("low")).estimate(2048, 2048), 85); + assert_eq!( + VisionTokenPolicy::for_model("gpt-4o-mini").estimate(512, 512), + 8500 + ); + assert_eq!( + VisionTokenPolicy::for_model("gpt-4.1-mini").estimate(1024, 1024), + 1659 + ); + assert_eq!( + VisionTokenPolicy::for_model("Qwen/Qwen2.5-VL-7B-Instruct").estimate(280, 560), + 200 + ); + assert_eq!( + VisionTokenPolicy::for_model("custom").estimate(2048, 2048), + 3250 + ); + } + + #[test] + fn openai_patch_models_apply_their_own_detail_defaults_and_patch_limits() { + let astra = VisionTokenPolicy::for_model("openai/gpt-6-astra-2026-01-01"); + assert_eq!(astra.estimate(2048, 2048), 4916); + assert_eq!(astra.with_detail(Some("auto")).estimate(2048, 2048), 4916); + assert_eq!(astra.with_detail(Some("low")).estimate(2048, 2048), 308); + assert_eq!(astra.with_detail(Some("high")).estimate(2048, 2048), 3000); + assert_eq!(astra.with_detail(Some("high")).estimate(4096, 512), 2458); + + for name in ["gpt-5.4", "gpt-5.4-mini"] { + let policy = VisionTokenPolicy::for_model(name); + assert_eq!(policy.estimate(2048, 2048), 3000); + assert_eq!(policy.with_detail(Some("low")).estimate(2048, 2048), 4916); + assert_eq!( + policy.with_detail(Some("original")).estimate(4096, 4096), + 12_000 + ); + // 2048x1536 exceeds 2500 patches. The scaled grid is 57x43. + assert_eq!(policy.estimate(2048, 1536), 2942); + } + let mini = VisionTokenPolicy::for_model("gpt-4.1-mini-2025-04-14"); + for detail in ["low", "high", "auto"] { + assert_eq!(mini.with_detail(Some(detail)).estimate(4096, 4096), 6636); + } + } + + #[test] + fn gemini_resolution_and_claude_tiers_bound_visual_tokens() { + for model in ["gemini-3.6-flash", "gemini-4-hydrogen"] { + let policy = VisionTokenPolicy::for_model(model); + assert_eq!(policy.estimate(32, 32), 1120); + for (level, expected) in [ + ("MEDIA_RESOLUTION_LOW", 280), + ("MEDIA_RESOLUTION_MEDIUM", 560), + ("MEDIA_RESOLUTION_HIGH", 1120), + ("MEDIA_RESOLUTION_ULTRA_HIGH", 2240), + ] { + assert_eq!( + policy + .with_gemini_media_resolution(Some(level)) + .estimate(2048, 1024), + expected + ); + } + } + let standard = VisionTokenPolicy::for_model("claude-haiku-4-5-20251001"); + assert_eq!(standard.estimate(4000, 4000), 1568); + assert_eq!(standard.estimate(8192, 128), 56); + let high = VisionTokenPolicy::for_model("claude-sonnet-5"); + assert_eq!(high.estimate(3840, 2160), 4784); + assert_eq!(high.estimate(1000, 1000), 1296); + } + + #[test] + fn oversized_screenshot_fits_at_largest_resolution_and_retains_alpha() { + let source = DynamicImage::new_rgba8(2048, 1024); + let mut bytes = Cursor::new(Vec::new()); + source.write_to(&mut bytes, ImageFormat::Png).unwrap(); + let data = STANDARD.encode(bytes.into_inner()); + assert_eq!( + inline_image_dimensions("image/png", &data), + Some((2048, 1024)) + ); + let budget = estimate_image_tokens(1024, 512); + let projected = VisionTokenPolicy::Generic + .resize("image/png", &data, budget) + .unwrap(); + assert!(estimate_image_tokens(projected.width, projected.height) <= budget); + assert!( + estimate_image_tokens(projected.width + 1, (projected.width + 1).div_ceil(2)) > budget + ); + let decoded = + image::load_from_memory(&STANDARD.decode(projected.data_base64).unwrap()).unwrap(); + assert_eq!(decoded.dimensions(), (projected.width, projected.height)); + assert_eq!(decoded.to_rgba8().get_pixel(0, 0)[3], 0); + let original = VisionTokenPolicy::Generic + .resize("image/png", &data, usize::MAX) + .unwrap(); + assert_eq!(original.data_base64, data); + } + + #[test] + fn invalid_input_and_infeasible_budgets_are_explicit() { + assert!(inline_image_dimensions("image/png", "@@").is_none()); + assert!(VisionTokenPolicy::Generic + .resize("image/png", "@@", 1000) + .is_err()); + assert!(VisionTokenPolicy::Generic + .fit_dimensions( + 1024, + 1024, + VisionTokenPolicy::Generic.min_readable_tokens(1024, 1024) - 1 + ) + .is_err()); + assert_eq!( + VisionTokenPolicy::Generic + .fit_dimensions(1, 10000, estimate_image_tokens(1, 512)) + .unwrap(), + (1, 512) + ); + } + + #[test] + fn shrinking_an_animation_does_not_silently_send_one_frame() { + let mut bytes = Vec::new(); + let frame = image::Frame::new(image::RgbaImage::new(640, 64)); + image::codecs::gif::GifEncoder::new(&mut bytes) + .encode_frames([frame.clone(), frame]) + .unwrap(); + let data = STANDARD.encode(bytes); + let budget = VisionTokenPolicy::Generic.min_readable_tokens(640, 64); + let error = VisionTokenPolicy::Generic + .resize("image/gif", &data, budget) + .err() + .expect("resizing an animated image must fail explicitly"); + assert!(error.to_string().contains("animated GIF")); + let original = VisionTokenPolicy::Generic + .resize("image/gif", &data, usize::MAX) + .unwrap(); + assert_eq!(original.data_base64, data); + } +} diff --git a/src/crates/adapters/ai-adapters/src/vision_tokens/openai_patches.rs b/src/crates/adapters/ai-adapters/src/vision_tokens/openai_patches.rs new file mode 100644 index 0000000000..12e131063e --- /dev/null +++ b/src/crates/adapters/ai-adapters/src/vision_tokens/openai_patches.rs @@ -0,0 +1,104 @@ +//! OpenAI's patch-based model sizing table and 32-pixel patch calculation. +//! https://developers.openai.com/api/docs/guides/images-vision#model-sizing-behavior + +use super::{grid, scale_long_edge}; + +#[derive(Clone, Copy)] +enum Family { + Astra6, + Gpt56, + Gpt55, + Gpt54, + Gpt52, + Gpt41Mini, +} + +#[derive(Clone, Copy)] +enum Detail { + Low, + High, + Original, +} + +#[derive(Clone, Copy)] +pub(crate) struct OpenAiPatches { + family: Family, + detail: Detail, +} + +impl OpenAiPatches { + pub(super) fn for_model(model: &str) -> Option { + use Family::*; + let family = match model { + "gpt-6-astra" => Astra6, + "gpt-5.6-sol" | "gpt-5.6-terra" | "gpt-5.6-luna" => Gpt56, + "gpt-5.5" => Gpt55, + "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-nano" => Gpt54, + "gpt-5.2" => Gpt52, + "gpt-4.1-mini" => Gpt41Mini, + _ => return None, + }; + let detail = match family { + Astra6 | Gpt56 | Gpt55 => Detail::Original, + Gpt54 | Gpt52 | Gpt41Mini => Detail::High, + }; + Some(Self { family, detail }) + } + + pub(super) fn with_detail(mut self, detail: Option<&str>) -> Self { + self.detail = match detail { + Some("low") => Detail::Low, + Some("high") => Detail::High, + Some("original") => Detail::Original, + _ => return self, + }; + self + } + + pub(super) fn estimate(self, width: u32, height: u32) -> u64 { + use Detail::*; + use Family::*; + let (max_edge, patch_budget) = match (self.family, self.detail) { + (Gpt52 | Gpt41Mini, _) | (Gpt54, Low) => (2048, 6144), + (_, Low) => (512, 256), + (Astra6, High) => (65_535, 2500), + (_, High) => (2048, 2500), + (Gpt54 | Gpt55, Original) => (6000, 10_000), + // This detail has no automatic patch-budget resize. In particular, + // do not cap the estimate at the provider's separate rejection limit. + (Astra6 | Gpt56, Original) => (65_535, u64::MAX), + }; + let patches = resized_patches(width, height, max_edge, patch_budget); + let percent = if matches!(self.family, Gpt41Mini) { + 162 + } else { + 120 + }; + (patches * percent).div_ceil(100) + } +} + +fn resized_patches(width: u32, height: u32, max_edge: u32, budget: u64) -> u64 { + let (width, height) = if width.max(height) > max_edge { + scale_long_edge(width, height, max_edge) + } else { + (width, height) + }; + let patches = grid(width, height, 32); + if patches <= budget { + return patches; + } + + // Scale to the target area, then snap the tighter axis to a whole patch. + let width = f64::from(width); + let height = f64::from(height); + let scale = ((budget as f64 * 32.0 * 32.0) / (width * height)).sqrt(); + let scaled_w = width * scale / 32.0; + let scaled_h = height * scale / 32.0; + if scaled_w < 1.0 || scaled_h < 1.0 { + // A panorama still needs one patch along its short axis. + return budget; + } + let scale = (scaled_w.floor() * 32.0 / width).min(scaled_h.floor() * 32.0 / height); + grid((width * scale) as u32, (height * scale) as u32, 32).min(budget) +} diff --git a/src/crates/assembly/core/Cargo.toml b/src/crates/assembly/core/Cargo.toml index 7867d6db7f..881a24db4d 100644 --- a/src/crates/assembly/core/Cargo.toml +++ b/src/crates/assembly/core/Cargo.toml @@ -214,6 +214,7 @@ agent-runtime = [ "openbitfun-services-core/session-event-format", "ai-adapter-runtime", "openbitfun-ai-adapters/local-tokenizer", + "openbitfun-ai-adapters/vision-input", "dep:openbitfun-agent-runtime", "openbitfun-agent-runtime/agent-runtime", "dep:openbitfun-agent-content", diff --git a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs index a93f68512c..27438dd9b1 100644 --- a/src/crates/assembly/core/src/agentic/coordination/coordinator.rs +++ b/src/crates/assembly/core/src/agentic/coordination/coordinator.rs @@ -7187,6 +7187,7 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet } else { Vec::new() }; + let current_turn_start = image_input_messages.len(); image_input_messages.extend(additional_prepended_messages.iter().cloned()); image_input_messages.extend( wrapped_user_input_payload @@ -7211,6 +7212,7 @@ Update the persona files and delete BOOTSTRAP.md as soon as bootstrap is complet ); let image_requirement = ExecutionEngine::resolve_image_input_requirement( &image_input_messages, + current_turn_start, session.config.enable_tools, &image_tool_context, ) diff --git a/src/crates/assembly/core/src/agentic/core/message.rs b/src/crates/assembly/core/src/agentic/core/message.rs index 47fbbdf4ff..e38f3f3195 100644 --- a/src/crates/assembly/core/src/agentic/core/message.rs +++ b/src/crates/assembly/core/src/agentic/core/message.rs @@ -3,6 +3,9 @@ use crate::util::types::{Message as AIMessage, ToolCall as AIToolCall, ToolImage use crate::util::TokenCounter; use log::warn; use openbitfun_agent_runtime::prompt_markup::is_system_reminder_only; +use openbitfun_ai_adapters::vision_tokens::{ + estimate_image_tokens, inline_image_dimensions, UNKNOWN_IMAGE_DIMENSIONS, +}; use openbitfun_core_types::{ModelResponseReplay, ReasoningContentKind}; pub use openbitfun_runtime_ports::{CompressionContract, CompressionContractItem}; use serde::{Deserialize, Serialize}; @@ -694,37 +697,54 @@ impl Message { tokens } - fn estimate_image_tokens(metadata: Option<&serde_json::Value>) -> usize { - let (width, height) = metadata - .and_then(|m| { - let w = m.get("width").and_then(|v| v.as_u64()); - let h = m.get("height").and_then(|v| v.as_u64()); - match (w, h) { - (Some(w), Some(h)) if w > 0 && h > 0 => Some((w as u32, h as u32)), - _ => None, - } - }) - .unwrap_or((1024, 1024)); + fn user_image_dimensions(image: &ImageContextData) -> Option<(u32, u32)> { + if let Some(size) = image + .data_url + .as_deref() + .and_then(|url| url.split_once(',')) + .and_then(|(_, data)| inline_image_dimensions(&image.mime_type, data)) + { + return Some(size); + } - let tiles_w = width.div_ceil(512); - let tiles_h = height.div_ceil(512); - let tiles = (tiles_w.max(1) * tiles_h.max(1)) as usize; - 50 + tiles * 200 + // Path-only images may live on another host. Use their saved dimensions. + let metadata = image.metadata.as_ref()?; + let dimension = |key: &str| { + u32::try_from(metadata.get(key)?.as_u64()?) + .ok() + .filter(|&size| size > 0) + }; + Some((dimension("width")?, dimension("height")?)) } pub fn estimate_tokens_with_reasoning(&self, include_reasoning: bool) -> usize { - let mut total = 0usize; - total += 4; + let text_tokens = self.estimate_non_image_tokens_with_reasoning(include_reasoning); + let add_image = |total: usize, dimensions: Option<(u32, u32)>| { + let (width, height) = dimensions.unwrap_or(UNKNOWN_IMAGE_DIMENSIONS); + total.saturating_add(estimate_image_tokens(width, height)) + }; + match &self.content { + MessageContent::Multimodal { images, .. } => images + .iter() + .map(Self::user_image_dimensions) + .fold(text_tokens, add_image), + MessageContent::ToolResult { + image_attachments: Some(images), + .. + } => images + .iter() + .map(|image| inline_image_dimensions(&image.mime_type, &image.data_base64)) + .fold(text_tokens, add_image), + _ => text_tokens, + } + } + + pub fn estimate_non_image_tokens_with_reasoning(&self, include_reasoning: bool) -> usize { + let mut total = 4; match &self.content { - MessageContent::Text(text) => { - total += TokenCounter::estimate_tokens(text); - } - MessageContent::Multimodal { text, images } => { + MessageContent::Text(text) | MessageContent::Multimodal { text, .. } => { total += TokenCounter::estimate_tokens(text); - for image in images { - total += Self::estimate_image_tokens(image.metadata.as_ref()); - } } MessageContent::Mixed { reasoning_content, @@ -756,7 +776,6 @@ impl Message { tool_name, result, result_for_assistant, - image_attachments, .. } => { if let Some(text) = result_for_assistant.as_ref().filter(|s| !s.is_empty()) { @@ -766,11 +785,6 @@ impl Message { } else { total += TokenCounter::estimate_tokens(tool_name); } - if let Some(imgs) = image_attachments { - for _ in imgs { - total += Self::estimate_image_tokens(None); - } - } } } @@ -842,6 +856,60 @@ mod tests { }; use serde_json::json; + #[test] + fn restored_tool_results_and_inline_uploads_use_the_encoded_image_dimensions() { + use super::{ImageContextData, ToolImageAttachment, ToolResult}; + use base64::{engine::general_purpose::STANDARD, Engine}; + use std::io::Cursor; + + for (size, expected_tokens) in [(512, 250), (2048, 3250)] { + let mut png = Cursor::new(Vec::new()); + image::DynamicImage::new_luma8(size, size) + .write_to(&mut png, image::ImageFormat::Png) + .unwrap(); + let data = STANDARD.encode(png.into_inner()); + let user = Message::user_multimodal( + "Screenshot".into(), + vec![ImageContextData { + id: "screenshot".into(), + image_path: None, + data_url: Some(format!("data:image/png;base64,{data}")), + mime_type: "image/png".into(), + metadata: None, + }], + ); + let mut result = ToolResult { + tool_id: "call".into(), + tool_name: "view_image".into(), + effective_tool_name: None, + result: json!({}), + result_for_assistant: Some("Screenshot".into()), + is_error: false, + duration_ms: None, + image_attachments: None, + }; + let text_tokens = + Message::tool_result(result.clone()).estimate_tokens_with_reasoning(false); + result.image_attachments = Some(vec![ToolImageAttachment { + mime_type: "image/png".into(), + data_base64: data, + }]); + + let stored = serde_json::to_value(Message::tool_result(result)).unwrap(); + let restored: Message = serde_json::from_value(stored).unwrap(); + for message in [user, restored] { + assert_eq!( + message.estimate_non_image_tokens_with_reasoning(false), + text_tokens + ); + assert_eq!( + message.estimate_tokens_with_reasoning(false) - text_tokens, + expected_tokens + ); + } + } + } + #[test] fn ptc_specs_and_routed_execution_metadata_round_trip_together_with_legacy_defaults() { let mut message = Message::assistant("Synthetic reply".into()); diff --git a/src/crates/assembly/core/src/agentic/core/messages_helper.rs b/src/crates/assembly/core/src/agentic/core/messages_helper.rs index 58d4b9a52d..195f6892e9 100644 --- a/src/crates/assembly/core/src/agentic/core/messages_helper.rs +++ b/src/crates/assembly/core/src/agentic/core/messages_helper.rs @@ -71,6 +71,20 @@ impl MessageHelper { messages: &[Message], tools: Option<&[ToolDefinition]>, reasoning_policy: RequestReasoningTokenPolicy, + ) -> usize { + Self::estimate_request_tokens_with( + messages, + tools, + reasoning_policy, + Message::estimate_tokens_with_reasoning, + ) + } + + pub(crate) fn estimate_request_tokens_with( + messages: &[Message], + tools: Option<&[ToolDefinition]>, + reasoning_policy: RequestReasoningTokenPolicy, + estimate_message: fn(&Message, bool) -> usize, ) -> usize { let reasoning_frontier_start = match reasoning_policy { RequestReasoningTokenPolicy::FullHistory => Some(0), @@ -86,7 +100,7 @@ impl MessageHelper { .map(|(index, message)| { let include_reasoning = reasoning_frontier_start.is_some_and(|frontier_start| index >= frontier_start); - message.estimate_tokens_with_reasoning(include_reasoning) + estimate_message(message, include_reasoning) }) .sum::(); diff --git a/src/crates/assembly/core/src/agentic/execution/compression_job.rs b/src/crates/assembly/core/src/agentic/execution/compression_job.rs index f6b4967c45..c423cb99ea 100644 --- a/src/crates/assembly/core/src/agentic/execution/compression_job.rs +++ b/src/crates/assembly/core/src/agentic/execution/compression_job.rs @@ -220,7 +220,7 @@ impl CompressionJob { } async fn request_summary(&self, messages: &[Message]) -> OpenBitFunResult { - let mut messages = ExecutionEngine::build_ai_messages_for_send( + let (mut messages, image_turn_start) = ExecutionEngine::build_ai_messages_for_send( messages, &self.client.config.format, self.workspace.as_ref(), @@ -244,11 +244,15 @@ impl CompressionJob { ); } messages.push(AIMessage::user(self.compressor.build_compact_prompt())); + let context = ModelRequestContext { + image_turn_start: Some(image_turn_start), + ..self.request_context.clone() + }; super::super::compression_request::request_summary( self.client.clone(), messages, self.tools.clone(), - &self.request_context, + &context, self.trace.clone(), ) .await diff --git a/src/crates/assembly/core/src/agentic/execution/context_budget.rs b/src/crates/assembly/core/src/agentic/execution/context_budget.rs index cfbab0b502..a472266e26 100644 --- a/src/crates/assembly/core/src/agentic/execution/context_budget.rs +++ b/src/crates/assembly/core/src/agentic/execution/context_budget.rs @@ -1,7 +1,7 @@ //! Input admission budgets shared by ordinary requests and pool routing. -use crate::service::config::types::automatic_max_output_tokens; use openbitfun_core_types::model_pool::ModelPoolContextBudget; +use openbitfun_core_types::token_estimate::{automatic_max_output_tokens, INPUT_SAFETY_RESERVE}; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub(super) struct CompressionTriggerBudget { @@ -12,8 +12,6 @@ pub(super) struct CompressionTriggerBudget { } impl CompressionTriggerBudget { - const SAFETY_RESERVE_TOKENS: usize = 10_000; - /// The active model or pool owns the request budget. Persisted session /// windows can describe a previous model or a legacy creation default. pub(super) fn for_request( @@ -30,7 +28,7 @@ impl CompressionTriggerBudget { let output_reserve_tokens = configured_max_tokens .map(|value| value as usize) .unwrap_or_else(|| automatic_max_output_tokens(context_window as u32) as usize); - let safety_reserve_tokens = Self::SAFETY_RESERVE_TOKENS; + let safety_reserve_tokens = INPUT_SAFETY_RESERVE; Self { context_window, input_limit: context_window @@ -43,7 +41,7 @@ impl CompressionTriggerBudget { pub(super) fn for_pool(budget: ModelPoolContextBudget) -> Self { let context_window = budget.context_window as usize; let input_limit = budget.input_limit as usize; - let safety_reserve_tokens = Self::SAFETY_RESERVE_TOKENS.min(context_window); + let safety_reserve_tokens = INPUT_SAFETY_RESERVE.min(context_window); Self { context_window, input_limit, diff --git a/src/crates/assembly/core/src/agentic/execution/execution_engine.rs b/src/crates/assembly/core/src/agentic/execution/execution_engine.rs index 73cebf8205..d7b6e7ab00 100644 --- a/src/crates/assembly/core/src/agentic/execution/execution_engine.rs +++ b/src/crates/assembly/core/src/agentic/execution/execution_engine.rs @@ -747,6 +747,7 @@ impl ExecutionEngine { output_schema: context .get(openbitfun_runtime_ports::OUTPUT_SCHEMA_CONTEXT_KEY) .and_then(|schema| serde_json::from_str(schema).ok()), + ..Default::default() } } @@ -839,16 +840,18 @@ impl ExecutionEngine { messages: &[Message], tools: Option<&[ToolDefinition]>, ) -> usize { - MessageHelper::estimate_request_tokens( + MessageHelper::estimate_request_tokens_with( messages, tools, RequestReasoningTokenPolicy::LatestTurnOnly, + Message::estimate_non_image_tokens_with_reasoning, ) } /// Estimate request pressure for compression decisions. /// - /// `total_tokens` tracks the whole provider request input. The snapshot also + /// Pixels can be resized or omitted on the outgoing request. Only text pressure + /// warrants compressing the durable conversation. The snapshot also /// keeps the mutable conversation portion and fixed scaffold overhead /// available for diagnostics, while the trigger decision reserves output and /// safety budget from the full context window. @@ -996,7 +999,7 @@ impl ExecutionEngine { fn estimate_tail_tokens(messages: &[Message]) -> usize { messages .iter() - .map(|message| message.estimate_tokens_with_reasoning(true)) + .map(|message| message.estimate_non_image_tokens_with_reasoning(true)) .sum() } @@ -1226,7 +1229,7 @@ impl ExecutionEngine { .unwrap_or(0); let preserved_tokens: usize = preserved .iter() - .map(|m| m.estimate_tokens_with_reasoning(true)) + .map(|m| m.estimate_non_image_tokens_with_reasoning(true)) .sum::() + tool_tokens + prepended_reminder_tokens @@ -1237,13 +1240,13 @@ impl ExecutionEngine { + rounds .iter() .flat_map(|r| r.iter()) - .map(|m| m.estimate_tokens_with_reasoning(true)) + .map(|m| m.estimate_non_image_tokens_with_reasoning(true)) .sum::(); while total_tokens > context_window && kept_start < rounds.len() { let round_tokens: usize = rounds[kept_start] .iter() - .map(|m| m.estimate_tokens_with_reasoning(true)) + .map(|m| m.estimate_non_image_tokens_with_reasoning(true)) .sum(); total_tokens -= round_tokens; kept_start += 1; @@ -1954,10 +1957,12 @@ impl ExecutionEngine { /// checked separately by ImageInputRequirement::validate. pub(crate) async fn resolve_image_input_requirement( messages: &[Message], + current_turn_start: usize, tools_enabled: bool, tool_context: &ToolUseContext, ) -> ImageInputRequirement { - let requirement = Self::image_input_requirement(messages, tools_enabled); + let requirement = + Self::image_input_requirement(messages, current_turn_start, tools_enabled); if requirement != ImageInputRequirement::NativeOrAnalysisTool { return requirement; } @@ -1991,7 +1996,7 @@ impl ExecutionEngine { .iter() .chain(&visible.deferred_tools) .any(|tool| tool.name() == "analyze_image"); - Self::image_input_requirement(messages, analysis_available) + Self::image_input_requirement(messages, current_turn_start, analysis_available) } pub(crate) async fn resolve_model_id_for_turn( @@ -2168,7 +2173,10 @@ impl ExecutionEngine { attach_images: bool, ) -> openbitfun_core_types::UsageContextBreakdown { let kept_images = if attach_images { - Self::image_bearing_indices_to_keep(messages) + Self::image_bearing_indices_to_keep( + messages, + Self::image_turn_start(messages, current_turn_id), + ) } else { HashSet::new() }; @@ -2212,6 +2220,16 @@ impl ExecutionEngine { ) } + /// Provider usage for a prefix containing pixels cannot be split after the fact. + /// Earlier text-only anchors still calibrate the estimate of the remaining text. + fn text_only_anchor_prefix(messages: &[Message]) -> &[Message] { + let end = messages + .iter() + .position(Self::message_bears_images) + .unwrap_or(messages.len()); + &messages[..end] + } + /// True if this message would contribute at least one image to the model (before pruning). fn message_bears_images(msg: &Message) -> bool { if Self::skip_message_for_model_send(msg) { @@ -2246,9 +2264,10 @@ impl ExecutionEngine { pub(crate) fn image_input_requirement( messages: &[Message], + current_turn_start: usize, analysis_tool_available: bool, ) -> ImageInputRequirement { - let retained = Self::image_bearing_indices_to_keep(messages); + let retained = Self::image_bearing_indices_to_keep(messages, current_turn_start); if retained.is_empty() { return ImageInputRequirement::None; } @@ -2265,8 +2284,22 @@ impl ExecutionEngine { } } - /// Indices of the image-bearing messages that should keep image payloads. - fn image_bearing_indices_to_keep(messages: &[Message]) -> HashSet { + fn image_turn_start(messages: &[Message], current_turn_id: &str) -> usize { + messages + .iter() + .position(|message| { + message.metadata.turn_id.as_deref() == Some(current_turn_id) + && !Self::skip_message_for_model_send(message) + }) + .unwrap_or(messages.len()) + } + + /// History pixels are elided in cache-stable batches. Active-turn pixels + /// are kept for the selected model's outgoing token budget. + fn image_bearing_indices_to_keep( + messages: &[Message], + current_turn_start: usize, + ) -> HashSet { let with_images: Vec = messages .iter() .enumerate() @@ -2274,7 +2307,13 @@ impl ExecutionEngine { .map(|(i, _)| i) .collect(); let elided = Self::elided_image_message_count(with_images.len()); - with_images[elided..].iter().copied().collect() + with_images + .into_iter() + .enumerate() + .filter_map(|(rank, index)| { + (rank >= elided || index >= current_turn_start).then_some(index) + }) + .collect() } /// Number of oldest image-bearing messages whose pixels are elided. It only @@ -2302,7 +2341,7 @@ impl ExecutionEngine { let finalize_tool_names = Self::finalize_tool_names(input.tool_definitions.as_deref()); let finalize_runtime_tool_restrictions = Self::finalize_runtime_tool_restrictions(input.context, &finalize_tool_names); - let mut final_ai_messages = Self::build_ai_messages_for_send( + let (mut final_ai_messages, image_turn_start) = Self::build_ai_messages_for_send( input.messages, &input.ai_client.config.format, input.context.workspace.as_ref(), @@ -2341,7 +2380,10 @@ impl ExecutionEngine { loaded_deferred_tool_specs: Vec::new(), model_config_id: input.primary_model_facts.model_id.clone(), effective_model_name: input.ai_client.config.model.clone(), - model_request_context: input.model_request_context.clone(), + model_request_context: ModelRequestContext { + image_turn_start: Some(image_turn_start), + ..input.model_request_context.clone() + }, account_client_source: input.account_client_source.clone(), channel_client_source: input.channel_client_source.clone(), prepared_model: None, @@ -2379,7 +2421,7 @@ impl ExecutionEngine { current_turn_id: &str, attach_images: bool, prepended_reminders: &[&str], - ) -> OpenBitFunResult> { + ) -> OpenBitFunResult<(Vec, usize)> { let limits = ImageLimits::for_provider(provider); let image_context = ToolUseContext::for_tool_listing(workspace.cloned(), workspace_services.cloned()); @@ -2390,6 +2432,7 @@ impl ExecutionEngine { .filter(|text| !text.is_empty()) .collect::>(); let mut result = Vec::with_capacity(messages.len() + trimmed_reminders.len()); + let mut image_turn_start = None; let mut attached_image_count = 0usize; let first_non_system_index = messages .iter() @@ -2397,8 +2440,9 @@ impl ExecutionEngine { .unwrap_or(messages.len()); let mut prepended_reminders_injected = false; + let current_turn_start = Self::image_turn_start(messages, current_turn_id); let keep_image_messages = if attach_images { - Self::image_bearing_indices_to_keep(messages) + Self::image_bearing_indices_to_keep(messages, current_turn_start) } else { HashSet::new() }; @@ -2416,6 +2460,9 @@ impl ExecutionEngine { { continue; } + if msg_idx == current_turn_start { + image_turn_start = Some(result.len()); + } let keep_this_message_images = attach_images && keep_image_messages.contains(&msg_idx); match &msg.content { MessageContent::Multimodal { text, images } => { @@ -2552,7 +2599,8 @@ impl ExecutionEngine { } } - Ok(result) + let image_turn_start = image_turn_start.unwrap_or(result.len()); + Ok((result, image_turn_start)) } fn render_multimodal_as_text(text: &str, images: &[ImageContextData]) -> String { @@ -3419,6 +3467,7 @@ impl ExecutionEngine { ); Self::resolve_image_input_requirement( &initial_messages, + Self::image_turn_start(&initial_messages, &context.dialog_turn_id), enable_tools, &description_context, ) @@ -4224,6 +4273,7 @@ impl ExecutionEngine { let pool_attempt = if let Some(pool_id) = selected_pool.as_deref() { let image_requirement = Self::image_input_requirement( &messages, + Self::image_turn_start(&messages, &context.dialog_turn_id), enable_tools && available_tools.iter().any(|name| name == "analyze_image"), ); let (attempt, _next_client) = if let Some(prepared) = initial_pool_attempt.take() { @@ -4348,7 +4398,7 @@ impl ExecutionEngine { .session_manager .select_latest_matching_token_anchor_for_model( &context.session_id, - &messages, + Self::text_only_anchor_prefix(&messages), &model_id, ) .await; @@ -4605,9 +4655,14 @@ impl ExecutionEngine { .ordered_reminders(); let send_prepended_reminder_tokens = Self::prepended_reminder_tokens_for_pressure(&send_prepended_reminders); - let mut send_pressure = if send_pressure_reusable - && token_pressure.prepended_reminder_tokens == send_prepended_reminder_tokens - { + let same_pressure = send_pressure_reusable + && token_pressure.prepended_reminder_tokens == send_prepended_reminder_tokens; + let mut minimum_non_image_input_tokens = if same_pressure && anchor_details.is_some() { + token_pressure.total_tokens + } else { + 0 + }; + let mut send_pressure = if same_pressure { token_pressure } else { Self::estimate_auto_compression_pressure( @@ -4623,12 +4678,16 @@ impl ExecutionEngine { round_index, send_pressure.total_tokens, context_window ); let before_truncate_tokens = send_pressure.total_tokens; + let before_truncate_len = messages.len(); messages = Self::emergency_truncate_messages( messages, context_window, tool_definitions.as_deref(), send_prepended_reminder_tokens, ); + if messages.len() != before_truncate_len { + minimum_non_image_input_tokens = 0; + } self.session_manager .prune_token_anchors_to_messages(&context.session_id, &messages) .await; @@ -4726,7 +4785,11 @@ impl ExecutionEngine { let analysis_available = enable_tools && available_tools.iter().any(|name| name == "analyze_image"); let send_image_requirement = if selected_pool.is_some() { - Self::image_input_requirement(&messages, analysis_available) + Self::image_input_requirement( + &messages, + Self::image_turn_start(&messages, &context.dialog_turn_id), + analysis_available, + ) } else if !primary_supports_image_understanding && messages.iter().any(|message| { message.metadata.turn_id.as_deref() == Some(context.dialog_turn_id.as_str()) @@ -4760,7 +4823,7 @@ impl ExecutionEngine { &model_fingerprint, selected_pool.is_some(), ); - let ai_messages = Self::build_ai_messages_for_send( + let (ai_messages, image_turn_start) = Self::build_ai_messages_for_send( &request_messages, &ai_client.config.format, context.workspace.as_ref(), @@ -4771,6 +4834,11 @@ impl ExecutionEngine { ) .await?; + round_context.model_request_context.image_turn_start = Some(image_turn_start); + round_context + .model_request_context + .minimum_non_image_input_tokens = minimum_non_image_input_tokens; + let round_lifecycle = active_round_lifecycle.get_or_insert_with(ModelRoundLifecycle::new); round_lifecycle.routing = routing_decision; @@ -5603,6 +5671,26 @@ impl ExecutionEngine { &model_fingerprint, selected_pool.is_some(), ); + let anchor = self + .session_manager + .select_latest_matching_token_anchor_for_model( + &context.session_id, + Self::text_only_anchor_prefix(&finalize_messages), + &model_id, + ) + .await + .selected; + let mut finalize_request_context = model_request_context.clone(); + if let Some(anchor) = anchor { + let (pressure, _) = Self::estimate_auto_compression_pressure_with_anchor( + &finalize_messages, + tool_definitions.as_deref(), + compression_trigger_budget, + Some(&anchor), + Self::prepended_reminder_tokens_for_pressure(&finalize_prepended_reminders), + ); + finalize_request_context.minimum_non_image_input_tokens = pressure.total_tokens; + } let final_round_result = self .run_finalize_round(FinalizeRoundInput { permission_constraints: tool_policy.permission_constraints.clone(), @@ -5615,7 +5703,7 @@ impl ExecutionEngine { round_group_id: finalize_round_group_id.clone(), execution_context_vars: &execution_context_vars, primary_model_facts: &primary_model_facts, - model_request_context: &model_request_context, + model_request_context: &finalize_request_context, prepended_reminders: &finalize_prepended_reminders, messages: &finalize_messages, reminder_text: finalize_reminder, @@ -5649,7 +5737,7 @@ impl ExecutionEngine { round_group_id: finalize_round_group_id.clone(), execution_context_vars: &execution_context_vars, primary_model_facts: &primary_model_facts, - model_request_context: &model_request_context, + model_request_context: &finalize_request_context, prepended_reminders: &finalize_prepended_reminders, messages: &finalize_messages, reminder_text: finalize_reminder, @@ -6164,7 +6252,7 @@ mod tests { } } for provider in ["openai", "responses", "anthropic", "gemini"] { - let messages = ExecutionEngine::build_ai_messages_for_send( + let (messages, _) = ExecutionEngine::build_ai_messages_for_send( &[source.clone()], provider, None, @@ -6203,7 +6291,7 @@ mod tests { assert_eq!((decoded.width(), decoded.height()), (6, 4)); assert_eq!(find_geometry(&wire), Some(observation.clone()), "{provider}: screenshot ref and projection geometry must remain attached to these pixels"); } - let text_only = ExecutionEngine::build_ai_messages_for_send( + let (text_only, _) = ExecutionEngine::build_ai_messages_for_send( &[source.clone()], "openai", None, @@ -6293,7 +6381,7 @@ mod tests { if attempt > 0 { store.add_message("image-limit", Message::user("Continue".into())); } - let messages = ExecutionEngine::build_ai_messages_for_send( + let (messages, _) = ExecutionEngine::build_ai_messages_for_send( &store.get_context_messages("image-limit"), "openai", None, @@ -6361,17 +6449,17 @@ mod tests { let image = crate::agentic::image_analysis::attachments::test_image(); let mut messages = vec![Message::user("Text only".into())]; assert_eq!( - ExecutionEngine::image_input_requirement(&messages, false), + ExecutionEngine::image_input_requirement(&messages, messages.len(), false), Requirement::None ); let user_image = Message::user_multimodal("Inherited image".into(), vec![image.clone()]); messages.push(user_image.clone()); assert_eq!( - ExecutionEngine::image_input_requirement(&messages, true), + ExecutionEngine::image_input_requirement(&messages, messages.len(), true), Requirement::NativeOrAnalysisTool ); assert_eq!( - ExecutionEngine::image_input_requirement(&messages, false), + ExecutionEngine::image_input_requirement(&messages, messages.len(), false), Requirement::Native ); let tool_image = Message::tool_result(ToolResult { @@ -6389,12 +6477,12 @@ mod tests { }); messages.push(tool_image); assert_eq!( - ExecutionEngine::image_input_requirement(&messages, true), + ExecutionEngine::image_input_requirement(&messages, messages.len(), true), Requirement::Native ); messages.push(user_image.clone()); assert_eq!( - ExecutionEngine::image_input_requirement(&messages, true), + ExecutionEngine::image_input_requirement(&messages, messages.len(), true), Requirement::Native ); messages.push(Message::internal_reminder_multimodal( @@ -6404,13 +6492,13 @@ mod tests { )); // Elision advances in batches, so the tool pixels stay in the sent window. assert_eq!( - ExecutionEngine::image_input_requirement(&messages, true), + ExecutionEngine::image_input_requirement(&messages, messages.len(), true), Requirement::Native ); messages.push(user_image.clone()); messages.push(user_image.clone()); assert_eq!( - ExecutionEngine::image_input_requirement(&messages, true), + ExecutionEngine::image_input_requirement(&messages, messages.len(), true), Requirement::Native ); messages.push(Message::internal_reminder_multimodal( @@ -6421,14 +6509,14 @@ mod tests { // The seventh image-bearing message elides the oldest batch, including // the tool pixels, from the same window used for sending. assert_eq!( - ExecutionEngine::image_input_requirement(&messages, true), + ExecutionEngine::image_input_requirement(&messages, messages.len(), true), Requirement::NativeOrAnalysisTool ); let mut hidden = user_image; hidden.metadata.semantic_kind = Some(super::MessageSemanticKind::ComputerUseVerificationScreenshot); assert_eq!( - ExecutionEngine::image_input_requirement(&[hidden], true), + ExecutionEngine::image_input_requirement(&[hidden], 0, true), Requirement::None ); } @@ -6444,7 +6532,7 @@ mod tests { crate::agentic::tools::framework::ToolUseContext::for_tool_listing(None, None); context.agent_type = Some("Claw".into()); assert_eq!( - ExecutionEngine::resolve_image_input_requirement(&messages, false, &context).await, + ExecutionEngine::resolve_image_input_requirement(&messages, 0, false, &context).await, Requirement::Native ); context @@ -6452,12 +6540,13 @@ mod tests { .denied_tool_names .insert("analyze_image".into()); assert_eq!( - ExecutionEngine::resolve_image_input_requirement(&messages, true, &context).await, + ExecutionEngine::resolve_image_input_requirement(&messages, 0, true, &context).await, Requirement::Native ); assert_eq!( ExecutionEngine::resolve_image_input_requirement( &[Message::user("No image".into())], + 0, true, &context ) @@ -6502,7 +6591,11 @@ mod tests { .chain(&visible.deferred_tools) .any(|tool| tool.name() == "analyze_image"); assert_eq!( - ExecutionEngine::image_input_requirement(&messages, analysis_available), + ExecutionEngine::image_input_requirement( + &messages, + messages.len(), + analysis_available + ), super::ImageInputRequirement::NativeOrAnalysisTool, ); } @@ -6531,7 +6624,7 @@ mod tests { .with_turn_id("turn".into()), ]; for provider in ["openai", "anthropic", "responses", "gemini"] { - let native = ExecutionEngine::build_ai_messages_for_send( + let (native, _) = ExecutionEngine::build_ai_messages_for_send( &messages, provider, None, @@ -6561,7 +6654,7 @@ mod tests { ); } } - let text_only = ExecutionEngine::build_ai_messages_for_send( + let (text_only, _) = ExecutionEngine::build_ai_messages_for_send( &messages, "openai", None, @@ -6616,7 +6709,7 @@ mod tests { let image = crate::agentic::image_analysis::attachments::test_image(); let image_message = |index: usize| { Message::user_multimodal(format!("Screenshot {index}"), vec![image.clone()]) - .with_turn_id("turn".into()) + .with_turn_id("earlier".into()) }; let send = |messages: Vec| async move { serde_json::to_value( @@ -6630,7 +6723,8 @@ mod tests { &["stable reminder"], ) .await - .unwrap(), + .unwrap() + .0, ) .unwrap() }; @@ -7779,6 +7873,158 @@ mod tests { assert_eq!(details.expect("anchor details").tail_tokens, tail_tokens); } + #[test] + fn image_projection_reserves_text_using_a_clean_anchor_without_compressing_pixels() { + let image = crate::agentic::image_analysis::attachments::test_image(); + let prefix = vec![ + Message::system("instructions".into()), + Message::user("history".into()), + ]; + let anchor = TokenAnchor::from_request_prefix( + TokenAnchorInput { + session_id: "s".into(), + turn_id: "t".into(), + round_id: "r".into(), + model_id: "m".into(), + input_tokens: 900, + system_tokens_at_anchor: ExecutionEngine::system_tokens_for_pressure(&prefix), + tool_tokens_at_anchor: 0, + prepended_reminder_tokens_at_anchor: 0, + }, + &prefix, + ); + let mut messages = prefix; + messages.push(Message::user_multimodal("inspect".into(), vec![image; 30])); + let available = ExecutionEngine::text_only_anchor_prefix(&messages); + assert_eq!(available.len(), 2); + assert!(anchor.matches_prefix(available)); + let (pressure, _) = ExecutionEngine::estimate_auto_compression_pressure_with_anchor( + &messages, + None, + CompressionTriggerBudget::for_model(2_000, None), + Some(&anchor), + 0, + ); + assert_eq!( + pressure.total_tokens, + 900 + Message::user("inspect".into()).estimate_tokens_with_reasoning(false) + ); + assert!( + messages + .last() + .unwrap() + .estimate_tokens_with_reasoning(false) + > 2_000 + ); + let kept = ExecutionEngine::emergency_truncate_messages(messages.clone(), 2_000, None, 0); + assert_eq!(kept.len(), messages.len()); + } + + #[tokio::test] + async fn image_projection_preserves_all_active_turn_pixels_through_history_batch_elision() { + use super::ImageInputRequirement; + let image = crate::agentic::image_analysis::attachments::test_image(); + let mut messages = vec![ + Message::user_multimodal("earlier".into(), vec![image.clone()]) + .with_turn_id("old".into()), + ]; + messages.push( + Message::tool_result(ToolResult { + tool_id: "read-image".into(), + tool_name: "Read".into(), + effective_tool_name: None, + result_for_assistant: None, + is_error: false, + duration_ms: None, + result: serde_json::json!({}), + image_attachments: Some(vec![crate::util::types::ToolImageAttachment { + mime_type: "image/png".into(), + data_base64: image + .data_url + .as_deref() + .unwrap() + .split_once(',') + .unwrap() + .1 + .into(), + }]), + }) + .with_turn_id("active".into()), + ); + for _ in 0..6 { + messages.push( + Message::user_multimodal("active image".into(), vec![image.clone()]) + .with_turn_id("active".into()), + ); + } + let start = ExecutionEngine::image_turn_start(&messages, "active"); + assert_eq!( + ExecutionEngine::image_input_requirement(&messages, start, true), + ImageInputRequirement::Native + ); + let (outgoing, boundary) = ExecutionEngine::build_ai_messages_for_send( + &messages, + "openai", + None, + None, + "active", + true, + &[], + ) + .await + .unwrap(); + assert_eq!(boundary, 1); + assert!(outgoing[0].content.as_deref().unwrap().contains("omitted")); + assert_eq!( + outgoing[1].tool_image_attachments.as_ref().unwrap().len(), + 1 + ); + assert!(outgoing[2..] + .iter() + .all(|m| m.content.as_deref().unwrap().contains("image_url"))); + } + + #[tokio::test] + async fn image_projection_turn_boundary_uses_emitted_messages_and_real_turn_identity() { + let messages = vec![ + Message::system("system".into()), + Message::internal_reminder(InternalReminderKind::InterruptedContinue, "stale") + .with_turn_id("older".into()), + Message::user("earlier request".into()).with_turn_id("older".into()), + Message::user("verification".into()) + .with_semantic_kind(MessageSemanticKind::ComputerUseVerificationScreenshot) + .with_turn_id("current".into()), + Message::user("inspect".into()).with_turn_id("current".into()), + Message::internal_reminder(InternalReminderKind::FinalizeCacheAnchor, "finish") + .with_turn_id("current".into()), + ]; + let (outgoing, boundary) = ExecutionEngine::build_ai_messages_for_send( + &messages, + "openai", + None, + None, + "current", + true, + &["injected reminder"], + ) + .await + .unwrap(); + assert_eq!(boundary, 3); + assert_eq!(outgoing[boundary].content.as_deref(), Some("inspect")); + let (history, history_only) = ExecutionEngine::build_ai_messages_for_send( + &messages[..3], + "openai", + None, + None, + "current", + true, + &["injected reminder"], + ) + .await + .unwrap(); + assert_eq!(history_only, history.len()); + } + #[test] fn auto_compression_pressure_applies_tool_definition_delta_to_anchor() { let messages = vec![ diff --git a/src/crates/assembly/core/src/agentic/execution/prompt_suggestion.rs b/src/crates/assembly/core/src/agentic/execution/prompt_suggestion.rs index f8e1573636..60842d6eec 100644 --- a/src/crates/assembly/core/src/agentic/execution/prompt_suggestion.rs +++ b/src/crates/assembly/core/src/agentic/execution/prompt_suggestion.rs @@ -70,13 +70,13 @@ async fn prompt_suggestion_enabled() -> bool { /// unchanged, then the suggestion instruction as the only appended message. pub(super) async fn build_prompt_suggestion_messages( request: &PromptSuggestionRequest, -) -> crate::util::errors::OpenBitFunResult> { +) -> crate::util::errors::OpenBitFunResult<(Vec, usize)> { let reminders = request .prepended_reminders .iter() .map(String::as_str) .collect::>(); - let mut ai_messages = ExecutionEngine::build_ai_messages_for_send( + let (mut ai_messages, image_turn_start) = ExecutionEngine::build_ai_messages_for_send( &request.messages, &request.ai_client.config.format, request.workspace.as_ref(), @@ -87,7 +87,7 @@ pub(super) async fn build_prompt_suggestion_messages( ) .await?; ai_messages.push(AIMessage::user(prompt_suggestion_instruction().to_string())); - Ok(ai_messages) + Ok((ai_messages, image_turn_start)) } async fn generate_prompt_suggestion( @@ -161,10 +161,11 @@ where async fn request_prompt_suggestion_response( request: &PromptSuggestionRequest, - ai_messages: Vec, + (ai_messages, image_turn_start): (Vec, usize), trace: Option, ) -> anyhow::Result> { - let context = suggestion_request_context(&request.model_request_context); + let mut context = suggestion_request_context(&request.model_request_context); + context.image_turn_start = Some(image_turn_start); let response = request .ai_client .send_message_once_with_trace_and_request_context( @@ -696,6 +697,7 @@ mod tests { output_schema: Some( serde_json::json!({"type": "object", "properties": {"report": {"type": "string"}}}), ), + ..Default::default() }; let suggestion = suggestion_request_context(&context); assert_eq!( @@ -740,7 +742,7 @@ mod tests { ]; let reminders = vec!["skill listing".to_string()]; let reminder_refs = reminders.iter().map(String::as_str).collect::>(); - let round_messages = ExecutionEngine::build_ai_messages_for_send( + let (round_messages, round_boundary) = ExecutionEngine::build_ai_messages_for_send( &messages, &ai_client.config.format, None, @@ -764,10 +766,11 @@ mod tests { workspace_services: None, attach_images: false, }; - let suggestion_messages = build_prompt_suggestion_messages(&request) + let (suggestion_messages, boundary) = build_prompt_suggestion_messages(&request) .await .expect("suggestion messages"); + assert_eq!(boundary, round_boundary); assert_eq!(suggestion_messages.len(), round_messages.len() + 1); assert_eq!( serde_json::to_value(&suggestion_messages[..round_messages.len()]).unwrap(), diff --git a/src/crates/assembly/core/src/agentic/execution/round_executor.rs b/src/crates/assembly/core/src/agentic/execution/round_executor.rs index 0cc214071f..9e01a9a1e1 100644 --- a/src/crates/assembly/core/src/agentic/execution/round_executor.rs +++ b/src/crates/assembly/core/src/agentic/execution/round_executor.rs @@ -789,6 +789,11 @@ impl RoundExecutor { .cancellation_tokens .get_or_insert_new(&context.dialog_turn_id); + // A calibrated text estimate belongs to the original model and prefix. + // Replay projection can strip signed reasoning before the send. + let calibrated_model = (context.model_request_context.minimum_non_image_input_tokens > 0 + && !crate::infrastructure::ai::channel_client_source::ChannelClientSource::has_nonportable_history(&ai_messages)) + .then(|| (context.model_config_id.clone(), ai_client.config.model.clone())); let channels = context.channel_client_source.clone(); let lineage = context.model_request_context.prompt_cache_route_key.clone(); let mut excluded_channels = Vec::new(); @@ -1121,10 +1126,16 @@ impl RoundExecutor { let request_trace_config = trace_config .clone() .map(|config| config.with_round_attempt(attempt_id.clone(), attempt_number)); + let mut request_context = context.model_request_context.clone(); + if !calibrated_model.as_ref().is_some_and(|(id, model)| { + id == &context.model_config_id && model == &ai_client.config.model + }) { + request_context.minimum_non_image_input_tokens = 0; + } let send_future = ai_client.send_message_stream_once_with_request_context( ai_messages.clone(), tool_definitions.clone(), - Some(context.model_request_context.clone()), + Some(request_context), request_trace_config, ); let send_result = tokio::select! { @@ -3528,11 +3539,25 @@ pub(super) mod tests { image_attachments: None, }) .into(); + let mut followup = super::AIMessage::user("Continue from that result".into()); + if manual { + // The primary's text calibration must not reject pixels on + // the selected backup before its transport is reached. + context.model_request_context.minimum_non_image_input_tokens = 64_000; + let image = crate::agentic::image_analysis::attachments::test_image(); + followup.content = Some( + json!([ + {"type": "text", "text": "Inspect the result"}, + {"type": "image_url", "image_url": {"url": image.data_url.unwrap()}} + ]) + .to_string(), + ); + } let history = vec![ super::AIMessage::user("Save the file".into()), previous, tool, - super::AIMessage::user("Continue from that result".into()), + followup, ]; let before = serde_json::to_value(&history).unwrap(); let mut lifecycle = ModelRoundLifecycle::new(); @@ -3579,6 +3604,9 @@ pub(super) mod tests { assert_eq!(primary.requests.lock().unwrap().len(), usize::from(!manual)); assert_eq!(backup.requests.lock().unwrap().len(), 1); let body = backup.requests.lock().unwrap()[0].to_string(); + if manual { + assert!(body.contains("data:image/png;base64,")); + } assert!( body.contains("channel-fixture"), "complete tool history must reach {format}: {body}" diff --git a/src/crates/assembly/core/src/util/token_counter.rs b/src/crates/assembly/core/src/util/token_counter.rs index 2a1ca12891..d70ae5a820 100644 --- a/src/crates/assembly/core/src/util/token_counter.rs +++ b/src/crates/assembly/core/src/util/token_counter.rs @@ -1,96 +1 @@ -//! Token estimation utility - -use crate::util::types::{Message, ToolDefinition}; - -/// Heuristic: ASCII chars 0.3 token, non-ASCII chars 0.6 token -pub struct TokenCounter; - -impl TokenCounter { - pub fn estimate_tokens(text: &str) -> usize { - if text.is_empty() { - return 0; - } - - let mut token_count: f32 = 0.; - - for c in text.chars() { - if c.is_ascii() { - token_count += 0.3; - } else { - token_count += 0.6; - } - } - - token_count as usize - } - - pub fn estimate_message_tokens(message: &Message) -> usize { - let mut total = 0; - - total += 4; - - if let Some(reasoning_content) = &message.reasoning_content { - total += Self::estimate_tokens(reasoning_content); - } - - if let Some(content) = &message.content { - total += Self::estimate_tokens(content); - } - - if let Some(tool_calls) = &message.tool_calls { - for tool_call in tool_calls { - total += Self::estimate_tokens(&tool_call.name); - total += Self::estimate_tokens(&tool_call.serialized_arguments()); - total += 10; - } - } - - if let Some(name) = &message.name { - total += Self::estimate_tokens(name); - } - - total - } - - pub fn estimate_messages_tokens(messages: &[Message]) -> usize { - let mut total: usize = messages.iter().map(Self::estimate_message_tokens).sum(); - - total += 3; - - total - } - - pub fn estimate_tool_definitions_tokens(tools: &[ToolDefinition]) -> usize { - let mut total = 0; - - for tool in tools { - total += Self::estimate_tokens(&tool.name); - total += Self::estimate_tokens(&tool.description); - - if let Ok(json_str) = serde_json::to_string(&tool.parameters) { - total += Self::estimate_tokens(&json_str); - } - - total += 15; - } - - if !tools.is_empty() { - total += 10; - } - - total - } - - pub fn estimate_request_tokens( - messages: &[Message], - tools: Option<&[ToolDefinition]>, - ) -> usize { - let mut total = Self::estimate_messages_tokens(messages); - - if let Some(tool_defs) = tools { - total += Self::estimate_tool_definitions_tokens(tool_defs); - } - - total - } -} +pub use openbitfun_core_types::token_estimate::TokenCounter; diff --git a/src/crates/contracts/config-contracts/src/types.rs b/src/crates/contracts/config-contracts/src/types.rs index a232ee2a1d..eebf49701d 100644 --- a/src/crates/contracts/config-contracts/src/types.rs +++ b/src/crates/contracts/config-contracts/src/types.rs @@ -2,6 +2,7 @@ //! //! Defines all configuration-related types shared between backend and frontend. +pub use openbitfun_core_types::token_estimate::automatic_max_output_tokens; use openbitfun_core_types::{product_identity, ToolPresentationMode, WorktreeSettings}; pub use openbitfun_core_types::{ ImageDialect, ReasoningConfig, ReasoningPreset, ReasoningPresetAction, @@ -1882,22 +1883,6 @@ pub type AgentSubagentOverrideConfig = HashMap u32 { - let quarter_context = context_window / 4; - AUTOMATIC_MAX_OUTPUT_TOKEN_TIERS - .iter() - .rev() - .copied() - .filter(|tier| *tier != 64_000 || context_window >= MAX_OUTPUT_64K_MIN_CONTEXT_WINDOW) - .find(|tier| *tier <= quarter_context) - .unwrap_or(quarter_context) -} /// A configured output cap may use up to 40% of the model context window. pub fn is_valid_configured_max_output_tokens(context_window: u32, max_tokens: u32) -> bool { diff --git a/src/crates/contracts/core-types/src/ai.rs b/src/crates/contracts/core-types/src/ai.rs index efc7224ea1..bb8bf8a151 100644 --- a/src/crates/contracts/core-types/src/ai.rs +++ b/src/crates/contracts/core-types/src/ai.rs @@ -660,6 +660,12 @@ pub struct AIConfig { /// in this contract. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct ModelRequestContext { + /// First outgoing message in the active turn, after host-only messages and reminders + /// have been projected. A boundary at the end denotes a history-only request. + pub image_turn_start: Option, + /// Non-image input estimate calibrated from a matching text-only provider prefix. + /// Zero denotes that no comparable provider usage is available for this request. + pub minimum_non_image_input_tokens: usize, /// Opaque execution-lifetime identity, distinct from shareable prompt-cache lineage. /// Absence means a standalone request with no reusable transport continuation. pub conversation_scope: Option>, diff --git a/src/crates/contracts/core-types/src/lib.rs b/src/crates/contracts/core-types/src/lib.rs index 1f4d44fff1..d5c2559b97 100644 --- a/src/crates/contracts/core-types/src/lib.rs +++ b/src/crates/contracts/core-types/src/lib.rs @@ -19,6 +19,7 @@ pub mod session_usage; pub mod speech; pub mod subscription; pub mod surface; +pub mod token_estimate; pub mod tool_image_attachment; pub mod tool_presentation; pub mod worktree; diff --git a/src/crates/contracts/core-types/src/token_estimate.rs b/src/crates/contracts/core-types/src/token_estimate.rs new file mode 100644 index 0000000000..73f227cf44 --- /dev/null +++ b/src/crates/contracts/core-types/src/token_estimate.rs @@ -0,0 +1,114 @@ +//! Shared request token estimates and output reserves. + +use crate::{Message, ToolDefinition}; + +pub const INPUT_SAFETY_RESERVE: usize = 10_000; +const AUTOMATIC_MAX_OUTPUT_TOKEN_TIERS: [u32; 5] = [8_000, 16_000, 24_000, 32_000, 64_000]; +const MAX_OUTPUT_64K_MIN_CONTEXT_WINDOW: u32 = 400_000; + +/// Chooses the largest supported output tier that does not exceed one quarter +/// of the model context window. The 64k tier requires a context window of at +/// least 400k. +pub fn automatic_max_output_tokens(context_window: u32) -> u32 { + let quarter_context = context_window / 4; + AUTOMATIC_MAX_OUTPUT_TOKEN_TIERS + .iter() + .rev() + .copied() + .filter(|tier| *tier != 64_000 || context_window >= MAX_OUTPUT_64K_MIN_CONTEXT_WINDOW) + .find(|tier| *tier <= quarter_context) + .unwrap_or(quarter_context) +} + +/// Heuristic: ASCII chars 0.3 token, non-ASCII chars 0.6 token +pub struct TokenCounter; + +impl TokenCounter { + pub fn estimate_tokens(text: &str) -> usize { + if text.is_empty() { + return 0; + } + + let mut token_count: f32 = 0.; + + for c in text.chars() { + if c.is_ascii() { + token_count += 0.3; + } else { + token_count += 0.6; + } + } + + token_count as usize + } + + pub fn estimate_message_tokens(message: &Message) -> usize { + Self::estimate_message_overhead(message) + + message.content.as_deref().map_or(0, Self::estimate_tokens) + } + + /// Message envelope, reasoning, tool calls and name, excluding content. + pub fn estimate_message_overhead(message: &Message) -> usize { + let mut total = 4; + + if let Some(reasoning_content) = &message.reasoning_content { + total += Self::estimate_tokens(reasoning_content); + } + + if let Some(tool_calls) = &message.tool_calls { + for tool_call in tool_calls { + total += Self::estimate_tokens(&tool_call.name); + total += Self::estimate_tokens(&tool_call.serialized_arguments()); + total += 10; + } + } + + if let Some(name) = &message.name { + total += Self::estimate_tokens(name); + } + + total + } + + pub fn estimate_messages_tokens(messages: &[Message]) -> usize { + let mut total: usize = messages.iter().map(Self::estimate_message_tokens).sum(); + + total += 3; + + total + } + + pub fn estimate_tool_definitions_tokens(tools: &[ToolDefinition]) -> usize { + let mut total = 0; + + for tool in tools { + total += Self::estimate_tokens(&tool.name); + total += Self::estimate_tokens(&tool.description); + + if let Ok(json_str) = serde_json::to_string(&tool.parameters) { + total += Self::estimate_tokens(&json_str); + } + + total += 15; + } + + if !tools.is_empty() { + total += 10; + } + + total + } + + pub fn estimate_request_tokens( + messages: &[Message], + tools: Option<&[ToolDefinition]>, + ) -> usize { + let mut total = Self::estimate_messages_tokens(messages); + + if let Some(tool_defs) = tools { + total += Self::estimate_tool_definitions_tokens(tool_defs); + } + + total + } +}