fix(providers): replay OpenAI Responses reasoning across tool turns (#13222)

This commit is contained in:
filip
2026-10-30 08:47:28 +00:00
committed by GitHub
parent 5614a09400
commit 0aeb4077a9
5 changed files with 229 additions and 43 deletions
+19
View File
@@ -286,6 +286,24 @@ fn messages_for_provider(
.collect()
}
/// Signed reasoning only verifies with the provider account that produced it.
fn drop_foreign_signed_thinking(messages: &mut [Message], provider: &str) {
for message in messages {
if message
.metadata
.inference
.as_ref()
.is_some_and(|inference| inference.provider != provider)
{
message.content.retain(|content| match content {
MessageContent::Thinking(thinking) => thinking.signature.is_empty(),
MessageContent::RedactedThinking(_) => false,
_ => true,
});
}
}
}
fn latest_provider_session_id<'a>(
conversation: &'a Conversation,
provider: &str,
@@ -467,6 +485,7 @@ impl<S: MachineSession, E: InferenceEffect> Inference<S, E> for InferenceRunner<
self.output().additional_messages = additional_messages;
let provider_name = self.provider.get_name();
drop_foreign_signed_thinking(&mut messages_for_provider, provider_name);
if let Some(session_id) = latest_provider_session_id(conversation, provider_name) {
if let Err(error) = self.provider.resume(session_id).await {
tracing::warn!(
@@ -1,10 +1,11 @@
use crate::conversation::message::{Message, MessageContentBlock};
use crate::conversation::message::{Message, MessageContentBlock, ThinkingContentBlock};
use crate::conversation::token_usage::{ProviderUsage, Usage};
use crate::documents::{
convert_document, document_media_type_is_supported, unsupported_document_text, DocumentFormat,
ASSISTANT_ROLE_REASON, UNSUPPORTED_MEDIA_TYPE_REASON,
};
use crate::errors::ProviderError;
use crate::formats::anthropic::thinking_block_is_stale;
use crate::formats::openai::{
extract_reasoning_effort, openai_reasoning_effort_for_thinking, sanitize_function_name,
};
@@ -44,16 +45,59 @@ pub struct SummaryText {
pub text: String,
}
fn reasoning_from_summary(summary: &[SummaryText]) -> Option<MessageContentBlock> {
fn reasoning_from_output(
summary: &[SummaryText],
encrypted_content: Option<&str>,
) -> Option<MessageContentBlock> {
let text: String = summary
.iter()
.map(|s| sanitize_unicode_tags(&s.text))
.collect::<Vec<_>>()
.join("\n");
if text.is_empty() {
let encrypted_content = encrypted_content.unwrap_or_default();
if text.is_empty() && encrypted_content.is_empty() {
None
} else {
Some(MessageContentBlock::thinking(text, ""))
Some(MessageContentBlock::thinking(text, encrypted_content))
}
}
/// The thinking signature slot also carries Anthropic signatures and reasoning
/// imported from other accounts, which the API rejects, so only reasoning that
/// `current_model` produced in this session is replayed.
pub fn reasoning_input_item(
message: &Message,
thinking: &ThinkingContentBlock,
current_model: &str,
) -> Option<Value> {
if thinking.signature.is_empty()
|| message.metadata.inference.is_none()
|| thinking_block_is_stale(message, Some(current_model))
{
return None;
}
let summary: Vec<Value> = if thinking.thinking.is_empty() {
Vec::new()
} else {
vec![json!({ "type": "summary_text", "text": thinking.thinking })]
};
Some(json!({
"type": "reasoning",
"summary": summary,
"encrypted_content": thinking.signature
}))
}
pub fn is_encrypted_reasoning_error(message: &str) -> bool {
let lower = message.to_lowercase();
lower.contains("encrypted content") && lower.contains("could not be verified")
}
/// Rejected reasoning stays in the session, so callers retry once without any
/// reasoning items rather than failing every later request.
pub fn strip_reasoning_items(payload: &mut Value) {
if let Some(input) = payload.get_mut("input").and_then(Value::as_array_mut) {
input.retain(|item| item["type"] != "reasoning");
}
}
@@ -66,6 +110,8 @@ pub enum ResponseOutputItem {
id: Option<String>,
#[serde(default)]
summary: Vec<SummaryText>,
#[serde(default, skip_serializing_if = "Option::is_none")]
encrypted_content: Option<String>,
},
Message {
// `id` and `status` are required when the OpenAI API emits these
@@ -363,6 +409,8 @@ pub enum ResponseOutputItemInfo {
id: Option<String>,
#[serde(default)]
summary: Vec<SummaryText>,
#[serde(default, skip_serializing_if = "Option::is_none")]
encrypted_content: Option<String>,
},
Message {
#[serde(skip_serializing_if = "Option::is_none")]
@@ -408,7 +456,12 @@ pub enum ContentBlockPart {
},
}
fn add_message_items(input_items: &mut Vec<Value>, messages: &[Message], supports_vision: bool) {
fn add_message_items(
input_items: &mut Vec<Value>,
messages: &[Message],
supports_vision: bool,
current_model: &str,
) {
for message in messages.iter().filter(|m| m.is_agent_visible()) {
let role = match message.role {
Role::User => "user",
@@ -434,6 +487,11 @@ fn add_message_items(input_items: &mut Vec<Value>, messages: &[Message], support
}));
}
}
// Streamed text is stored ahead of the reasoning that produced it,
// so pending text is left to flush after the reasoning item.
MessageContentBlock::Thinking(thinking) if message.role == Role::Assistant => {
input_items.extend(reasoning_input_item(message, thinking, current_model));
}
MessageContentBlock::ToolRequest(request) if message.role == Role::Assistant => {
if !text_items.is_empty() {
input_items.push(json!({
@@ -652,6 +710,7 @@ pub fn create_responses_request_for_model(
&mut input_items,
messages,
model_config.supports_vision.unwrap_or_default(),
&model_config.model_name,
);
let (model_name, legacy_reasoning_effort) = extract_reasoning_effort(capability_model_name);
@@ -723,6 +782,10 @@ pub fn create_responses_request_for_model(
.insert("reasoning".to_string(), Value::Object(reasoning));
}
if is_reasoning_model {
payload["include"] = json!(["reasoning.encrypted_content"]);
}
if !tools.is_empty() {
let tools_spec: Vec<Value> = tools
.iter()
@@ -906,8 +969,12 @@ pub fn responses_api_to_message(response: &ResponsesApiResponse) -> anyhow::Resu
for item in &response.output {
match item {
ResponseOutputItem::Reasoning { summary, .. } => {
content.extend(reasoning_from_summary(summary));
ResponseOutputItem::Reasoning {
summary,
encrypted_content,
..
} => {
content.extend(reasoning_from_output(summary, encrypted_content.as_deref()));
}
ResponseOutputItem::Message {
content: msg_content,
@@ -991,8 +1058,15 @@ fn process_streaming_output_items(
for item in output_items {
match item {
ResponseOutputItemInfo::Reasoning { summary, .. } => {
content.extend(reasoning_from_summary(&summary));
ResponseOutputItemInfo::Reasoning {
summary,
encrypted_content,
..
} => {
content.extend(reasoning_from_output(
&summary,
encrypted_content.as_deref(),
));
}
ResponseOutputItemInfo::Message { content: parts, .. } => {
for part in parts {
@@ -1308,7 +1382,7 @@ mod document_tests {
fn format(messages: &[Message]) -> Vec<Value> {
let mut items = Vec::new();
add_message_items(&mut items, messages, true);
add_message_items(&mut items, messages, true, "gpt-5.6");
items
}
@@ -3386,4 +3460,57 @@ mod tests {
.unwrap()
.contains("invalid arguments"));
}
#[tokio::test]
async fn test_encrypted_reasoning_replays_only_for_its_model() -> anyhow::Result<()> {
use crate::conversation::message::InferenceMetadata;
use rmcp::model::CallToolResult;
let reasoning_item = json!({
"type": "reasoning", "id": "rs_1", "summary": [], "encrypted_content": "enc-1"
});
let call_item = json!({
"type": "function_call", "id": "fc_1", "call_id": "call_1", "name": "shell", "arguments": "{}"
});
let lines = vec![format!(
r#"data: {{"type":"response.completed","sequence_number":1,"response":{{"id":"resp_1","object":"response","status":"completed","model":"gpt-5.6","output":[{reasoning_item},{call_item}]}}}}"#
)];
let stream =
responses_api_to_streaming_message(tokio_stream::iter(lines.into_iter().map(Ok)));
futures::pin_mut!(stream);
let (Some(assistant), _) = stream.next().await.unwrap()? else {
panic!("expected a message");
};
let assistant = assistant.with_inference(InferenceMetadata {
provider: "openai".to_string(),
requested_model: "gpt-5.6".to_string(),
resolved_model: None,
provider_session_id: None,
});
let messages = vec![
Message::user().with_text("list files"),
assistant,
Message::user().with_content(MessageContentBlock::tool_response(
"call_1",
Ok(CallToolResult::success(vec![ContentBlock::text("a.txt")])),
)),
];
let same = create_responses_request(&ModelConfig::new("gpt-5.6"), "", &messages, &[])?;
assert_eq!(same["include"], json!(["reasoning.encrypted_content"]));
let input = same["input"].as_array().unwrap();
assert_eq!(
input[1],
json!({ "type": "reasoning", "summary": [], "encrypted_content": "enc-1" })
);
assert_eq!(input[2]["type"], "function_call");
let other = create_responses_request(&ModelConfig::new("gpt-5.5"), "", &messages, &[])?;
assert!(!other["input"]
.as_array()
.unwrap()
.iter()
.any(|item| item["type"] == "reasoning"));
Ok(())
}
}
+1
View File
@@ -102,6 +102,7 @@ fn is_permanent_request_failure(message: &str) -> bool {
.iter()
.any(|marker| message.contains(marker))
|| crate::formats::anthropic::is_thinking_signature_error(message)
|| crate::formats::openai_responses::is_encrypted_reasoning_error(message)
}
pub fn should_retry(error: &ProviderError, config: &RetryConfig) -> bool {
+43 -22
View File
@@ -15,8 +15,8 @@ use crate::formats::openai::{
record_response_metadata, response_to_message, OpenAiFormatOptions,
};
use crate::formats::openai_responses::{
create_responses_request_for_model, get_responses_usage, responses_api_to_message,
ResponsesApiResponse,
create_responses_request_for_model, get_responses_usage, is_encrypted_reasoning_error,
responses_api_to_message, strip_reasoning_items, ResponsesApiResponse,
};
use crate::http_status::{extract_request_id, read_json_response};
use crate::images::ImageFormat;
@@ -341,6 +341,29 @@ impl OpenAiProvider {
.or_insert_with(|| serde_json::Value::String(session_id));
}
async fn post_responses(
&self,
model_config: &ModelConfig,
payload: &serde_json::Value,
) -> Result<reqwest::Response, ProviderError> {
self.with_retry(|| async {
handle_status(
self.api_client
.request(&Self::map_base_path(
&self.base_path,
"responses",
OPEN_AI_DEFAULT_RESPONSES_PATH,
))
.model_headers(model_config)?
.streaming(self.supports_streaming)
.response_post(payload)
.await?,
)
.await
})
.await
}
async fn stream_responses_payload(
&self,
model_config: &ModelConfig,
@@ -348,26 +371,24 @@ impl OpenAiProvider {
) -> Result<MessageStream, ProviderError> {
self.insert_prompt_cache_key(&mut payload);
let mut log = start_log(model_config, &payload)?;
let response = self
.with_retry(|| async {
handle_status(
self.api_client
.request(&Self::map_base_path(
&self.base_path,
"responses",
OPEN_AI_DEFAULT_RESPONSES_PATH,
))
.model_headers(model_config)?
.streaming(self.supports_streaming)
.response_post(&payload)
.await?,
)
.await
})
.await
.inspect_err(|e| {
let _ = log.error(e);
})?;
let response = match self.post_responses(model_config, &payload).await {
Err(ProviderError::RequestFailed(message))
if is_encrypted_reasoning_error(&message) =>
{
tracing::warn!(
error = %message,
"API rejected replayed reasoning; retrying once without it"
);
let _ = log.error(&message);
strip_reasoning_items(&mut payload);
log = start_log(model_config, &payload)?;
self.post_responses(model_config, &payload).await
}
other => other,
}
.inspect_err(|e| {
let _ = log.error(e);
})?;
if self.supports_streaming {
stream_responses_compat(response, log)
} else {
+29 -11
View File
@@ -17,7 +17,10 @@ use chrono::{DateTime, Utc};
use futures::future::BoxFuture;
use futures::{StreamExt, TryStreamExt};
use goose_providers::errors::ProviderError;
use goose_providers::formats::openai_responses::responses_api_to_streaming_message;
use goose_providers::formats::openai_responses::{
is_encrypted_reasoning_error, reasoning_input_item, responses_api_to_streaming_message,
strip_reasoning_items,
};
use goose_providers::model::ModelConfig;
use rmcp::model::{ContentBlock, Role, Tool};
use serde::{Deserialize, Serialize};
@@ -115,7 +118,7 @@ impl ChatGptCodexAuthState {
static CHATGPT_CODEX_AUTH_STATE: LazyLock<Arc<ChatGptCodexAuthState>> =
LazyLock::new(|| Arc::new(ChatGptCodexAuthState::new()));
fn build_input_items(messages: &[Message]) -> Result<Vec<Value>> {
fn build_input_items(messages: &[Message], model_name: &str) -> Result<Vec<Value>> {
let mut items = Vec::new();
for message in messages {
@@ -153,6 +156,9 @@ fn build_input_items(messages: &[Message]) -> Result<Vec<Value>> {
"image_url": format!("data:{};base64,{}", img.mime_type, img.data),
}));
}
MessageContent::Thinking(thinking) if message.role == Role::Assistant => {
items.extend(reasoning_input_item(message, thinking, model_name));
}
MessageContent::ToolRequest(request) => {
flush_text(&mut items, role, &mut content_items);
if let Ok(tool_call) = &request.tool_call {
@@ -265,7 +271,7 @@ fn create_codex_request(
messages: &[Message],
tools: &[Tool],
) -> Result<Value> {
let input_items = build_input_items(messages)?;
let input_items = build_input_items(messages, &model_config.model_name)?;
let reasoning_effort = reasoning_effort_for_config(model_config);
let mut payload = json!({
@@ -273,6 +279,7 @@ fn create_codex_request(
"input": input_items,
"store": false,
"instructions": system,
"include": ["reasoning.encrypted_content"],
});
let payload_obj = payload
@@ -938,12 +945,23 @@ impl Provider for ChatGptCodexProvider {
.map_err(|e| ProviderError::ExecutionError(e.to_string()))?;
payload["stream"] = serde_json::Value::Bool(true);
let response = self
.with_retry(|| async {
let payload_clone = payload.clone();
self.post_streaming(&payload_clone).await
})
.await?;
let response = match self
.with_retry(|| async { self.post_streaming(&payload).await })
.await
{
Err(ProviderError::RequestFailed(message))
if is_encrypted_reasoning_error(&message) =>
{
tracing::warn!(
error = %message,
"API rejected replayed reasoning; retrying once without it"
);
strip_reasoning_items(&mut payload);
self.with_retry(|| async { self.post_streaming(&payload).await })
.await
}
other => other,
}?;
let stream = response.bytes_stream().map_err(io::Error::other);
@@ -1147,7 +1165,7 @@ mod tests {
"image content included in user message"
)]
fn test_codex_input_order(messages: Vec<Message>, expected: Vec<String>) {
let items = build_input_items(&messages).unwrap();
let items = build_input_items(&messages, "gpt-5.6").unwrap();
let payload = json!({ "input": items });
let kinds = input_kinds(&payload);
assert_eq!(kinds, expected);
@@ -1156,7 +1174,7 @@ mod tests {
#[test]
fn test_image_url_format() {
let messages = vec![Message::user().with_image(TEST_IMAGE_B64, "image/png")];
let items = build_input_items(&messages).unwrap();
let items = build_input_items(&messages, "gpt-5.6").unwrap();
// The image is inside the content array of the user message
let content = items[0]["content"].as_array().unwrap();
let image_item = &content[0];