mirror of
https://github.com/openai/codex.git
synced 2026-11-27 23:31:09 +00:00
Account for file images in context budgets and Guardian reviews (#46072)
## Why File images contributed zero to history and compaction token estimates and were dropped from Guardian context. This undercounted context usage and omitted image evidence from reviews. ## What changed - Estimate file images using the fixed resized-image cost, or 10,000 patch tokens for `original` detail because file references do not expose dimensions. - Charge file images against remote compaction and Guardian request budgets. - Preserve file images from user messages and tool outputs through Guardian selection and delivery, and deduplicate review images by file ID. - Apply transcript image count and byte limits to both reference types, counting file ID bytes rather than referenced file contents. ## Testing Add coverage for file-image estimates, selection limits, delivery, and compaction retention. Extend Guardian tests to verify file-image evidence reaches reviews and uploaded original-detail images trigger reviewer-history compaction. GitOrigin-RevId: ee024204dcbe16e277fea9347c6a4d7fc120e18d
This commit is contained in:
1 parent
ce03f22af6
commit
b974893c90
18 files changed
+481
-199
No files matched your search
@@ -25,6 +25,15 @@ fn image() -> ContentItem {
|
||||
}
|
||||
}
|
||||
|
||||
fn file_image() -> ContentItem {
|
||||
ContentItem::InputImage {
|
||||
image: ImageReference::File {
|
||||
file_id: "file_123".to_string(),
|
||||
},
|
||||
detail: Some(codex_protocol::models::ImageDetail::Original),
|
||||
}
|
||||
}
|
||||
|
||||
fn text(value: &str) -> ContentItem {
|
||||
ContentItem::InputText {
|
||||
text: value.to_string(),
|
||||
@@ -45,21 +54,23 @@ fn trim(items: Vec<ResponseItem>, max_tokens: usize) -> Vec<ResponseItem> {
|
||||
#[test]
|
||||
fn image_only_boundary_is_atomic_and_does_not_backfill_older_messages() {
|
||||
let newest = message(vec![text("new")]);
|
||||
let items = vec![
|
||||
message(vec![text("old")]),
|
||||
message(vec![image()]),
|
||||
newest.clone(),
|
||||
];
|
||||
let image_tokens = images::content_item_token_count(&image());
|
||||
for (max_tokens, expected) in [
|
||||
(
|
||||
image_tokens + 1,
|
||||
vec![message(vec![image()]), newest.clone()],
|
||||
),
|
||||
(image_tokens, vec![newest.clone()]),
|
||||
(1, vec![newest]),
|
||||
] {
|
||||
assert_eq!(trim(items.clone(), max_tokens), expected);
|
||||
for image in [image(), file_image()] {
|
||||
let items = vec![
|
||||
message(vec![text("old")]),
|
||||
message(vec![image.clone()]),
|
||||
newest.clone(),
|
||||
];
|
||||
let image_tokens = images::content_item_token_count(&image);
|
||||
for (max_tokens, expected) in [
|
||||
(
|
||||
image_tokens + 1,
|
||||
vec![message(vec![image.clone()]), newest.clone()],
|
||||
),
|
||||
(image_tokens, vec![newest.clone()]),
|
||||
(1, vec![newest.clone()]),
|
||||
] {
|
||||
assert_eq!(trim(items.clone(), max_tokens), expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
use crate::context_manager::estimate_image_bytes;
|
||||
use crate::context_manager::estimate_image_reference_bytes;
|
||||
use codex_context_fragments::AnnotatedContent;
|
||||
use codex_context_fragments::set_annotated_content;
|
||||
use codex_context_fragments::to_annotated_content;
|
||||
use codex_history::ResponseItemEnvelope;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ImageReference;
|
||||
use codex_protocol::models::is_image_close_tag_text;
|
||||
use codex_protocol::models::is_image_open_tag_text;
|
||||
use codex_protocol::models::is_local_image_open_tag_text;
|
||||
@@ -18,17 +17,10 @@ pub(super) fn content_item_token_count(item: &ContentItem) -> usize {
|
||||
ContentItem::InputText { text } | ContentItem::OutputText { text } => {
|
||||
approx_token_count(text)
|
||||
}
|
||||
ContentItem::InputImage {
|
||||
image: ImageReference::Inline { image_url },
|
||||
detail,
|
||||
} => usize::try_from(approx_tokens_from_byte_count_i64(estimate_image_bytes(
|
||||
image_url, *detail,
|
||||
)))
|
||||
ContentItem::InputImage { image, detail } => usize::try_from(
|
||||
approx_tokens_from_byte_count_i64(estimate_image_reference_bytes(image, *detail)),
|
||||
)
|
||||
.unwrap_or(usize::MAX),
|
||||
ContentItem::InputImage {
|
||||
image: ImageReference::File { .. },
|
||||
..
|
||||
} => 0,
|
||||
ContentItem::InputAudio { .. } => 0,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -890,6 +890,7 @@ fn estimate_encrypted_function_output_length(encoded_len: usize) -> usize {
|
||||
/// Returns the same coarse, model-visible token estimate used for full history estimates.
|
||||
///
|
||||
/// Counts content directly, excluding transport IDs, metadata, and outer JSON escaping.
|
||||
/// Original-detail file images use the maximum patch count.
|
||||
pub(crate) fn estimate_item_token_count(item: &ResponseItem) -> i64 {
|
||||
let model_visible_bytes = estimate_response_item_model_visible_bytes(item);
|
||||
approx_tokens_from_byte_count_i64(model_visible_bytes)
|
||||
@@ -918,7 +919,6 @@ static ORIGINAL_IMAGE_ESTIMATE_CACHE: LazyLock<BlockingLruCache<[u8; 20], Option
|
||||
});
|
||||
|
||||
fn estimate_response_item_model_visible_bytes(item: &ResponseItem) -> i64 {
|
||||
// TODO(kc) Account for file-backed image size after its token-cost contract is defined.
|
||||
match item {
|
||||
ResponseItem::Message { content, .. } => content
|
||||
.iter()
|
||||
@@ -926,14 +926,9 @@ fn estimate_response_item_model_visible_bytes(item: &ResponseItem) -> i64 {
|
||||
ContentItem::InputText { text } | ContentItem::OutputText { text } => {
|
||||
text_bytes(text)
|
||||
}
|
||||
ContentItem::InputImage {
|
||||
image: ImageReference::Inline { image_url },
|
||||
detail,
|
||||
} => estimate_image_bytes(image_url, *detail),
|
||||
ContentItem::InputImage {
|
||||
image: ImageReference::File { .. },
|
||||
..
|
||||
} => 0,
|
||||
ContentItem::InputImage { image, detail } => {
|
||||
estimate_image_reference_bytes(image, *detail)
|
||||
}
|
||||
ContentItem::InputAudio { audio_url } => estimate_audio_bytes(audio_url),
|
||||
})
|
||||
.fold(0i64, i64::saturating_add),
|
||||
@@ -1112,8 +1107,8 @@ fn estimate_original_image_bytes(image_url: &str) -> Option<i64> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Shared image estimate, excluding message framing.
|
||||
pub(crate) fn estimate_image_bytes(image_url: &str, detail: Option<ImageDetail>) -> i64 {
|
||||
/// Inline image estimate, excluding the data URL prefix and message framing.
|
||||
fn estimate_image_bytes(image_url: &str, detail: Option<ImageDetail>) -> i64 {
|
||||
match detail {
|
||||
Some(ImageDetail::Original) => {
|
||||
estimate_original_image_bytes(image_url).unwrap_or(RESIZED_IMAGE_BYTES_ESTIMATE)
|
||||
@@ -1122,6 +1117,21 @@ pub(crate) fn estimate_image_bytes(image_url: &str, detail: Option<ImageDetail>)
|
||||
}
|
||||
}
|
||||
|
||||
/// Image estimate for callers that only have the reference. Original-detail file images use the
|
||||
/// maximum patch count because their dimensions are not available from the reference.
|
||||
pub(crate) fn estimate_image_reference_bytes(
|
||||
image: &ImageReference,
|
||||
detail: Option<ImageDetail>,
|
||||
) -> i64 {
|
||||
match image {
|
||||
ImageReference::Inline { image_url } => estimate_image_bytes(image_url, detail),
|
||||
ImageReference::File { .. } if detail == Some(ImageDetail::Original) => {
|
||||
i64::try_from(approx_bytes_for_tokens(ORIGINAL_IMAGE_MAX_PATCHES)).unwrap_or(i64::MAX)
|
||||
}
|
||||
ImageReference::File { .. } => RESIZED_IMAGE_BYTES_ESTIMATE,
|
||||
}
|
||||
}
|
||||
|
||||
fn estimate_audio_bytes(audio_url: &str) -> i64 {
|
||||
i64::try_from(approx_bytes_for_tokens(estimate_audio_token_count(
|
||||
audio_url,
|
||||
@@ -1136,14 +1146,9 @@ fn estimate_function_output_bytes(output: &FunctionCallOutputBody) -> i64 {
|
||||
.iter()
|
||||
.map(|part| match part {
|
||||
FunctionCallOutputContentItem::InputText { text } => text_bytes(text),
|
||||
FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::Inline { image_url },
|
||||
detail,
|
||||
} => estimate_image_bytes(image_url, *detail),
|
||||
FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::File { .. },
|
||||
..
|
||||
} => 0,
|
||||
FunctionCallOutputContentItem::InputImage { image, detail } => {
|
||||
estimate_image_reference_bytes(image, *detail)
|
||||
}
|
||||
FunctionCallOutputContentItem::InputAudio { audio_url } => {
|
||||
estimate_audio_bytes(audio_url)
|
||||
}
|
||||
|
||||
@@ -2577,8 +2577,39 @@ fn image_data_url_payload_does_not_dominate_message_estimate() {
|
||||
assert!(estimated > text_only_estimated);
|
||||
}
|
||||
|
||||
/// File images use the fixed estimate for normal detail and the maximum patch count for original.
|
||||
#[test]
|
||||
fn image_data_url_payload_does_not_dominate_function_call_output_estimate() {
|
||||
fn file_images_use_detail_appropriate_estimates() {
|
||||
let item = ResponseItem::Message {
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![
|
||||
ContentItem::InputImage {
|
||||
image: ImageReference::File {
|
||||
file_id: "file_high".to_string(),
|
||||
},
|
||||
detail: Some(ImageDetail::High),
|
||||
},
|
||||
ContentItem::InputImage {
|
||||
image: ImageReference::File {
|
||||
file_id: "file_original".to_string(),
|
||||
},
|
||||
detail: Some(ImageDetail::Original),
|
||||
},
|
||||
],
|
||||
phase: None,
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
};
|
||||
|
||||
let estimated = estimate_response_item_model_visible_bytes(&item);
|
||||
let expected = RESIZED_IMAGE_BYTES_ESTIMATE
|
||||
.saturating_add(approx_bytes_for_tokens(/*tokens*/ 10_000) as i64);
|
||||
|
||||
assert_eq!(estimated, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_call_output_estimates_inline_and_file_images() {
|
||||
let payload = "B".repeat(50_000);
|
||||
let image_url = format!("data:image/png;base64,{payload}");
|
||||
let item = ResponseItem::FunctionCallOutput {
|
||||
@@ -2594,14 +2625,22 @@ fn image_data_url_payload_does_not_dominate_function_call_output_estimate() {
|
||||
image: ImageReference::Inline { image_url },
|
||||
detail: Some(DEFAULT_IMAGE_DETAIL),
|
||||
},
|
||||
FunctionCallOutputContentItem::InputImage {
|
||||
image: ImageReference::File {
|
||||
file_id: "file_original".to_string(),
|
||||
},
|
||||
detail: Some(ImageDetail::Original),
|
||||
},
|
||||
]),
|
||||
internal_chat_message_metadata_passthrough: None,
|
||||
};
|
||||
|
||||
let raw_len = serde_json::to_string(&item).unwrap().len() as i64;
|
||||
let estimated = estimate_response_item_model_visible_bytes(&item);
|
||||
let expected =
|
||||
"call-abc".len() as i64 + "Screenshot captured".len() as i64 + RESIZED_IMAGE_BYTES_ESTIMATE;
|
||||
let expected = "call-abc".len() as i64
|
||||
+ "Screenshot captured".len() as i64
|
||||
+ RESIZED_IMAGE_BYTES_ESTIMATE
|
||||
+ approx_bytes_for_tokens(/*tokens*/ 10_000) as i64;
|
||||
|
||||
assert_eq!(estimated, expected);
|
||||
assert!(estimated < raw_len);
|
||||
|
||||
@@ -4,6 +4,6 @@ pub(crate) mod updates;
|
||||
|
||||
pub(crate) use history::ContextManager;
|
||||
pub(crate) use history::HistoryReplacement;
|
||||
pub(crate) use history::estimate_image_bytes;
|
||||
pub(crate) use history::estimate_image_reference_bytes;
|
||||
pub(crate) use history::estimate_item_token_count;
|
||||
pub(crate) use history::is_user_turn_boundary;
|
||||
@@ -508,20 +508,26 @@ async fn run_review_on_session(
|
||||
.any(|(_, cost)| cost.image_count > 0)
|
||||
{
|
||||
let reviewer_history = review_session.session.clone_history().await;
|
||||
let reviewer_image_urls = reviewer_history
|
||||
.raw_items()
|
||||
.flat_map(|item| match item {
|
||||
ResponseItem::Message { content, .. } => content.as_slice(),
|
||||
_ => &[],
|
||||
})
|
||||
.filter_map(|item| match item {
|
||||
ContentItem::InputImage {
|
||||
image: ImageReference::Inline { image_url },
|
||||
..
|
||||
} => Some(image_url.as_str()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<HashSet<_>>();
|
||||
let mut reviewer_image_urls = HashSet::new();
|
||||
let mut reviewer_file_ids = HashSet::new();
|
||||
for item in reviewer_history.raw_items() {
|
||||
let ResponseItem::Message { content, .. } = item else {
|
||||
continue;
|
||||
};
|
||||
for item in content {
|
||||
let ContentItem::InputImage { image, .. } = item else {
|
||||
continue;
|
||||
};
|
||||
match image {
|
||||
ImageReference::Inline { image_url } => {
|
||||
reviewer_image_urls.insert(image_url.as_str());
|
||||
}
|
||||
ImageReference::File { file_id } => {
|
||||
reviewer_file_ids.insert(file_id.as_str());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let context_window = model_info.resolved_context_window().map(|supported| {
|
||||
params
|
||||
.spawn_config
|
||||
@@ -542,7 +548,7 @@ async fn run_review_on_session(
|
||||
} else {
|
||||
ImagePreparationMode::DetailBased
|
||||
};
|
||||
prompt_items.context.retain_images(|image_url, detail| {
|
||||
prompt_items.context.retain_images(|image, detail| {
|
||||
*detail = match normalize_output_image_detail(&model_info, *detail) {
|
||||
_ if mode == ImagePreparationMode::UnifiedBudget => {
|
||||
Some(ImageDetail::Original)
|
||||
@@ -550,15 +556,23 @@ async fn run_review_on_session(
|
||||
Some(ImageDetail::Low) => Some(ImageDetail::High),
|
||||
detail => detail,
|
||||
};
|
||||
let prepared_image_url = match resize_image(image_url, detail, mode) {
|
||||
Ok(Some(prepared)) => Cow::Owned(prepared.into_data_url()),
|
||||
Ok(None) => Cow::Borrowed(image_url),
|
||||
Err(error) => {
|
||||
warn!(%error, "failed to prepare guardian review image");
|
||||
return false;
|
||||
match image {
|
||||
ImageReference::Inline { image_url } => {
|
||||
let prepared_image_url = match resize_image(image_url, detail, mode)
|
||||
{
|
||||
Ok(Some(prepared)) => Cow::Owned(prepared.into_data_url()),
|
||||
Ok(None) => Cow::Borrowed(image_url),
|
||||
Err(error) => {
|
||||
warn!(%error, "failed to prepare guardian review image");
|
||||
return false;
|
||||
}
|
||||
};
|
||||
!reviewer_image_urls.contains(prepared_image_url.as_str())
|
||||
}
|
||||
};
|
||||
!reviewer_image_urls.contains(prepared_image_url.as_ref())
|
||||
ImageReference::File { file_id } => {
|
||||
!reviewer_file_ids.contains(file_id.as_str())
|
||||
}
|
||||
}
|
||||
});
|
||||
let prompt: ResponseItem =
|
||||
ResponseInputItem::from(prompt_items.context.clone().into_user_inputs()?)
|
||||
|
||||
Reference in new issue
Block a user