Return a reduced copy of the row whose JSON-encoded size <= cap_bytes. The input row is not mutated. Drop order: response_text -> response_tool_calls -> request_messages (oldest first).
(
row: dict[str, Any], *, cap_bytes: int = 64 * 1024
)
| 268 | # --- Truncation --------------------------------------------------------------- |
| 269 | |
| 270 | def truncate_content_payload( |
| 271 | row: dict[str, Any], *, cap_bytes: int = 64 * 1024 |
| 272 | ) -> tuple[dict[str, Any], bool]: |
| 273 | """Return a reduced copy of the row whose JSON-encoded size <= cap_bytes. |
| 274 | |
| 275 | The input row is not mutated. Drop order: |
| 276 | response_text -> response_tool_calls -> request_messages (oldest first). |
| 277 | """ |
| 278 | out = dict(row) |
| 279 | |
| 280 | def _size() -> int: |
| 281 | return len(json.dumps(out, default=str, ensure_ascii=False).encode("utf-8")) |
| 282 | |
| 283 | if _size() <= cap_bytes: |
| 284 | return out, False |
| 285 | |
| 286 | if out.get("response_text"): |
| 287 | out["response_text"] = "" |
| 288 | if _size() <= cap_bytes: |
| 289 | return out, True |
| 290 | |
| 291 | if out.get("response_tool_calls"): |
| 292 | out["response_tool_calls"] = [] |
| 293 | if _size() <= cap_bytes: |
| 294 | return out, True |
| 295 | |
| 296 | msgs = list(out.get("request_messages") or []) |
| 297 | while msgs and _size() > cap_bytes: |
| 298 | msgs.pop(0) |
| 299 | out["request_messages"] = msgs |
| 300 | return out, True |