The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
chore: merge origin/main (resolve gateway/platforms/api_server_openai_routes.py)
teknium16b415f87547a
diff --cc gateway/platforms/api_server_openai_routes.pyindex 82c0281fc78,db2edf0ac21..a55d2d06a2d--- a/gateway/platforms/api_server_openai_routes.py+++ b/gateway/platforms/api_server_openai_routes.py@@@ -88,72 -88,37 +88,103 @@@ def _message_item(text: Any) -> Dict[st"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 _cap_text(text: str, keep: int) -> str:+ """Head of ``text`` plus a marker saying how much was cut (the Responses truncation rule)."""+ return text[:keep] + "...[" + str(len(text) - keep) + " more chars]"+++def _cap_history_tool_outputs(history: List[Dict[str, Any]], max_chars: int) -> List[Dict[str, Any]]:+ """Copy of ``history`` with tool outputs and string tool-call arguments longer than+ ``max_chars`` cut down. Only tool rows and ``tool_calls`` blobs change; user/assistant text+ is left alone, and the agent's own transcript rows are never mutated (rows are copied).+ Opt-in via gateway.api_server.history_tool_output_max_chars: a single stored snapshot+ embeds the full cumulative history, so a few large tool outputs pushed one+ response_store.db write to ~677 KB (#82513)."""+ if max_chars <= 0:+ return history+ out: List[Dict[str, Any]] = []+ for msg in history:+ if not isinstance(msg, dict):+ out.append(msg)+ continue+ content = msg.get("content")+ if msg.get("role") == "tool" and isinstance(content, str) and len(content) > max_chars:+ msg = {**msg, "content": _cap_text(content, max_chars)}+ tool_calls = msg.get("tool_calls")+ if msg.get("role") == "assistant" and isinstance(tool_calls, list):+ capped_calls = []+ for call in tool_calls:+ fn = call.get("function") if isinstance(call, dict) else None+ raw = fn.get("arguments") if isinstance(fn, dict) else None+ if isinstance(raw, str) and len(raw) > max_chars:+ try:+ args = json.loads(raw)+ except ValueError:+ args = None+ if isinstance(args, dict):+ for k, v in args.items():+ if isinstance(v, str) and len(v) > max_chars:+ args[k] = _cap_text(v, max_chars)+ call = {**call, "function": {**fn, "arguments": json.dumps(args)}}+ capped_calls.append(call)+ msg = {**msg, "tool_calls": capped_calls}+ out.append(msg)+ return out+++ def _reasoning_item(text: str) -> Dict[str, Any]:+ """Completed Responses ``reasoning`` output item (same shape the SSE writer closes with)."""+ return {"id": f"rs_{uuid.uuid4().hex[:24]}", "type": "reasoning", "status": "completed",+ "summary": [{"type": "summary_text", "text": text}]}+++ def _is_reasoning_input_item(item: Any) -> bool:+ """Echoed-back ``reasoning`` output item: Responses SDK clients replay a prior response's+ ``output`` list as the next ``input``. It carries no message content, so it must be+ skipped rather than parsed into an empty ``user`` turn (#99552)."""+ return isinstance(item, dict) and item.get("type") == "reasoning"+++ def _turn_reasoning_text(+ conversation_history: List[Dict[str, Any]], user_message: Any, result: Dict[str, Any]) -> str:+ """Reasoning the model produced on this turn, joined for a non-streaming+ ``message.reasoning_content``. Read from the assistant messages the agent already+ persisted (``build_assistant_message`` stores the structured reasoning under+ ``reasoning``) rather than re-accumulating callback deltas, so it is exactly what the+ stream would have carried and cannot double-count the post-response fallback."""+ messages = result.get("messages") if isinstance(result, dict) else None+ if not isinstance(messages, list):+ return ""+ start = OpenAICompatRoutesMixin._response_messages_turn_start_index(+ conversation_history, user_message, result)+ parts = [m["reasoning"] for m in messages[start:]+ if isinstance(m, dict) and m.get("role") == "assistant"+ and isinstance(m.get("reasoning"), str) and m["reasoning"].strip()]+ return "\n\n".join(parts)++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)."""