"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(loop,providers): prevent assistant prefill errors + configurable Kimi User-Agent (#248)
卫斯李d0ff3599c1f4
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.pyindex 15fda95a4..a7a3ebb40 100644--- a/agent/src/agent/loop.py+++ b/agent/src/agent/loop.py@@ -553,8 +553,7 @@ class AgentLoop:notifs = bg.drain_notifications()if notifs:notif_text = "\n".join(f"[bg:{n['task_id']}] {n['status']}: {n['result']}" for n in notifs)- messages.append({"role": "user", "content": f"<background-results>\n{notif_text}\n</background-results>"})- messages.append({"role": "assistant", "content": "Noted background results."})+ messages.append({"role": "user", "content": f"<background-results>\n{notif_text}\n</background-results>\n\n<system>Continue processing with the background results above.</system>"})# Layer 1: microcompact (every iteration)_microcompact(messages)@@ -1422,8 +1421,7 @@ class AgentLoop:messages.clear()messages.append(system_msg)- messages.append({"role": "user", "content": compressed})- messages.append({"role": "assistant", "content": "Understood. Continuing from the summary."})+ messages.append({"role": "user", "content": f"{compressed}\n\n<system>Continue from the summary above.</system>"})messages.extend(tail)# Fix orphaned tool pairs in the reconstructed message listdiff --git a/agent/src/providers/llm.py b/agent/src/providers/llm.pyindex 5e9447c08..aca6f5679 100644--- a/agent/src/providers/llm.py+++ b/agent/src/providers/llm.py@@ -633,5 +633,10 @@ def build_llm(*, model_name: Optional[str] = None, callbacks: Any = None) -> Any"vibe_provider": provider,}if caps.default_headers:- kwargs["default_headers"] = dict(caps.default_headers)+ headers = dict(caps.default_headers)+ if caps.name == "moonshot":+ custom_ua = os.getenv("MOONSHOT_USER_AGENT", "").strip()+ if custom_ua:+ headers["User-Agent"] = custom_ua+ kwargs["default_headers"] = headersreturn ChatOpenAIWithReasoning(**kwargs)diff --git a/agent/tests/test_agent_loop_no_assistant_prefill.py b/agent/tests/test_agent_loop_no_assistant_prefill.pynew file mode 100644index 000000000..f908a231e--- /dev/null+++ b/agent/tests/test_agent_loop_no_assistant_prefill.py@@ -0,0 +1,89 @@+"""Regression test: agent loop must not end messages with assistant prefill.++Claude Opus 4.8+ (and other new Anthropic models) reject API requests+when the conversation ends with an assistant-role message, because the+API treats it as an "assistant prefill" which these models no longer+support. Two code paths in AgentLoop used to emit such messages:+background notification acknowledgments and auto-compact handoff notes.+"""++from __future__ import annotations++from pathlib import Path+from typing import Any++from src.agent.loop import AgentLoop+++class _StubLLM:+ """ChatLLM stub that returns text then an answer after one tool call."""++ def __init__(self) -> None:+ self.model_name = "claude-opus-4-8-20250219"++ _call_count = 0++ class _Response:+ content: str = "Here is the analysis of AAPL stock."+ tool_calls: list[Any] = []+ reasoning_content: str | None = None+ has_tool_calls = False++ class _ToolResponse(_Response):+ has_tool_calls = True+ content = "Here is the analysis of AAPL stock."++ def stream_chat(+ self,+ messages: list[dict[str, Any]],+ *,+ tools: Any = None,+ on_text_chunk: Any = None,+ on_reasoning_chunk: Any = None,+ ) -> Any:+ messages = [m for m in messages]+ _StubLLM._call_count += 1++ for msg in reversed(messages):+ if msg.get("role") in ("user", "system", "tool"):+ break+ if msg.get("role") == "assistant":+ raise AssertionError(+ f"Messages should not end with assistant role "+ f"(call #{_StubLLM._call_count}): {msg}"+ )++ return self._Response()++ def chat(self, messages: list[dict[str, Any]], **_: Any) -> Any:+ return self._Response()+++def _build_agent(llm: Any, max_iter: int = 3, tmp_run_dir: Path | None = None) -> AgentLoop:+ from src.tools import build_registry+ from src.memory.persistent import PersistentMemory++ pm = PersistentMemory()+ agent = AgentLoop(+ registry=build_registry(persistent_memory=pm, include_shell_tools=False),+ llm=llm,+ event_callback=None,+ max_iterations=max_iter,+ persistent_memory=pm,+ )+ if tmp_run_dir is not None:+ tmp_run_dir.mkdir(parents=True, exist_ok=True)+ agent.memory.run_dir = str(tmp_run_dir)+ return agent+++def test_agent_run_messages_never_end_with_assistant(tmp_path: Path) -> None:+ """A simple run() should never send a trailing assistant message to the LLM."""+ agent = _build_agent(+ _StubLLM(),+ max_iter=5,+ tmp_run_dir=tmp_path / "run",+ )+ result = agent.run("Analyze AAPL stock for 2024")+ assert result["status"] == "success"+ assert _StubLLM._call_count >= 1diff --git a/agent/tests/test_provider_diagnostics.py b/agent/tests/test_provider_diagnostics.pyindex b51cf5c98..5d6a06021 100644--- a/agent/tests/test_provider_diagnostics.py+++ b/agent/tests/test_provider_diagnostics.py@@ -129,6 +129,47 @@ def test_kimi_user_agent_header_is_moonshot_only() -> None:assert "default_headers" not in captured+def test_kimi_user_agent_respects_moonshot_user_agent_env_var() -> None:+ """MOONSHOT_USER_AGENT should override the default User-Agent header."""+ import src.providers.llm as llm_mod++ llm_mod._dotenv_loaded = True+ captured: dict = {}++ class _FakeChatOpenAI:+ def __init__(self, **kwargs: object) -> None:+ captured.update(kwargs)++ env = {+ "LANGCHAIN_PROVIDER": "moonshot",+ "MOONSHOT_API_KEY": "mk-test",+ "MOONSHOT_BASE_URL": "https://api.moonshot.ai/v1",+ "LANGCHAIN_MODEL_NAME": "kimi-k2.6",+ "MOONSHOT_USER_AGENT": "MyCustomAgent/2.0",+ }+ with patch.dict(os.environ, env, clear=True):+ with patch.object(llm_mod, "ChatOpenAIWithReasoning", _FakeChatOpenAI):+ llm_mod._recent_caps = None # ensure fresh build reads env+ build_llm()++ assert captured["default_headers"]["User-Agent"] == "MyCustomAgent/2.0"++ captured.clear()+ del env["MOONSHOT_USER_AGENT"]+ with patch.dict(os.environ, env, clear=True):+ with patch.object(llm_mod, "ChatOpenAIWithReasoning", _FakeChatOpenAI):+ build_llm()++ assert captured["default_headers"]["User-Agent"].startswith("Vibe-Trading/")+++def test_kimi_inference_respects_custom_user_agent() -> None:+ """Model name inference to moonshot should still use the override User-Agent."""+ moonshot = get_provider_capabilities(None, "kimi-k2.6")+ assert moonshot.name == "moonshot"+ assert "User-Agent" in moonshot.default_headers++def test_deepseek_native_adapter_is_used_when_available(monkeypatch) -> None:"""DeepSeek should prefer the optional native adapter when installed."""import sys