fix(llm): keep mid-conversation system messages in place

Anthropic Messages has one top-level system and the Responses API one
instructions field. The Anthropic converter kept only the last system
message, so a deep_solve context checkpoint or a Mastery lesson notice
replaced the whole system prompt. The Responses converter joined every
system message into instructions, so each appended notice rewrote the
start of the request.

Leading system messages still become system/instructions. A later one
stays where it was: an Anthropic user text block labelled [System note]
(after any tool_result blocks), or a Responses developer message.
This commit is contained in:
zszz3
2026-12-02 15:44:33 +08:00
parent 99804c9d81
commit 37f5565bb2
3 changed files with 316 additions and 17 deletions

View File

@@ -39,6 +39,11 @@ def _gen_tool_id() -> str:
DEFAULT_ANTHROPIC_MODEL = "claude-sonnet-5-5"
# Prefix for a system message that arrives after the conversation has started.
# Anthropic has a single top-level system prompt, so such a message is sent in
# place as user text under this label.
SYSTEM_NOTE_LABEL = "[System note]"
class AnthropicProvider(LLMProvider):
"""LLM provider using the native Anthropic SDK for Claude models."""
@@ -110,8 +115,17 @@ class AnthropicProvider(LLMProvider):
self,
messages: list[dict[str, Any]],
) -> tuple[str | list[dict[str, Any]], list[dict[str, Any]]]:
"""Return ``(system, anthropic_messages)``."""
system: str | list[dict[str, Any]] = ""
"""Return ``(system, anthropic_messages)``.
Anthropic takes one top-level ``system``, so only the system messages
that open the conversation become it. A system message further down
(a solve checkpoint, a lesson notice, a history summary) stays where it
is as a labelled user text block: lifting it into ``system`` would
either replace the opening instructions or rewrite the start of every
later request, and the model would lose where in the conversation it
was said.
"""
leading: list[Any] = []
raw: list[dict[str, Any]] = []
for msg in messages:
@@ -119,22 +133,19 @@ class AnthropicProvider(LLMProvider):
content = msg.get("content")
if role == "system":
system = content if isinstance(content, (str, list)) else str(content or "")
text = self._system_text(content)
if not text:
continue
if raw:
self._append_user_blocks(
raw, [{"type": "text", "text": f"{SYSTEM_NOTE_LABEL}\n{text}"}]
)
else:
leading.append(content)
continue
if role == "tool":
block = self._tool_result_block(msg)
if raw and raw[-1]["role"] == "user":
prev_c = raw[-1]["content"]
if isinstance(prev_c, list):
prev_c.append(block)
else:
raw[-1]["content"] = [
{"type": "text", "text": prev_c or ""},
block,
]
else:
raw.append({"role": "user", "content": [block]})
self._append_user_blocks(raw, [self._tool_result_block(msg)])
continue
if role == "assistant":
@@ -150,8 +161,58 @@ class AnthropicProvider(LLMProvider):
)
continue
system: str | list[dict[str, Any]] = ""
if len(leading) == 1:
system = leading[0] if isinstance(leading[0], (str, list)) else str(leading[0])
elif leading:
system = [
block
for content in leading
for block in (
content
if isinstance(content, list)
else [{"type": "text", "text": str(content)}]
)
]
return system, self._merge_consecutive(raw)
@staticmethod
def _system_text(content: Any) -> str:
if isinstance(content, list):
return "\n".join(
part["text"]
for part in content
if isinstance(part, dict)
and part.get("type") == "text"
and isinstance(part.get("text"), str)
and part["text"]
)
return content if isinstance(content, str) else str(content or "")
@staticmethod
def _append_user_blocks(raw: list[dict[str, Any]], blocks: list[dict[str, Any]]) -> None:
"""Add *blocks* to the trailing user message, or start one.
Anthropic requires a user message's ``tool_result`` blocks to come
before any other content, so a tool result is placed after the leading
results already there rather than after a system note.
"""
if not raw or raw[-1]["role"] != "user":
raw.append({"role": "user", "content": list(blocks)})
return
prev_c = raw[-1]["content"]
if not isinstance(prev_c, list):
prev_c = [{"type": "text", "text": prev_c or ""}]
raw[-1]["content"] = prev_c
for block in blocks:
if block.get("type") == "tool_result":
at = 0
while at < len(prev_c) and prev_c[at].get("type") == "tool_result":
at += 1
prev_c.insert(at, block)
else:
prev_c.append(block)
@staticmethod
def _tool_id(raw: Any) -> str:
# Preserve native IDs, but encode foreign IDs without collapsing distinct

View File

@@ -39,7 +39,14 @@ def _replay_output_item(item: dict[str, Any]) -> dict[str, Any]:
def convert_messages(messages: 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.
The system messages that open the conversation become ``instructions``. A
system message further down (a solve checkpoint, a lesson notice, a
history summary) stays in place as a ``developer`` input item: folding it
into ``instructions`` would change the start of the request every time it
changes, so nothing after it could be served from the prompt cache.
"""
system_parts: list[str] = []
input_items: list[dict[str, Any]] = []
@@ -58,7 +65,12 @@ def convert_messages(messages: list[dict[str, Any]]) -> tuple[str, list[dict[str
and part["text"]
)
if isinstance(content, str) and content:
system_parts.append(content)
if input_items:
input_items.append(
{"role": "developer", "content": [{"type": "input_text", "text": content}]}
)
else:
system_parts.append(content)
continue
if role == "user":

View File

@@ -0,0 +1,226 @@
"""A system message after the conversation has started stays where it is.
The chat loop adds ``role=system`` messages mid-conversation: deep_solve folds
finished steps into a ``[Context checkpoint]`` plus a state message, and
Mastery appends a lesson notice before a request. Anthropic has a single
top-level ``system`` and the Responses API a single ``instructions`` field;
lifting these messages into that slot either replaced the opening
instructions (Anthropic kept only the last system message) or rewrote the
start of every later request (Responses concatenated all of them).
"""
from __future__ import annotations
from copy import deepcopy
from typing import Any
import pytest
from deeptutor.services.llm.provider_core.openai_responses import convert_messages
pytest.importorskip("anthropic")
from deeptutor.services.llm.provider_core.anthropic_provider import ( # noqa: E402
SYSTEM_NOTE_LABEL,
AnthropicProvider,
)
POLICY = "You are DeepTutor. Tool rules. Solve workflow."
def _provider() -> AnthropicProvider:
return AnthropicProvider(api_key="test-key", default_model="claude-sonnet-5-5")
def _tool_round(call_id: str, result: str) -> list[dict[str, Any]]:
return [
{
"role": "assistant",
"content": "",
"tool_calls": [
{
"id": call_id,
"type": "function",
"function": {"name": "solve_plan", "arguments": "{}"},
}
],
},
{"role": "tool", "tool_call_id": call_id, "content": result},
]
def _solve_after_checkpoint() -> list[dict[str, Any]]:
"""The shape ``AgentLoop._fold_context_checkpoint`` leaves behind."""
return [
{"role": "system", "content": POLICY},
{"role": "user", "content": "Solve x^2=4"},
*_tool_round("c1", "plan ok"),
{"role": "system", "content": "[Context checkpoint]\nStep 1 done: factored."},
{"role": "system", "content": "State: step 2 of 3"},
]
# ---------------------------------------------------------------------------
# Anthropic Messages
# ---------------------------------------------------------------------------
def test_anthropic_keeps_the_opening_system_prompt_after_a_checkpoint() -> None:
system, messages = _provider()._convert_messages(_solve_after_checkpoint())
assert system == POLICY
last = messages[-1]
assert last["role"] == "user"
assert [block["type"] for block in last["content"]] == ["tool_result", "text", "text"]
assert last["content"][1]["text"] == (
f"{SYSTEM_NOTE_LABEL}\n[Context checkpoint]\nStep 1 done: factored."
)
assert last["content"][2]["text"] == f"{SYSTEM_NOTE_LABEL}\nState: step 2 of 3"
def test_anthropic_lesson_notice_does_not_replace_the_playbook() -> None:
playbook = "Mastery playbook"
notice = "Call mastery_prepare_lesson before teaching this objective."
system, messages = _provider()._convert_messages(
[
{"role": "system", "content": playbook},
{"role": "user", "content": "Teach me"},
{"role": "system", "content": notice},
]
)
assert system == playbook
assert messages == [
{
"role": "user",
"content": [
{"type": "text", "text": "Teach me"},
{"type": "text", "text": f"{SYSTEM_NOTE_LABEL}\n{notice}"},
],
}
]
def test_anthropic_tool_result_stays_ahead_of_a_system_note() -> None:
"""Anthropic rejects a user message whose tool_result follows other content."""
_, messages = _provider()._convert_messages(
[
{"role": "system", "content": POLICY},
{"role": "user", "content": "Solve"},
{
"role": "assistant",
"content": "",
"tool_calls": [
{"id": "a", "type": "function", "function": {"name": "x", "arguments": "{}"}},
{"id": "b", "type": "function", "function": {"name": "y", "arguments": "{}"}},
],
},
{"role": "tool", "tool_call_id": "a", "content": "A"},
{"role": "system", "content": "note"},
{"role": "tool", "tool_call_id": "b", "content": "B"},
]
)
content = messages[-1]["content"]
assert [block["type"] for block in content] == ["tool_result", "tool_result", "text"]
assert [block.get("tool_use_id") for block in content[:2]] == ["a", "b"]
def test_anthropic_a_checkpoint_leaves_the_earlier_request_as_a_prefix() -> None:
"""The fold appends after the history it keeps, so the cached prefix holds."""
provider = _provider()
before = _solve_after_checkpoint()[:4]
system_before, messages_before = provider._convert_messages(deepcopy(before))
system_after, messages_after = provider._convert_messages(_solve_after_checkpoint())
assert system_after == system_before
assert messages_after[:-1] == messages_before[:-1]
prior_tail = messages_before[-1]["content"]
assert messages_after[-1]["content"][: len(prior_tail)] == prior_tail
def test_anthropic_joins_several_opening_system_messages_in_order() -> None:
system, messages = _provider()._convert_messages(
[
{"role": "system", "content": "Policy"},
{"role": "system", "content": [{"type": "text", "text": "Locale"}]},
{"role": "system", "content": ""},
{"role": "user", "content": "Hi"},
]
)
assert system == [{"type": "text", "text": "Policy"}, {"type": "text", "text": "Locale"}]
assert messages == [{"role": "user", "content": "Hi"}]
def test_anthropic_single_opening_block_list_is_passed_through() -> None:
blocks = [{"type": "text", "text": "Policy", "cache_control": {"type": "ephemeral"}}]
system, _ = _provider()._convert_messages(
[{"role": "system", "content": blocks}, {"role": "user", "content": "Hi"}]
)
assert system == blocks
def test_anthropic_empty_later_system_message_adds_nothing() -> None:
system, messages = _provider()._convert_messages(
[
{"role": "system", "content": POLICY},
{"role": "user", "content": "Hi"},
{"role": "system", "content": None},
{"role": "system", "content": []},
]
)
assert system == POLICY
assert messages == [{"role": "user", "content": "Hi"}]
def test_anthropic_request_kwargs_cache_the_opening_system_prompt() -> None:
kwargs = _provider()._build_kwargs(
messages=_solve_after_checkpoint(),
tools=None,
model=None,
max_tokens=256,
temperature=0.0,
reasoning_effort=None,
tool_choice=None,
)
assert kwargs["system"] == [
{"type": "text", "text": POLICY, "cache_control": {"type": "ephemeral"}}
]
assert kwargs["messages"][-1]["content"][-1]["text"].endswith("State: step 2 of 3")
# ---------------------------------------------------------------------------
# Responses API
# ---------------------------------------------------------------------------
def test_responses_keeps_a_later_system_message_in_place() -> None:
messages = _solve_after_checkpoint()
original = deepcopy(messages)
instructions, items = convert_messages(messages)
assert instructions == POLICY
assert [item.get("type") or item.get("role") for item in items] == [
"user",
"function_call",
"function_call_output",
"developer",
"developer",
]
assert items[3] == {
"role": "developer",
"content": [{"type": "input_text", "text": "[Context checkpoint]\nStep 1 done: factored."}],
}
assert messages == original
def test_responses_a_checkpoint_does_not_change_the_instructions() -> None:
before_instructions, before_items = convert_messages(_solve_after_checkpoint()[:4])
after_instructions, after_items = convert_messages(_solve_after_checkpoint())
assert after_instructions == before_instructions
assert after_items[: len(before_items)] == before_items