Place the DeepSeek relocated-volatile sections AFTER the conversation. Wrapped as ambient `` `` context. Merged into the trailing user message when that is a plain user turn (string content, or a content-block list with no ``tool_result``) so the wire keeps strict us
(
api_messages: list[dict[str, Any]], tail_text: str
)
| 458 | |
| 459 | |
| 460 | def _append_session_context_tail( |
| 461 | api_messages: list[dict[str, Any]], tail_text: str |
| 462 | ) -> list[dict[str, Any]]: |
| 463 | """Place the DeepSeek relocated-volatile sections AFTER the conversation. |
| 464 | |
| 465 | Wrapped as ambient ``<system-reminder>`` context. Merged into the trailing |
| 466 | user message when that is a plain user turn (string content, or a |
| 467 | content-block list with no ``tool_result``) so the wire keeps strict |
| 468 | user/assistant alternation. Otherwise — e.g. the turn ends in a tool result |
| 469 | (which converts to ``role:tool`` on the wire) — appended as a standalone |
| 470 | trailing user message, which lands correctly after the tool messages. |
| 471 | Returns a new list; ``api_messages`` is not mutated. |
| 472 | """ |
| 473 | reminder = ( |
| 474 | "<system-reminder>\n" |
| 475 | "Current session/environment context (ambient — not a new user request):\n" |
| 476 | f"{tail_text}\n" |
| 477 | "</system-reminder>" |
| 478 | ) |
| 479 | last = api_messages[-1] if api_messages else None |
| 480 | if isinstance(last, dict) and last.get("role") == "user": |
| 481 | content = last.get("content") |
| 482 | if isinstance(content, str): |
| 483 | merged = dict(last) |
| 484 | merged["content"] = f"{content}\n\n{reminder}" if content else reminder |
| 485 | return [*api_messages[:-1], merged] |
| 486 | if isinstance(content, list) and not any( |
| 487 | isinstance(b, dict) and b.get("type") == "tool_result" for b in content |
| 488 | ): |
| 489 | merged = dict(last) |
| 490 | merged["content"] = [*content, {"type": "text", "text": reminder}] |
| 491 | return [*api_messages[:-1], merged] |
| 492 | return [*api_messages, {"role": "user", "content": reminder}] |
| 493 | |
| 494 | |
| 495 | async def _call_model_sync( |