mirror of
https://github.com/openai/codex.git
synced 2026-12-06 01:10:58 +00:00
chore: change compact messages structure
This commit is contained in:
@@ -15,7 +15,6 @@ use crate::protocol::TaskStartedEvent;
|
||||
use crate::protocol::TurnContextItem;
|
||||
use crate::truncate::truncate_middle;
|
||||
use crate::util::backoff;
|
||||
use askama::Template;
|
||||
use codex_protocol::items::TurnItem;
|
||||
use codex_protocol::models::ContentItem;
|
||||
use codex_protocol::models::ResponseInputItem;
|
||||
@@ -24,17 +23,11 @@ use codex_protocol::protocol::RolloutItem;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
use futures::prelude::*;
|
||||
use tracing::error;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub const SUMMARIZATION_PROMPT: &str = include_str!("../../templates/compact/prompt.md");
|
||||
const COMPACT_USER_MESSAGE_MAX_TOKENS: usize = 20_000;
|
||||
|
||||
#[derive(Template)]
|
||||
#[template(path = "compact/history_bridge.md", escape = "none")]
|
||||
struct HistoryBridgeTemplate<'a> {
|
||||
user_messages_text: &'a str,
|
||||
summary_text: &'a str,
|
||||
}
|
||||
|
||||
pub(crate) async fn run_inline_auto_compact_task(
|
||||
sess: Arc<Session>,
|
||||
turn_context: Arc<TurnContext>,
|
||||
@@ -219,33 +212,52 @@ fn build_compacted_history_with_limit(
|
||||
summary_text: &str,
|
||||
max_bytes: usize,
|
||||
) -> Vec<ResponseItem> {
|
||||
let mut user_messages_text = if user_messages.is_empty() {
|
||||
"(none)".to_string()
|
||||
} else {
|
||||
user_messages.join("\n\n")
|
||||
};
|
||||
// Truncate the concatenated prior user messages so the bridge message
|
||||
// stays well under the context window (approx. 4 bytes/token).
|
||||
if user_messages_text.len() > max_bytes {
|
||||
user_messages_text = truncate_middle(&user_messages_text, max_bytes).0;
|
||||
let mut selected_messages: Vec<String> = Vec::new();
|
||||
if max_bytes > 0 {
|
||||
let mut remaining = max_bytes;
|
||||
for message in user_messages.iter().rev() {
|
||||
if remaining == 0 {
|
||||
break;
|
||||
}
|
||||
if message.len() <= remaining {
|
||||
selected_messages.push(message.clone());
|
||||
remaining = remaining.saturating_sub(message.len());
|
||||
} else {
|
||||
let (truncated, _) = truncate_middle(message, remaining);
|
||||
selected_messages.push(truncated);
|
||||
break;
|
||||
}
|
||||
}
|
||||
selected_messages.reverse();
|
||||
}
|
||||
|
||||
for message in selected_messages {
|
||||
history.push(ResponseItem::Message {
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![ContentItem::InputText { text: message }],
|
||||
});
|
||||
}
|
||||
|
||||
let summary_text = if summary_text.is_empty() {
|
||||
"(no summary available)".to_string()
|
||||
} else {
|
||||
summary_text.to_string()
|
||||
};
|
||||
let Ok(bridge) = HistoryBridgeTemplate {
|
||||
user_messages_text: &user_messages_text,
|
||||
summary_text: &summary_text,
|
||||
}
|
||||
.render() else {
|
||||
return vec![];
|
||||
};
|
||||
history.push(ResponseItem::Message {
|
||||
|
||||
let call_id = Uuid::new_v4().to_string();
|
||||
history.push(ResponseItem::CustomToolCall {
|
||||
id: None,
|
||||
role: "user".to_string(),
|
||||
content: vec![ContentItem::InputText { text: bridge }],
|
||||
status: Some("completed".to_string()),
|
||||
call_id: call_id.clone(),
|
||||
name: "compactor".to_string(),
|
||||
input: String::new(),
|
||||
});
|
||||
history.push(ResponseItem::CustomToolCallOutput {
|
||||
call_id,
|
||||
output: summary_text,
|
||||
});
|
||||
|
||||
history
|
||||
}
|
||||
|
||||
@@ -384,30 +396,40 @@ mod tests {
|
||||
"SUMMARY",
|
||||
max_bytes,
|
||||
);
|
||||
assert_eq!(history.len(), 3);
|
||||
|
||||
// Expect exactly one bridge message added to history (plus any initial context we provided, which is none).
|
||||
assert_eq!(history.len(), 1);
|
||||
let truncated_message = &history[0];
|
||||
let tool_call = &history[1];
|
||||
let tool_output = &history[2];
|
||||
|
||||
// Extract the text content of the bridge message.
|
||||
let bridge_text = match &history[0] {
|
||||
let truncated_text = match truncated_message {
|
||||
ResponseItem::Message { role, content, .. } if role == "user" => {
|
||||
content_items_to_text(content).unwrap_or_default()
|
||||
}
|
||||
other => panic!("unexpected item in history: {other:?}"),
|
||||
};
|
||||
|
||||
// The bridge should contain the truncation marker and not the full original payload.
|
||||
assert!(
|
||||
bridge_text.contains("tokens truncated"),
|
||||
"expected truncation marker in bridge message"
|
||||
truncated_text.contains("tokens truncated"),
|
||||
"expected truncation marker in truncated user message"
|
||||
);
|
||||
assert!(
|
||||
!bridge_text.contains(&big),
|
||||
"bridge should not include the full oversized user text"
|
||||
);
|
||||
assert!(
|
||||
bridge_text.contains("SUMMARY"),
|
||||
"bridge should include the provided summary text"
|
||||
!truncated_text.contains(&big),
|
||||
"truncated user message should not include the full oversized user text"
|
||||
);
|
||||
|
||||
match tool_call {
|
||||
ResponseItem::CustomToolCall { name, .. } => {
|
||||
assert_eq!(name, "compactor");
|
||||
}
|
||||
other => panic!("expected CustomToolCall, got {other:?}"),
|
||||
}
|
||||
|
||||
match tool_output {
|
||||
ResponseItem::CustomToolCallOutput { output, .. } => {
|
||||
assert_eq!(output, "SUMMARY");
|
||||
}
|
||||
other => panic!("expected CustomToolCallOutput, got {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
You were originally given instructions from a user over one or more turns. Here were the user messages:
|
||||
|
||||
{{ user_messages_text }}
|
||||
|
||||
Another language model started to solve this problem and produced a summary of its thinking process. You also have access to the state of the tools that were used by that language model. Use this to build on the work that has already been done and avoid duplicating work. Here is the summary produced by the other language model, use the information in this summary to assist with your own analysis:
|
||||
|
||||
{{ summary_text }}
|
||||
@@ -12,6 +12,7 @@ use codex_protocol::user_input::UserInput;
|
||||
use core_test_support::load_default_config_for_test;
|
||||
use core_test_support::skip_if_no_network;
|
||||
use core_test_support::wait_for_event;
|
||||
use std::collections::HashSet;
|
||||
use tempfile::TempDir;
|
||||
|
||||
use codex_core::codex::compact::SUMMARIZATION_PROMPT;
|
||||
@@ -163,7 +164,7 @@ async fn summarize_context_three_requests_and_instructions() {
|
||||
"expected summarize trigger, got `{text2}`"
|
||||
);
|
||||
|
||||
// Third request must contain the refreshed instructions, bridge summary message and new user msg.
|
||||
// Third request must contain the refreshed instructions, compacted user history, and new user message.
|
||||
let input3 = body3.get("input").and_then(|v| v.as_array()).unwrap();
|
||||
|
||||
assert!(
|
||||
@@ -171,16 +172,58 @@ async fn summarize_context_three_requests_and_instructions() {
|
||||
"expected refreshed context and new user message in third request"
|
||||
);
|
||||
|
||||
// Collect all (role, text) message tuples.
|
||||
let mut messages: Vec<(String, String)> = Vec::new();
|
||||
let mut compactor_call_ids: HashSet<String> = HashSet::new();
|
||||
let mut compactor_output: Option<String> = None;
|
||||
|
||||
for item in input3 {
|
||||
if item["type"].as_str() == Some("message") {
|
||||
let role = item["role"].as_str().unwrap_or_default().to_string();
|
||||
let text = item["content"][0]["text"]
|
||||
.as_str()
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
messages.push((role, text));
|
||||
match item.get("type").and_then(|v| v.as_str()) {
|
||||
Some("message") => {
|
||||
let role = item
|
||||
.get("role")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
let text = item
|
||||
.get("content")
|
||||
.and_then(|v| v.as_array())
|
||||
.and_then(|arr| arr.first())
|
||||
.and_then(|entry| entry.get("text"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
messages.push((role, text));
|
||||
}
|
||||
Some("custom_tool_call") => {
|
||||
let name = item
|
||||
.get("name")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or_default();
|
||||
if name == "compactor" {
|
||||
let call_id = item
|
||||
.get("call_id")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
compactor_call_ids.insert(call_id);
|
||||
}
|
||||
}
|
||||
Some("custom_tool_call_output") => {
|
||||
let output = item
|
||||
.get("output")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
let call_id = item
|
||||
.get("call_id")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
if compactor_call_ids.contains(&call_id) && compactor_output.is_none() {
|
||||
compactor_output = Some(output);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,22 +236,18 @@ async fn summarize_context_three_requests_and_instructions() {
|
||||
.any(|(r, t)| r == "user" && t == THIRD_USER_MSG),
|
||||
"third request should include the new user message"
|
||||
);
|
||||
let Some((_, bridge_text)) = messages.iter().find(|(role, text)| {
|
||||
role == "user"
|
||||
&& (text.contains("Here were the user messages")
|
||||
|| text.contains("Here are all the user messages"))
|
||||
&& text.contains(SUMMARY_TEXT)
|
||||
}) else {
|
||||
panic!("expected a bridge message containing the summary");
|
||||
};
|
||||
assert!(
|
||||
bridge_text.contains("hello world"),
|
||||
"bridge should capture earlier user messages"
|
||||
messages
|
||||
.iter()
|
||||
.any(|(r, t)| r == "user" && t == "hello world"),
|
||||
"third request should include the original user message"
|
||||
);
|
||||
assert!(
|
||||
!bridge_text.contains(SUMMARIZATION_PROMPT),
|
||||
"bridge text should not echo the summarize trigger"
|
||||
!compactor_call_ids.is_empty(),
|
||||
"expected a compactor tool call"
|
||||
);
|
||||
let compactor_output = compactor_output.expect("expected a compactor tool call output");
|
||||
assert_eq!(compactor_output, SUMMARY_TEXT);
|
||||
assert!(
|
||||
!messages
|
||||
.iter()
|
||||
|
||||
@@ -102,6 +102,38 @@ async fn compact_resume_and_fork_preserve_model_history_view() {
|
||||
|
||||
// 3. Capture the requests to the model and validate the history slices.
|
||||
let requests = gather_request_bodies(&server).await;
|
||||
for (idx, request) in requests.iter().enumerate() {
|
||||
if let Some(input) = request.get("input").and_then(|v| v.as_array()) {
|
||||
println!("request {idx}:");
|
||||
for item in input {
|
||||
let item_type = item.get("type").and_then(|v| v.as_str()).unwrap_or("<unknown>");
|
||||
let role = item.get("role").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let name = item.get("name").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let text_full = item
|
||||
.get("content")
|
||||
.and_then(|v| v.as_array())
|
||||
.and_then(|arr| arr.first())
|
||||
.and_then(|entry| entry.get("text"))
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("");
|
||||
let text = if text_full.len() > 60 {
|
||||
format!("{}…", &text_full[..60])
|
||||
} else {
|
||||
text_full.to_string()
|
||||
};
|
||||
let output_full = item.get("output").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let output = if output_full.len() > 60 {
|
||||
format!("{}…", &output_full[..60])
|
||||
} else {
|
||||
output_full.to_string()
|
||||
};
|
||||
let call_id = item.get("call_id").and_then(|v| v.as_str()).unwrap_or("");
|
||||
println!(
|
||||
" type={item_type} role={role} name={name} call_id={call_id} text={text:?} output={output:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// input after compact is a prefix of input after resume/fork
|
||||
let input_after_compact = json!(requests[requests.len() - 3]["input"]);
|
||||
@@ -155,6 +187,37 @@ async fn compact_resume_and_fork_preserve_model_history_view() {
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
let expected_model = OPENAI_DEFAULT_MODEL;
|
||||
let extract_compactor_items = |request: &Value| -> (Value, Value) {
|
||||
let mut call = None;
|
||||
let mut output = None;
|
||||
if let Some(input) = request.get("input").and_then(|v| v.as_array()) {
|
||||
for item in input {
|
||||
match item.get("type").and_then(|v| v.as_str()) {
|
||||
Some("custom_tool_call")
|
||||
if item
|
||||
.get("name")
|
||||
.and_then(|v| v.as_str())
|
||||
== Some("compactor") =>
|
||||
{
|
||||
call = Some(item.clone());
|
||||
}
|
||||
Some("custom_tool_call_output") => {
|
||||
output = Some(item.clone());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let call = call.expect("expected compactor call");
|
||||
let output = output.expect("expected compactor output");
|
||||
(call, output)
|
||||
};
|
||||
let (compactor_call_after_compact, compactor_output_after_compact) =
|
||||
extract_compactor_items(&requests[2]);
|
||||
let (compactor_call_after_resume, compactor_output_after_resume) =
|
||||
extract_compactor_items(&requests[3]);
|
||||
let (compactor_call_after_fork, compactor_output_after_fork) =
|
||||
extract_compactor_items(&requests[4]);
|
||||
let user_turn_1 = json!(
|
||||
{
|
||||
"model": expected_model,
|
||||
@@ -304,16 +367,12 @@ async fn compact_resume_and_fork_preserve_model_history_view() {
|
||||
"content": [
|
||||
{
|
||||
"type": "input_text",
|
||||
"text": "You were originally given instructions from a user over one or more turns. Here were the user messages:
|
||||
|
||||
hello world
|
||||
|
||||
Another language model started to solve this problem and produced a summary of its thinking process. You also have access to the state of the tools that were used by that language model. Use this to build on the work that has already been done and avoid duplicating work. Here is the summary produced by the other language model, use the information in this summary to assist with your own analysis:
|
||||
|
||||
SUMMARY_ONLY_CONTEXT"
|
||||
"text": "hello world"
|
||||
}
|
||||
]
|
||||
},
|
||||
compactor_call_after_compact.clone(),
|
||||
compactor_output_after_compact.clone(),
|
||||
{
|
||||
"type": "message",
|
||||
"role": "user",
|
||||
@@ -369,16 +428,12 @@ SUMMARY_ONLY_CONTEXT"
|
||||
"content": [
|
||||
{
|
||||
"type": "input_text",
|
||||
"text": "You were originally given instructions from a user over one or more turns. Here were the user messages:
|
||||
|
||||
hello world
|
||||
|
||||
Another language model started to solve this problem and produced a summary of its thinking process. You also have access to the state of the tools that were used by that language model. Use this to build on the work that has already been done and avoid duplicating work. Here is the summary produced by the other language model, use the information in this summary to assist with your own analysis:
|
||||
|
||||
SUMMARY_ONLY_CONTEXT"
|
||||
"text": "hello world"
|
||||
}
|
||||
]
|
||||
},
|
||||
compactor_call_after_resume.clone(),
|
||||
compactor_output_after_resume.clone(),
|
||||
{
|
||||
"type": "message",
|
||||
"role": "user",
|
||||
@@ -454,16 +509,12 @@ SUMMARY_ONLY_CONTEXT"
|
||||
"content": [
|
||||
{
|
||||
"type": "input_text",
|
||||
"text": "You were originally given instructions from a user over one or more turns. Here were the user messages:
|
||||
|
||||
hello world
|
||||
|
||||
Another language model started to solve this problem and produced a summary of its thinking process. You also have access to the state of the tools that were used by that language model. Use this to build on the work that has already been done and avoid duplicating work. Here is the summary produced by the other language model, use the information in this summary to assist with your own analysis:
|
||||
|
||||
SUMMARY_ONLY_CONTEXT"
|
||||
"text": "hello world"
|
||||
}
|
||||
]
|
||||
},
|
||||
compactor_call_after_fork.clone(),
|
||||
compactor_output_after_fork.clone(),
|
||||
{
|
||||
"type": "message",
|
||||
"role": "user",
|
||||
|
||||
Reference in New Issue
Block a user