From ab8a7306c67549c3b314f44551a8c6ab496cd130 Mon Sep 17 00:00:00 2001 From: Manan Agrawal Date: Wed, 1 Apr 2026 17:32:29 -0400 Subject: [PATCH] Add example and docs for reasoning-message pairing constraint (#1791) --- README.md | 11 ++++++++ examples/reasoning-safe-history.js | 42 ++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 examples/reasoning-safe-history.js diff --git a/README.md b/README.md index b0392fea4..5428ecbe7 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,17 @@ const response = await client.responses.create({ input: 'Are semicolons optional in JavaScript?', }); +### Multi-turn conversations and reasoning items + +When using the Responses API, reasoning and message items must be preserved as pairs. + +A common mistake is filtering `response.output` to keep only messages. +This can lead to 400 errors due to missing reasoning items. + +Recommended: +- Pass `response.output` directly, OR +- Preserve reasoning-message pairs when constructing history + console.log(response.output_text); ``` diff --git a/examples/reasoning-safe-history.js b/examples/reasoning-safe-history.js new file mode 100644 index 000000000..677959e23 --- /dev/null +++ b/examples/reasoning-safe-history.js @@ -0,0 +1,42 @@ +import OpenAI from "openai"; + +const client = new OpenAI(); + +let conversation = []; + +function preservePairs(output) { + const result = []; + + for (let i = 0; i < output.length; i++) { + const curr = output[i]; + const next = output[i + 1]; + + if (curr.type === "reasoning" && next?.type === "message") { + result.push(curr, next); + i++; + } + } + + return result; +} + +async function run() { + for (const msg of [ + "Write a Python prime checker.", + "Add type hints.", + "Add docstrings." + ]) { + conversation.push({ role: "user", content: msg }); + + const response = await client.responses.create({ + model: "gpt-5.3-codex", + input: conversation, + reasoning: { effort: "high" }, + }); + + // ✅ SAFE + conversation.push(...preservePairs(response.output)); + } +} + +run(); \ No newline at end of file