Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(agent): deliver recovery steering as user messages with inline system tags (#1112)

lorenzozane747268999413
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index b71005db9..9b2215e0f 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -1071,8 +1071,8 @@ class AgentLoop:
break
trace.write({"type": "content_filter_skipped", "iter": current_iter})
messages.append({
- "role": "system",
- "content": CONTENT_FILTER_SKIP_MESSAGE,
+ "role": "user",
+ "content": f"<system>{CONTENT_FILTER_SKIP_MESSAGE}</system>",
})
continue
@@ -1129,18 +1129,16 @@ class AgentLoop:
)
messages.append(
{
- "role": "system",
- "content": self._grounding.recovery_prompt(
- recovery, validation
- ),
+ "role": "user",
+ "content": f"<system>{self._grounding.recovery_prompt(recovery, validation)}</system>",
}
)
final_content = ""
continue
messages.append(
{
- "role": "system",
- "content": self._grounding.correction_prompt(validation),
+ "role": "user",
+ "content": f"<system>{self._grounding.correction_prompt(validation)}</system>",
}
)
final_content = ""
diff --git a/agent/src/swarm/worker.py b/agent/src/swarm/worker.py
index d5050df60..8b58cf49f 100644
--- a/agent/src/swarm/worker.py
+++ b/agent/src/swarm/worker.py
@@ -683,8 +683,8 @@ def run_worker(
{"iteration": iteration, "content_filter_count": content_filter_count},
)
messages.append({
- "role": "system",
- "content": CONTENT_FILTER_SKIP_MESSAGE,
+ "role": "user",
+ "content": f"<system>{CONTENT_FILTER_SKIP_MESSAGE}</system>",
})
continue
diff --git a/agent/tests/message_roles_helpers.py b/agent/tests/message_roles_helpers.py
new file mode 100644
index 000000000..2845d2457
--- /dev/null
+++ b/agent/tests/message_roles_helpers.py
@@ -0,0 +1,28 @@
+"""Shared invariant: the LLM never sees a system message after index 0.
+
+Anthropic's Messages API accepts only a single leading ``system`` block;
+``langchain_anthropic`` raises ``ValueError`` on a mid-conversation system
+message. Every mid-conversation steering prompt must therefore be a
+``{"role": "user", ...}`` message carrying an inline ``<system>`` tag — the
+repo's canonical pattern (``loop.py`` background results and auto-compact).
+This helper enforces that invariant over every message list a run handed to
+the model.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+
+def assert_system_messages_only_lead(history: list[list[dict[str, Any]]]) -> None:
+ """Assert no captured message list has a system role after index 0.
+
+ Args:
+ history: One message list per LLM call, in call order.
+ """
+ for call_index, messages in enumerate(history):
+ for i, message in enumerate(messages):
+ assert message.get("role") != "system" or i == 0, (
+ f"mid-conversation system message at index {i} of LLM call "
+ f"{call_index}: {message!r}"
+ )
diff --git a/agent/tests/test_agent_grounding.py b/agent/tests/test_agent_grounding.py
index 6f4539865..2506e848e 100644
--- a/agent/tests/test_agent_grounding.py
+++ b/agent/tests/test_agent_grounding.py
@@ -19,6 +19,7 @@ from src.agent.grounding import (
from src.agent.loop import AgentLoop, _is_tool_success
from src.agent.tools import BaseTool, ToolRegistry
from src.agent.trace import TraceWriter
+from tests.message_roles_helpers import assert_system_messages_only_lead
def _resolver_payload(
@@ -860,6 +861,7 @@ class _CorrectingLLM:
)
),
]
+ self.messages_history: list[list[dict[str, Any]]] = []
def stream_chat(
self,
@@ -869,6 +871,7 @@ class _CorrectingLLM:
on_reasoning_chunk: Callable[[str], None] | None = None,
should_cancel: Callable[[], bool] | None = None,
) -> _Response:
+ self.messages_history.append(list(messages))
response = self.responses.pop(0)
if response.content and on_text_chunk:
on_text_chunk(response.content)
@@ -888,9 +891,10 @@ def test_agent_loop_rejects_then_corrects_ungrounded_final_answer(
registry.register(resolver)
registry.register(market)
events: list[tuple[str, dict[str, Any]]] = []
+ llm = _CorrectingLLM()
agent = AgentLoop(
registry=registry,
- llm=_CorrectingLLM(),
+ llm=llm,
max_iterations=4,
event_callback=lambda event, data: events.append((event, data)),
)
@@ -904,6 +908,8 @@ def test_agent_loop_rejects_then_corrects_ungrounded_final_answer(
assert "1.137" in result["content"]
assert "0.881" not in result["content"]
assert market.calls == 1
+ # The correction nudge must not be a mid-conversation system message.
+ assert_system_messages_only_lead(llm.messages_history)
streamed = "".join(
data.get("delta", "") for event, data in events if event == "text_delta"
)
diff --git a/agent/tests/test_agent_loop_content_filter.py b/agent/tests/test_agent_loop_content_filter.py
index 6a6407c0f..09284eb92 100644
--- a/agent/tests/test_agent_loop_content_filter.py
+++ b/agent/tests/test_agent_loop_content_filter.py
@@ -12,6 +12,7 @@ from typing import Any, Callable
import pytest
from src.providers.chat import LLMResponse, ToolCallRequest
+from tests.message_roles_helpers import assert_system_messages_only_lead
class _ContentFilterLoopLLM:
@@ -131,19 +132,22 @@ def test_content_filter_trace_entry(
def test_content_filter_injects_system_message(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
- """System message is injected into messages after content filter hit."""
+ """Steering text is a user message with an inline <system> tag, never mid-conversation system."""
llm = _ContentFilterLoopLLM(filter_count=1, final_content="Done.")
_run(monkeypatch, tmp_path, llm)
assert llm.calls == 2
messages_on_second_call = llm.messages_history[1]
- system_messages = [
+ steering = [
m for m in messages_on_second_call
if "content moderation" in str(m.get("content", ""))
]
- assert len(system_messages) == 1
- assert "[SYSTEM]" in system_messages[0]["content"]
+ assert len(steering) == 1
+ assert steering[0]["role"] == "user"
+ assert steering[0]["content"].startswith("<system>")
+ assert steering[0]["content"].endswith("</system>")
+ assert_system_messages_only_lead(llm.messages_history)
def test_multiple_content_filter_hits(
diff --git a/agent/tests/test_grounding_recovery.py b/agent/tests/test_grounding_recovery.py
index d89a759e9..e4976a3a0 100644
--- a/agent/tests/test_grounding_recovery.py
+++ b/agent/tests/test_grounding_recovery.py
@@ -25,6 +25,7 @@ from src.agent.grounding import (
GroundingLedger,
)
from src.providers.chat import LLMResponse
+from tests.message_roles_helpers import assert_system_messages_only_lead
pytestmark = pytest.mark.unit
@@ -326,6 +327,7 @@ class _FailingDraftLLM:
def __init__(self) -> None:
self.calls = 0
+ self.messages_history: list[list[dict[str, Any]]] = []
def stream_chat(
self,
@@ -336,6 +338,7 @@ class _FailingDraftLLM:
should_cancel: Callable[[], bool] | None = None,
) -> LLMResponse:
self.calls += 1
+ self.messages_history.append(list(messages))
draft = "机器人ETF 现价 1.171,建议买入。"
if on_text_chunk:
on_text_chunk(draft)
@@ -378,5 +381,8 @@ def test_loop_runs_recovery_before_fallback(
# Symbol resolution budget is two: two recovery turns, then fallback.
assert [e.get("action") for e in recovery_entries] == ["search_symbol", "search_symbol"]
assert llm.calls >= 3
+ # Recovery and correction steering must never be mid-conversation system
+ # messages: Anthropic only accepts a single leading system block.
+ assert_system_messages_only_lead(llm.messages_history)
# The run still terminates fail-closed once recovery is exhausted.
assert result["content"]
diff --git a/agent/tests/test_swarm_worker_content_filter.py b/agent/tests/test_swarm_worker_content_filter.py
index 6718e15db..ff67eefbd 100644
--- a/agent/tests/test_swarm_worker_content_filter.py
+++ b/agent/tests/test_swarm_worker_content_filter.py
@@ -15,6 +15,7 @@ from src.providers.chat import LLMResponse, ToolCallRequest
from src.swarm.models import SwarmAgentSpec, SwarmEvent, SwarmTask, WorkerResult
import src.swarm.worker as worker_mod
from src.swarm.worker import run_worker
+from tests.message_roles_helpers import assert_system_messages_only_lead
FINAL_TEXT = (
"# BTC-USDT — Short-Term View\n\n"
@@ -125,7 +126,7 @@ def test_content_filter_event_emitted(monkeypatch, tmp_path):
def test_content_filter_system_message_injected(monkeypatch, tmp_path):
- """A system message is injected after content-filter skip."""
+ """Steering text is injected as a user message with an inline system tag."""
llm = _ScriptedChatLLM([
LLMResponse(content="", content_filter_triggered=True),
LLMResponse(content=FINAL_TEXT),
@@ -135,11 +136,15 @@ def test_content_filter_system_message_injected(monkeypatch, tmp_path):
assert llm.calls == 2
second_call_messages = llm.received_messages[1]
- system_msgs = [
+ steering = [
m for m in second_call_messages
- if m.get("role") == "system" and "content moderation" in m.get("content", "")
+ if "content moderation" in m.get("content", "")
]
- assert len(system_msgs) == 1
+ assert len(steering) == 1
+ assert steering[0]["role"] == "user"
+ assert steering[0]["content"].startswith("<system>")
+ assert steering[0]["content"].endswith("</system>")
+ assert_system_messages_only_lead(llm.received_messages)
def test_multiple_content_filters_increment_counter(monkeypatch, tmp_path):