fix(responses): omit provider item IDs from chat history
This commit is contained in:
1 parent
e5a137956f
commit
0c5d8443ec
4 files changed
+31
-93
No files matched your search
@@ -16,18 +16,16 @@ def convert_messages(
|
|||||||
messages: list[dict[str, Any]],
|
messages: list[dict[str, Any]],
|
||||||
*,
|
*,
|
||||||
preserve_reasoning: bool = False,
|
preserve_reasoning: bool = False,
|
||||||
include_item_ids: bool = True,
|
|
||||||
) -> tuple[str, list[dict[str, Any]]]:
|
) -> tuple[str, list[dict[str, Any]]]:
|
||||||
"""Convert Chat Completions messages to Responses API input items.
|
"""Convert Chat Completions messages to Responses API input items.
|
||||||
|
|
||||||
Returns ``(system_prompt, input_items)`` where *system_prompt* is extracted
|
Returns ``(system_prompt, input_items)`` where *system_prompt* is extracted
|
||||||
from any ``system`` role message and *input_items* is the Responses API
|
from any ``system`` role message and *input_items* is the Responses API
|
||||||
``input`` array.
|
``input`` array. Provider-generated item IDs are deliberately omitted:
|
||||||
|
Chat history may be replayed through a different provider connection.
|
||||||
"""
|
"""
|
||||||
system_prompt = ""
|
system_prompt = ""
|
||||||
input_items: list[dict[str, Any]] = []
|
input_items: list[dict[str, Any]] = []
|
||||||
used_item_ids: set[str] = set()
|
|
||||||
|
|
||||||
for idx, msg in enumerate(messages):
|
for idx, msg in enumerate(messages):
|
||||||
role = msg.get("role")
|
role = msg.get("role")
|
||||||
content = msg.get("content")
|
content = msg.get("content")
|
||||||
@@ -49,32 +47,23 @@ def convert_messages(
|
|||||||
"content": [{"type": "output_text", "text": reasoning}],
|
"content": [{"type": "output_text", "text": reasoning}],
|
||||||
})
|
})
|
||||||
if isinstance(content, str) and content:
|
if isinstance(content, str) and content:
|
||||||
message_item: dict[str, Any] = {
|
input_items.append({
|
||||||
"type": "message", "role": "assistant",
|
"type": "message", "role": "assistant",
|
||||||
"content": [{"type": "output_text", "text": content}],
|
"content": [{"type": "output_text", "text": content}],
|
||||||
"status": "completed",
|
"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 []):
|
for raw_tool_call in cast(list[object], msg.get("tool_calls", []) or []):
|
||||||
tool_call = _as_json_object(raw_tool_call)
|
tool_call = _as_json_object(raw_tool_call)
|
||||||
if tool_call is None:
|
if tool_call is None:
|
||||||
continue
|
continue
|
||||||
fn = _as_json_object(tool_call.get("function")) or {}
|
fn = _as_json_object(tool_call.get("function")) or {}
|
||||||
call_id, item_id = split_tool_call_id(tool_call.get("id"))
|
call_id, _ = split_tool_call_id(tool_call.get("id"))
|
||||||
function_call_item: dict[str, Any] = {
|
input_items.append({
|
||||||
"type": "function_call",
|
"type": "function_call",
|
||||||
"call_id": call_id or f"call_{idx}",
|
"call_id": call_id or f"call_{idx}",
|
||||||
"name": fn.get("name"),
|
"name": fn.get("name"),
|
||||||
"arguments": tool_arguments_json_for_replay(fn.get("arguments")),
|
"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
|
continue
|
||||||
|
|
||||||
if role == "tool":
|
if role == "tool":
|
||||||
@@ -203,20 +192,6 @@ def convert_tools(tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|||||||
return converted
|
return converted
|
||||||
|
|
||||||
|
|
||||||
def _unique_item_id(item_id: str, used: set[str]) -> str:
|
|
||||||
"""Return a Responses input item id that is unique within one request."""
|
|
||||||
if item_id not in used:
|
|
||||||
used.add(item_id)
|
|
||||||
return item_id
|
|
||||||
|
|
||||||
suffix = 2
|
|
||||||
while f"{item_id}_{suffix}" in used:
|
|
||||||
suffix += 1
|
|
||||||
unique = f"{item_id}_{suffix}"
|
|
||||||
used.add(unique)
|
|
||||||
return unique
|
|
||||||
|
|
||||||
|
|
||||||
def split_tool_call_id(tool_call_id: Any) -> tuple[str, str | None]:
|
def split_tool_call_id(tool_call_id: Any) -> tuple[str, str | None]:
|
||||||
"""Split a compound ``call_id|item_id`` string.
|
"""Split a compound ``call_id|item_id`` string.
|
||||||
|
|
||||||
|
|||||||
@@ -54,7 +54,6 @@ def prepare_responses_input(
|
|||||||
instructions, fallback_items = convert_messages(
|
instructions, fallback_items = convert_messages(
|
||||||
messages,
|
messages,
|
||||||
preserve_reasoning=preserve_reasoning,
|
preserve_reasoning=preserve_reasoning,
|
||||||
include_item_ids=False,
|
|
||||||
)
|
)
|
||||||
if state is None or not responses_state_matches(
|
if state is None or not responses_state_matches(
|
||||||
state,
|
state,
|
||||||
@@ -70,17 +69,13 @@ def prepare_responses_input(
|
|||||||
_, delta_items = convert_messages(
|
_, delta_items = convert_messages(
|
||||||
state.pending_messages,
|
state.pending_messages,
|
||||||
preserve_reasoning=preserve_reasoning,
|
preserve_reasoning=preserve_reasoning,
|
||||||
include_item_ids=False,
|
|
||||||
)
|
)
|
||||||
logger.debug(
|
logger.debug(
|
||||||
"Replaying Responses state: prior_items={} pending_messages={}",
|
"Replaying Responses state: prior_items={} pending_messages={}",
|
||||||
len(prior_items),
|
len(prior_items),
|
||||||
len(state.pending_messages),
|
len(state.pending_messages),
|
||||||
)
|
)
|
||||||
replayed_items = deepcopy(prior_items)
|
replayed_items = _prepare_replayed_items(prior_items)
|
||||||
for item in replayed_items:
|
|
||||||
if item.get("type") == "reasoning":
|
|
||||||
item.pop("status", None)
|
|
||||||
return instructions, [*replayed_items, *delta_items], True
|
return instructions, [*replayed_items, *delta_items], True
|
||||||
|
|
||||||
|
|
||||||
@@ -222,3 +217,14 @@ def _state_items(
|
|||||||
return None
|
return None
|
||||||
items.append(cast(dict[str, Any], raw))
|
items.append(cast(dict[str, Any], raw))
|
||||||
return items
|
return items
|
||||||
|
|
||||||
|
|
||||||
|
def _prepare_replayed_items(
|
||||||
|
items: list[dict[str, Any]],
|
||||||
|
) -> list[dict[str, Any]]:
|
||||||
|
"""Copy provider state and remove output-only fields rejected on replay."""
|
||||||
|
replayed_items = deepcopy(items)
|
||||||
|
for item in replayed_items:
|
||||||
|
if item.get("type") == "reasoning":
|
||||||
|
item.pop("status", None)
|
||||||
|
return replayed_items
|
||||||
@@ -111,7 +111,7 @@ class XAIGrokProvider(LLMProvider):
|
|||||||
on_stream_recover: Callable[[], Awaitable[None]] | None = None,
|
on_stream_recover: Callable[[], Awaitable[None]] | None = None,
|
||||||
) -> LLMResponse:
|
) -> LLMResponse:
|
||||||
wire_model = _strip_model_prefix(model or self.default_model)
|
wire_model = _strip_model_prefix(model or self.default_model)
|
||||||
system_prompt, input_items = convert_messages(messages, include_item_ids=False)
|
system_prompt, input_items = convert_messages(messages)
|
||||||
|
|
||||||
stage = "oauth_token"
|
stage = "oauth_token"
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -151,6 +151,7 @@ class TestConvertMessages:
|
|||||||
assert items[0]["role"] == "assistant"
|
assert items[0]["role"] == "assistant"
|
||||||
assert items[0]["content"][0]["type"] == "output_text"
|
assert items[0]["content"][0]["type"] == "output_text"
|
||||||
assert items[0]["content"][0]["text"] == "I'll help"
|
assert items[0]["content"][0]["text"] == "I'll help"
|
||||||
|
assert "id" not in items[0]
|
||||||
|
|
||||||
def test_preserves_deepseek_reasoning_content(self):
|
def test_preserves_deepseek_reasoning_content(self):
|
||||||
_, items = convert_messages([
|
_, items = convert_messages([
|
||||||
@@ -167,7 +168,6 @@ class TestConvertMessages:
|
|||||||
"role": "assistant",
|
"role": "assistant",
|
||||||
"content": [{"type": "output_text", "text": "answer"}],
|
"content": [{"type": "output_text", "text": "answer"}],
|
||||||
"status": "completed",
|
"status": "completed",
|
||||||
"id": "msg_0",
|
|
||||||
},
|
},
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -212,27 +212,10 @@ class TestConvertMessages:
|
|||||||
}])
|
}])
|
||||||
assert items[0]["type"] == "function_call"
|
assert items[0]["type"] == "function_call"
|
||||||
assert items[0]["call_id"] == "call_abc"
|
assert items[0]["call_id"] == "call_abc"
|
||||||
assert items[0]["id"] == "fc_1"
|
assert "id" not in items[0]
|
||||||
assert items[0]["name"] == "get_weather"
|
assert items[0]["name"] == "get_weather"
|
||||||
assert items[0]["arguments"] == '{"city": "SF"}'
|
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):
|
def test_assistant_tool_call_history_repairs_malformed_arguments(self):
|
||||||
_, items = convert_messages([{
|
_, items = convert_messages([{
|
||||||
"role": "assistant",
|
"role": "assistant",
|
||||||
@@ -245,58 +228,32 @@ class TestConvertMessages:
|
|||||||
|
|
||||||
assert json.loads(items[0]["arguments"]) == {"path": "foo.txt"}
|
assert json.loads(items[0]["arguments"]) == {"path": "foo.txt"}
|
||||||
|
|
||||||
def test_duplicate_response_item_ids_are_made_unique(self):
|
def test_discards_provider_item_ids_without_changing_call_ids(self):
|
||||||
"""Codex rejects replayed Responses input items with duplicate ids."""
|
|
||||||
_, items = convert_messages([
|
_, items = convert_messages([
|
||||||
{
|
{
|
||||||
"role": "assistant",
|
"role": "assistant",
|
||||||
"content": None,
|
"content": None,
|
||||||
"tool_calls": [{
|
"tool_calls": [{
|
||||||
"id": "call_a|rs_same",
|
"id": "call_1|fc_1",
|
||||||
"function": {"name": "first", "arguments": "{}"},
|
"function": {"name": "get_weather", "arguments": "{}"},
|
||||||
}],
|
}],
|
||||||
},
|
},
|
||||||
{"role": "tool", "tool_call_id": "call_a|rs_same", "content": "ok"},
|
{"role": "tool", "tool_call_id": "call_1|fc_1", "content": "ok"},
|
||||||
{
|
|
||||||
"role": "assistant",
|
|
||||||
"content": None,
|
|
||||||
"tool_calls": [{
|
|
||||||
"id": "call_b|rs_same",
|
|
||||||
"function": {"name": "second", "arguments": "{}"},
|
|
||||||
}],
|
|
||||||
},
|
|
||||||
{"role": "tool", "tool_call_id": "call_b|rs_same", "content": "ok"},
|
|
||||||
])
|
])
|
||||||
function_call_ids = [
|
|
||||||
item["id"] for item in items if item.get("type") == "function_call"
|
|
||||||
]
|
|
||||||
assert function_call_ids == ["rs_same", "rs_same_2"]
|
|
||||||
assert len(function_call_ids) == len(set(function_call_ids))
|
|
||||||
|
|
||||||
def test_fallback_response_item_ids_are_unique_with_multiple_tool_calls(self):
|
assert all("id" not in item for item in items)
|
||||||
_, items = convert_messages([{
|
assert items[0]["call_id"] == "call_1"
|
||||||
"role": "assistant",
|
assert items[1]["call_id"] == "call_1"
|
||||||
"content": None,
|
|
||||||
"tool_calls": [
|
|
||||||
{"id": "call_a", "function": {"name": "first", "arguments": "{}"}},
|
|
||||||
{"id": "call_b", "function": {"name": "second", "arguments": "{}"}},
|
|
||||||
],
|
|
||||||
}])
|
|
||||||
function_call_ids = [
|
|
||||||
item["id"] for item in items if item.get("type") == "function_call"
|
|
||||||
]
|
|
||||||
assert function_call_ids == ["fc_0", "fc_0_2"]
|
|
||||||
assert len(function_call_ids) == len(set(function_call_ids))
|
|
||||||
|
|
||||||
def test_assistant_with_tool_calls_no_id(self):
|
def test_assistant_with_tool_calls_no_id(self):
|
||||||
"""Fallback IDs when tool_call.id is missing."""
|
"""Fallback call IDs still work when tool_call.id is missing."""
|
||||||
_, items = convert_messages([{
|
_, items = convert_messages([{
|
||||||
"role": "assistant",
|
"role": "assistant",
|
||||||
"content": None,
|
"content": None,
|
||||||
"tool_calls": [{"function": {"name": "f1", "arguments": "{}"}}],
|
"tool_calls": [{"function": {"name": "f1", "arguments": "{}"}}],
|
||||||
}])
|
}])
|
||||||
assert items[0]["call_id"] == "call_0"
|
assert items[0]["call_id"] == "call_0"
|
||||||
assert items[0]["id"].startswith("fc_")
|
assert "id" not in items[0]
|
||||||
|
|
||||||
def test_tool_message(self):
|
def test_tool_message(self):
|
||||||
_, items = convert_messages([{
|
_, items = convert_messages([{
|
||||||
|
|||||||
Reference in new issue
Block a user