fix(responses): clean up replayed items before sending them to providers
Prevent Responses API errors when conversation history is reused in a new provider request. Fresh and pending Chat-style history conversions no longer include stale provider-generated item IDs, while preserving function-call IDs for tool output linkage. During opaque Responses state replay, remove unsupported status fields from reasoning items before sending them to the provider. Preserve encrypted reasoning content and other valid provider fields. Add regression coverage for stale item IDs and replayed reasoning items with unsupported status fields.
This commit is contained in:
1 parent
19c3db55ce
commit
e5a137956f
4 files changed
+110
-10
No files matched your search
@@ -16,6 +16,7 @@ def convert_messages(
|
||||
messages: list[dict[str, Any]],
|
||||
*,
|
||||
preserve_reasoning: bool = False,
|
||||
include_item_ids: bool = True,
|
||||
) -> tuple[str, list[dict[str, Any]]]:
|
||||
"""Convert Chat Completions messages to Responses API input items.
|
||||
|
||||
@@ -48,26 +49,32 @@ def convert_messages(
|
||||
"content": [{"type": "output_text", "text": reasoning}],
|
||||
})
|
||||
if isinstance(content, str) and content:
|
||||
message_id = _unique_item_id(f"msg_{idx}", used_item_ids)
|
||||
input_items.append({
|
||||
message_item: dict[str, Any] = {
|
||||
"type": "message", "role": "assistant",
|
||||
"content": [{"type": "output_text", "text": content}],
|
||||
"status": "completed", "id": message_id,
|
||||
})
|
||||
"status": "completed",
|
||||
}
|
||||
if include_item_ids:
|
||||
message_item["id"] = _unique_item_id(f"msg_{idx}", used_item_ids)
|
||||
input_items.append(message_item)
|
||||
for raw_tool_call in cast(list[object], msg.get("tool_calls", []) or []):
|
||||
tool_call = _as_json_object(raw_tool_call)
|
||||
if tool_call is None:
|
||||
continue
|
||||
fn = _as_json_object(tool_call.get("function")) or {}
|
||||
call_id, item_id = split_tool_call_id(tool_call.get("id"))
|
||||
response_item_id = _unique_item_id(item_id or f"fc_{idx}", used_item_ids)
|
||||
input_items.append({
|
||||
function_call_item: dict[str, Any] = {
|
||||
"type": "function_call",
|
||||
"id": response_item_id,
|
||||
"call_id": call_id or f"call_{idx}",
|
||||
"name": fn.get("name"),
|
||||
"arguments": tool_arguments_json_for_replay(fn.get("arguments")),
|
||||
})
|
||||
}
|
||||
if include_item_ids:
|
||||
function_call_item["id"] = _unique_item_id(
|
||||
item_id or f"fc_{idx}",
|
||||
used_item_ids,
|
||||
)
|
||||
input_items.append(function_call_item)
|
||||
continue
|
||||
|
||||
if role == "tool":
|
||||
|
||||
@@ -54,6 +54,7 @@ def prepare_responses_input(
|
||||
instructions, fallback_items = convert_messages(
|
||||
messages,
|
||||
preserve_reasoning=preserve_reasoning,
|
||||
include_item_ids=False,
|
||||
)
|
||||
if state is None or not responses_state_matches(
|
||||
state,
|
||||
@@ -69,13 +70,18 @@ def prepare_responses_input(
|
||||
_, delta_items = convert_messages(
|
||||
state.pending_messages,
|
||||
preserve_reasoning=preserve_reasoning,
|
||||
include_item_ids=False,
|
||||
)
|
||||
logger.debug(
|
||||
"Replaying Responses state: prior_items={} pending_messages={}",
|
||||
len(prior_items),
|
||||
len(state.pending_messages),
|
||||
)
|
||||
return instructions, [*deepcopy(prior_items), *delta_items], True
|
||||
replayed_items = deepcopy(prior_items)
|
||||
for item in replayed_items:
|
||||
if item.get("type") == "reasoning":
|
||||
item.pop("status", None)
|
||||
return instructions, [*replayed_items, *delta_items], True
|
||||
|
||||
|
||||
def build_responses_state(
|
||||
|
||||
@@ -111,7 +111,7 @@ class XAIGrokProvider(LLMProvider):
|
||||
on_stream_recover: Callable[[], Awaitable[None]] | None = None,
|
||||
) -> LLMResponse:
|
||||
wire_model = _strip_model_prefix(model or self.default_model)
|
||||
system_prompt, input_items = convert_messages(messages)
|
||||
system_prompt, input_items = convert_messages(messages, include_item_ids=False)
|
||||
|
||||
stage = "oauth_token"
|
||||
try:
|
||||
|
||||
@@ -216,6 +216,23 @@ class TestConvertMessages:
|
||||
assert items[0]["name"] == "get_weather"
|
||||
assert items[0]["arguments"] == '{"city": "SF"}'
|
||||
|
||||
def test_can_omit_item_ids_without_changing_call_ids(self):
|
||||
_, items = convert_messages([
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": None,
|
||||
"tool_calls": [{
|
||||
"id": "call_1|fc_1",
|
||||
"function": {"name": "get_weather", "arguments": "{}"},
|
||||
}],
|
||||
},
|
||||
{"role": "tool", "tool_call_id": "call_1|fc_1", "content": "ok"},
|
||||
], include_item_ids=False)
|
||||
|
||||
assert all("id" not in item for item in items)
|
||||
assert items[0]["call_id"] == "call_1"
|
||||
assert items[1]["call_id"] == "call_1"
|
||||
|
||||
def test_assistant_tool_call_history_repairs_malformed_arguments(self):
|
||||
_, items = convert_messages([{
|
||||
"role": "assistant",
|
||||
@@ -753,6 +770,36 @@ class TestParseResponseOutput:
|
||||
|
||||
|
||||
class TestResponsesConversationState:
|
||||
def test_replayed_reasoning_items_omit_unsupported_status(self):
|
||||
state = build_responses_state(
|
||||
provider="openai:test",
|
||||
model="gpt-5.6",
|
||||
input_items=[{"role": "user", "content": "previous"}],
|
||||
output_items=[{
|
||||
"type": "reasoning",
|
||||
"id": "rs_1",
|
||||
"status": None,
|
||||
"encrypted_content": "opaque",
|
||||
}],
|
||||
).with_pending_messages([
|
||||
{"role": "user", "content": "continue"},
|
||||
])
|
||||
|
||||
_, items, replayed = prepare_responses_input(
|
||||
[{"role": "user", "content": "current"}],
|
||||
state=state,
|
||||
provider="openai:test",
|
||||
model="gpt-5.6",
|
||||
)
|
||||
|
||||
assert replayed is True
|
||||
reasoning_item = next(
|
||||
item for item in items
|
||||
if item.get("type") == "reasoning"
|
||||
)
|
||||
assert "status" not in reasoning_item
|
||||
assert reasoning_item["encrypted_content"] == "opaque"
|
||||
|
||||
def test_server_compaction_prunes_superseded_prefix(self):
|
||||
state = build_responses_state(
|
||||
provider="openai:test",
|
||||
@@ -852,6 +899,46 @@ class TestResponsesConversationState:
|
||||
assert "dropped_items=2" in log_text
|
||||
assert secret not in log_text
|
||||
|
||||
def test_fresh_and_pending_conversions_omit_item_ids(self):
|
||||
pending_messages = [{
|
||||
"role": "assistant",
|
||||
"content": None,
|
||||
"tool_calls": [{
|
||||
"id": "call_1|fc_1",
|
||||
"function": {"name": "read_file", "arguments": "{}"},
|
||||
}],
|
||||
}]
|
||||
|
||||
_, fresh_items, replayed = prepare_responses_input(
|
||||
pending_messages,
|
||||
state=None,
|
||||
provider="openai:test",
|
||||
model="gpt-5.6",
|
||||
)
|
||||
|
||||
assert replayed is False
|
||||
assert fresh_items[0]["call_id"] == "call_1"
|
||||
assert "id" not in fresh_items[0]
|
||||
|
||||
state = build_responses_state(
|
||||
provider="openai:test",
|
||||
model="gpt-5.6",
|
||||
input_items=[{"role": "user", "content": "previous"}],
|
||||
output_items=[{"type": "message", "id": "msg_previous"}],
|
||||
).with_pending_messages(pending_messages)
|
||||
|
||||
_, items, replayed = prepare_responses_input(
|
||||
[{"role": "user", "content": "current"}],
|
||||
state=state,
|
||||
provider="openai:test",
|
||||
model="gpt-5.6",
|
||||
)
|
||||
|
||||
assert replayed is True
|
||||
assert items[1]["id"] == "msg_previous"
|
||||
assert items[2]["call_id"] == "call_1"
|
||||
assert "id" not in items[2]
|
||||
|
||||
def test_replays_exact_items_then_only_pending_and_new_messages(self):
|
||||
prior_items = [
|
||||
{"role": "user", "content": "first"},
|
||||
|
||||
Reference in new issue
Block a user