diff --git a/src/agents/pi-embedded-helpers/openai.ts b/src/agents/pi-embedded-helpers/openai.ts index 17cfa45e354..c96151b18b6 100644 --- a/src/agents/pi-embedded-helpers/openai.ts +++ b/src/agents/pi-embedded-helpers/openai.ts @@ -207,6 +207,7 @@ export function downgradeOpenAIFunctionCallReasoningPairs( * is incomplete, drop the block to keep history usable. */ export function downgradeOpenAIReasoningBlocks(messages: AgentMessage[]): AgentMessage[] { + let anyChanged = false; const out: AgentMessage[] = []; for (const msg of messages) { @@ -259,6 +260,7 @@ export function downgradeOpenAIReasoningBlocks(messages: AgentMessage[]): AgentM continue; } + anyChanged = true; if (nextContent.length === 0) { continue; } @@ -266,5 +268,5 @@ export function downgradeOpenAIReasoningBlocks(messages: AgentMessage[]): AgentM out.push({ ...assistantMsg, content: nextContent } as AgentMessage); } - return out; + return anyChanged ? out : messages; } diff --git a/src/agents/pi-embedded-runner/run/attempt.ts b/src/agents/pi-embedded-runner/run/attempt.ts index 49938ba2d6e..ef5f969fa9a 100644 --- a/src/agents/pi-embedded-runner/run/attempt.ts +++ b/src/agents/pi-embedded-runner/run/attempt.ts @@ -1368,12 +1368,10 @@ export async function runEmbeddedAttempt( if (!Array.isArray(messages)) { return inner(model, context, options); } - const pairSanitized = downgradeOpenAIFunctionCallReasoningPairs( - messages as AgentMessage[], - ); - // Also strip orphaned reasoning blocks that lack a required following - // content item — OpenAI rejects these with a 400 error. - const sanitized = downgradeOpenAIReasoningBlocks(pairSanitized); + // Strip orphaned reasoning blocks first, then fix function-call + // pairing — matches the call order in google.ts. + const reasoningSanitized = downgradeOpenAIReasoningBlocks(messages as AgentMessage[]); + const sanitized = downgradeOpenAIFunctionCallReasoningPairs(reasoningSanitized); if (sanitized === messages) { return inner(model, context, options); }