The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(api-server): chained /v1/responses turns store each message once
teknium13305af8d992b
diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]new file mode 100644index 00000000000..4fc02b56c47--- /dev/null+++ b/contributors/emails/[email protected]@@ -0,0 +1 @@+berkantaydiff --git a/gateway/platforms/api_server_openai_routes.py b/gateway/platforms/api_server_openai_routes.pyindex 96f4183d0f6..f4a3434955a 100644--- a/gateway/platforms/api_server_openai_routes.py+++ b/gateway/platforms/api_server_openai_routes.py@@ -88,6 +88,28 @@ def _message_item(text: Any) -> Dict[str, Any]:"content": [{"type": "output_text", "text": text}]}+_TRANSCRIPT_IDENTITY_KEYS = ("role", "content", "tool_calls", "tool_call_id")+++def _same_transcript_prefix(agent_messages: List[Any], prefix: List[Any]) -> bool:+ """True when ``agent_messages`` starts with ``prefix`` by what each message *says*.++ The API layer builds bare ``{"role", "content"}`` dicts while the agent stamps its copies+ with ``timestamp`` / ``_db_persisted`` / ``reasoning`` / ``finish_reason``; whole-dict+ equality therefore never matched and every chained turn re-appended the full prior+ transcript (#95137, #101644, #82513)."""+ if len(agent_messages) < len(prefix):+ return False+ for got, want in zip(agent_messages, prefix):+ if not isinstance(got, dict) or not isinstance(want, dict):+ if got != want:+ return False+ continue+ if any(got.get(k) != want.get(k) for k in _TRANSCRIPT_IDENTITY_KEYS):+ return False+ return True++def _trim_tool_items(items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:"""Trim large tool payloads in place so response.completed stays under ~100KB (clientsalready received the full details via the incremental events)."""@@ -998,9 +1020,9 @@ class OpenAICompatRoutesMixin:return 0prior = list(conversation_history)expected_prefix = prior + [{"role": "user", "content": user_message}]- if agent_messages[:len(expected_prefix)] == expected_prefix:+ if _same_transcript_prefix(agent_messages, expected_prefix):return len(expected_prefix)- if prior and agent_messages[:len(prior)] == prior:+ if prior and _same_transcript_prefix(agent_messages, prior):return len(prior)return 0diff --git a/tests/gateway/test_api_server_responses_history_dedupe.py b/tests/gateway/test_api_server_responses_history_dedupe.pynew file mode 100644index 00000000000..a7ca3910c1f--- /dev/null+++ b/tests/gateway/test_api_server_responses_history_dedupe.py@@ -0,0 +1,46 @@+"""Stored /v1/responses transcripts must not duplicate history across chained turns.++The agent's ``result["messages"]`` copies of the prior history carry ``timestamp`` /+``_db_persisted`` / ``reasoning`` / ``finish_reason`` that the API layer's bare+``{"role", "content"}`` dicts never have, so a whole-dict prefix check failed every turn and+the stored history grew 3 -> 8 -> 17 instead of 2 -> 4 -> 6 (#95137, #101644, #82513).+"""++from agent.agent_runtime_helpers import repair_message_sequence+from agent.message_metadata import append_message+from gateway.platforms.api_server import APIServerAdapter+++class _Agent:+ api_mode = "chat_completions"+ session_id = "s"+++def _agent_turn(history, user_message, answer):+ """Real producers: turn_context appends the user row via append_message (stamps timestamp)."""+ messages = list(history)+ append_message(messages, {"role": "user", "content": user_message})+ repair_message_sequence(_Agent(), messages)+ append_message(messages, {"role": "assistant", "content": answer, "reasoning": "r", "finish_reason": "stop"})+ return {"messages": messages}+++def test_chained_responses_turns_store_each_message_once():+ build = APIServerAdapter._build_response_conversation_history+ history, counts = [], []+ for turn, prompt in enumerate(["Remember TOKEN-ABC.", "What token?", "Third"]):+ answer = f"answer {turn}"+ history = build(history, prompt, _agent_turn(history, prompt, answer), answer)+ counts.append(len(history))+ assert counts == [2, 4, 6]+ assert [m["role"] for m in history] == ["user", "assistant"] * 3+++def test_divergent_transcript_still_falls_back_to_appending():+ build = APIServerAdapter._build_response_conversation_history+ prior = [{"role": "user", "content": "a"}, {"role": "assistant", "content": "b"}]+ # A transcript whose first row differs in what it says is not a prefix match.+ result = {"messages": [{"role": "user", "content": "DIFFERENT", "timestamp": 1.0},+ {"role": "assistant", "content": "d"}]}+ stored = build(prior, "c", result, "d")+ assert [m["content"] for m in stored] == ["a", "b", "c", "DIFFERENT", "d"]