Skip to content

The agent engineering platform.

fix(openai): drop response item ids when `store` is false (#38372)

Mason Daugherty792c1a743e44
diff --git a/libs/partners/openai/langchain_openai/chat_models/base.py b/libs/partners/openai/langchain_openai/chat_models/base.py
index ff72f66ed3..1181a80a26 100644
--- a/libs/partners/openai/langchain_openai/chat_models/base.py
+++ b/libs/partners/openai/langchain_openai/chat_models/base.py
@@ -4183,7 +4183,9 @@ def _construct_responses_api_payload(
):
payload.pop("temperature", None)
- payload["input"] = _construct_responses_api_input(messages)
+ payload["input"] = _construct_responses_api_input(
+ messages, store=payload.get("store")
+ )
if tools := payload.pop("tools", None):
new_tools: list = []
for tool in tools:
@@ -4415,8 +4417,29 @@ def _pop_index_and_sub_index(block: dict) -> dict:
return new_block
-def _construct_responses_api_input(messages: Sequence[BaseMessage]) -> list:
- """Construct the input for the OpenAI Responses API."""
+def _construct_responses_api_input(
+ messages: Sequence[BaseMessage], *, store: bool | None = None
+) -> list:
+ """Construct the input for the OpenAI Responses API.
+
+ Args:
+ messages: Conversation history to serialize into Responses API input items.
+ store: Mirrors the request's `store` flag, controlling stateless-replay
+ behavior.
+
+ When `False`, the server does not persist response items, so
+ previously returned item IDs cannot be resolved on the next turn.
+ Assistant message IDs (`msg_*`) are therefore omitted and reasoning
+ blocks are dropped unless they carry `encrypted_content` (which can be
+ replayed without server-side storage).
+
+ When `True` or `None` (the default, matching the server's
+ stored-by-default behavior), item IDs and reasoning blocks
+ are preserved.
+
+ Returns:
+ A list of Responses API input items derived from `messages`.
+ """
input_ = []
for lc_msg in messages:
if isinstance(lc_msg, AIMessage):
@@ -4505,13 +4528,16 @@ def _construct_responses_api_input(messages: Sequence[BaseMessage]) -> list:
"type": "message",
"content": [new_block],
"role": "assistant",
- "id": msg_id,
}
+ if store is not False:
+ new_item["id"] = msg_id
if phase is not None:
new_item["phase"] = phase
input_.append(new_item)
+ elif block_type == "reasoning":
+ if store is not False or "encrypted_content" in block:
+ input_.append(_pop_index_and_sub_index(block))
elif block_type in (
- "reasoning",
"compaction",
"web_search_call",
"file_search_call",
@@ -4530,9 +4556,17 @@ def _construct_responses_api_input(messages: Sequence[BaseMessage]) -> list:
input_.append(_pop_index_and_sub_index(block))
elif block_type == "image_generation_call":
# A previous image generation call can be referenced by ID
- input_.append(
- {"type": "image_generation_call", "id": block["id"]}
- )
+ if store is not False:
+ input_.append(
+ {"type": "image_generation_call", "id": block["id"]}
+ )
+ else:
+ # ID-only references require stored server state. For
+ # stateless requests, replay full items and drop bare
+ # references that the backend cannot resolve.
+ image_generation_call = _pop_index_and_sub_index(block)
+ if set(image_generation_call) - {"type", "id"}:
+ input_.append(image_generation_call)
else:
pass
elif isinstance(msg.get("content"), str):
diff --git a/libs/partners/openai/tests/cassettes/TestChatOpenAICodexStandard.test_anthropic_inputs.yaml.gz b/libs/partners/openai/tests/cassettes/TestChatOpenAICodexStandard.test_anthropic_inputs.yaml.gz
index d510e93c6c..3880e973d3 100644
Binary files a/libs/partners/openai/tests/cassettes/TestChatOpenAICodexStandard.test_anthropic_inputs.yaml.gz and b/libs/partners/openai/tests/cassettes/TestChatOpenAICodexStandard.test_anthropic_inputs.yaml.gz differ
diff --git a/libs/partners/openai/tests/cassettes/TestChatOpenAICodexStandard.test_tool_message_histories_list_content.yaml.gz b/libs/partners/openai/tests/cassettes/TestChatOpenAICodexStandard.test_tool_message_histories_list_content.yaml.gz
index bdc427add8..53b6357eb0 100644
Binary files a/libs/partners/openai/tests/cassettes/TestChatOpenAICodexStandard.test_tool_message_histories_list_content.yaml.gz and b/libs/partners/openai/tests/cassettes/TestChatOpenAICodexStandard.test_tool_message_histories_list_content.yaml.gz differ
diff --git a/libs/partners/openai/tests/cassettes/test_codex_multi_turn_no_tools.yaml.gz b/libs/partners/openai/tests/cassettes/test_codex_multi_turn_no_tools.yaml.gz
index b2ba6a7e36..d7c15b8746 100644
Binary files a/libs/partners/openai/tests/cassettes/test_codex_multi_turn_no_tools.yaml.gz and b/libs/partners/openai/tests/cassettes/test_codex_multi_turn_no_tools.yaml.gz differ
diff --git a/libs/partners/openai/tests/cassettes/test_mcp_builtin_zdr.yaml.gz b/libs/partners/openai/tests/cassettes/test_mcp_builtin_zdr.yaml.gz
index 8f0fb68744..310a04d31c 100644
Binary files a/libs/partners/openai/tests/cassettes/test_mcp_builtin_zdr.yaml.gz and b/libs/partners/openai/tests/cassettes/test_mcp_builtin_zdr.yaml.gz differ
diff --git a/libs/partners/openai/tests/unit_tests/chat_models/test_base.py b/libs/partners/openai/tests/unit_tests/chat_models/test_base.py
index 594346ef46..1be3d52326 100644
--- a/libs/partners/openai/tests/unit_tests/chat_models/test_base.py
+++ b/libs/partners/openai/tests/unit_tests/chat_models/test_base.py
@@ -2771,6 +2771,103 @@ def test__construct_responses_api_input_human_message_with_image_url_conversion(
assert result[0]["content"][1]["detail"] == "high"
+def test__construct_responses_api_input_store_false_replays_stateless_history() -> None:
+ ai_message = AIMessage(
+ content=[
+ {"type": "reasoning", "id": "rs_123", "summary": []},
+ {
+ "type": "reasoning",
+ "id": "rs_456",
+ "summary": [],
+ "encrypted_content": "",
+ },
+ {"type": "text", "text": "Use pathlib.rglob.", "id": "msg_123"},
+ ],
+ response_metadata={"id": "resp_123"},
+ )
+
+ result = _construct_responses_api_input([ai_message], store=False)
+
+ assert result == [
+ {
+ "type": "reasoning",
+ "id": "rs_456",
+ "summary": [],
+ "encrypted_content": "",
+ },
+ {
+ "type": "message",
+ "content": [
+ {"type": "output_text", "text": "Use pathlib.rglob.", "annotations": []}
+ ],
+ "role": "assistant",
+ },
+ ]
+
+
[email protected]("store", [None, True])
+def test__construct_responses_api_input_store_enabled_keeps_item_ids(
+ store: bool | None,
+) -> None:
+ ai_message = AIMessage(
+ content=[
+ {"type": "reasoning", "id": "rs_123", "summary": []},
+ {"type": "text", "text": "Use pathlib.rglob.", "id": "msg_123"},
+ ],
+ response_metadata={"id": "resp_123"},
+ )
+
+ result = _construct_responses_api_input([ai_message], store=store)
+
+ assert result == [
+ {"type": "reasoning", "id": "rs_123", "summary": []},
+ {
+ "type": "message",
+ "content": [
+ {"type": "output_text", "text": "Use pathlib.rglob.", "annotations": []}
+ ],
+ "role": "assistant",
+ "id": "msg_123",
+ },
+ ]
+
+
+def test__construct_responses_api_input_store_false_keeps_full_tool_call_items() -> (
+ None
+):
+ ai_message = AIMessage(
+ content=[
+ {
+ "type": "function_call",
+ "name": "get_weather",
+ "arguments": '{"location": "San Francisco"}',
+ "call_id": "call_123",
+ "id": "fc_456",
+ }
+ ],
+ tool_calls=[
+ {
+ "id": "call_123",
+ "name": "get_weather",
+ "args": {"location": "San Francisco"},
+ "type": "tool_call",
+ }
+ ],
+ )
+
+ result = _construct_responses_api_input([ai_message], store=False)
+
+ assert result == [
+ {
+ "type": "function_call",
+ "name": "get_weather",
+ "arguments": '{"location": "San Francisco"}',
+ "call_id": "call_123",
+ "id": "fc_456",
+ }
+ ]
+
+
def test__construct_responses_api_input_ai_message_with_tool_calls() -> None:
"""Test that AI messages with tool calls are properly converted."""
tool_calls = [
diff --git a/libs/partners/openai/tests/unit_tests/chat_models/test_codex.py b/libs/partners/openai/tests/unit_tests/chat_models/test_codex.py
index c32532f090..cb5fac4415 100644
--- a/libs/partners/openai/tests/unit_tests/chat_models/test_codex.py
+++ b/libs/partners/openai/tests/unit_tests/chat_models/test_codex.py
@@ -7,7 +7,7 @@ from datetime import datetime, timedelta, timezone
from typing import Any
import pytest
-from langchain_core.messages import ChatMessage, HumanMessage, SystemMessage
+from langchain_core.messages import AIMessage, ChatMessage, HumanMessage, SystemMessage
import langchain_openai.chat_models.codex as codex_module
from langchain_openai.chat_models.base import ChatOpenAI
@@ -289,6 +289,89 @@ def test_request_payload_sends_store_false_and_stream_true() -> None:
assert payload["stream"] is True
+def test_request_payload_with_store_false_drops_reasoning_item_references() -> None:
+ model = _build_model()
+ payload = model._get_request_payload(
+ [
+ HumanMessage("Explain recursive file search."),
+ AIMessage(
+ content=[
+ {"type": "reasoning", "id": "rs_123", "summary": []},
+ {
+ "type": "reasoning",
+ "id": "rs_456",
+ "summary": [],
+ "encrypted_content": "encrypted-context",
+ },
+ {"type": "text", "text": "Use pathlib.rglob.", "id": "msg_123"},
+ ],
+ response_metadata={"id": "resp_123"},
+ ),
+ HumanMessage("Make it shorter."),
+ ]
+ )
+
+ assert payload["store"] is False
+ assert [item.get("type") for item in payload["input"]] == [
+ "message",
+ "reasoning",
+ "message",
+ "message",
+ ]
+ assert payload["input"][1] == {
+ "type": "reasoning",
+ "id": "rs_456",
+ "summary": [],
+ "encrypted_content": "encrypted-context",
+ }
+ assert payload["input"][2]["content"] == [
+ {"type": "output_text", "text": "Use pathlib.rglob.", "annotations": []}
+ ]
+ assert "id" not in payload["input"][2]
+
+
+def test_request_payload_with_store_false_drops_image_call_references() -> None:
+ model = _build_model()
+ payload = model._get_request_payload(
+ [
+ HumanMessage("Draw a word."),
+ AIMessage(
+ content=[
+ {"type": "image_generation_call", "id": "ig_reference_only"},
+ {
+ "type": "image_generation_call",
+ "id": "ig_with_result",
+ "result": "base64-image",
+ "status": "completed",
+ "index": 0,
+ },
+ {"type": "text", "text": "Done.", "id": "msg_123"},
+ ],
+ response_metadata={"id": "resp_123"},
+ ),
+ HumanMessage("Change the color."),
+ ]
+ )
+
+ assert payload["store"] is False
+ assert [item.get("type") for item in payload["input"]] == [
+ "message",
+ "image_generation_call",
+ "message",
+ "message",
+ ]
+ assert payload["input"][1] == {
+ "type": "image_generation_call",
+ "id": "ig_with_result",
+ "result": "base64-image",
+ "status": "completed",
+ }
+ assert payload["input"][2]["content"] == [
+ {"type": "output_text", "text": "Done.", "annotations": []}
+ ]
+ assert "id" not in payload["input"][2]
+
+
def test_request_payload_sets_default_instructions() -> None:
"""The Codex backend 400s without `instructions`; default must be injected."""
model = _build_model()