"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(providers): re-inject reasoning_content on outbound requests (#39)
warren618a1040bbb715f
diff --git a/agent/src/providers/llm.py b/agent/src/providers/llm.pyindex 0ecb84d4f..b977f4c1f 100644--- a/agent/src/providers/llm.py+++ b/agent/src/providers/llm.py@@ -22,12 +22,14 @@ if ChatOpenAI is not None:class ChatOpenAIWithReasoning(ChatOpenAI): # type: ignore[misc,valid-type]"""ChatOpenAI that preserves provider reasoning across invoke + stream.- langchain-openai 0.3.x drops non-standard fields in both paths:- * _convert_dict_to_message — invoke / ainvoke- * _convert_delta_to_message_chunk — stream / astream+ langchain-openai 0.3.x drops non-standard fields in three paths:+ * _convert_dict_to_message — invoke / ainvoke (inbound)+ * _convert_delta_to_message_chunk — stream / astream (inbound)+ * _convert_message_to_dict — request serialization (outbound)Moonshot/DeepSeek emit `reasoning_content`; OpenRouter relays as- `reasoning`. Both normalize to additional_kwargs["reasoning_content"],- so downstream reads one canonical key.+ `reasoning`. Inbound paths normalize to additional_kwargs["reasoning_content"];+ outbound path re-injects it so strict providers (kimi-k2.5) accept+ multi-turn continuations."""@staticmethod@@ -57,6 +59,30 @@ if ChatOpenAI is not None:if choices:self._capture(choices[0]["delta"], gen.message)return gen++ def _get_request_payload( # type: ignore[override]+ self,+ input_: Any,+ *,+ stop: Optional[list[str]] = None,+ **kwargs: Any,+ ) -> dict:+ """Re-inject reasoning_content and normalize assistant content.++ LangChain strips ``reasoning_content`` when serializing AIMessages+ back to OpenAI wire format. Moonshot kimi-k2.5 also rejects+ assistant turns where ``content`` is null or ``reasoning_content``+ is absent, breaking ReAct continuations after a tool call (#39).+ """+ payload = super()._get_request_payload(input_, stop=stop, **kwargs)+ messages = super()._convert_input(input_).to_messages()+ for i, m in enumerate(payload["messages"]):+ if m.get("role") != "assistant":+ continue+ if m.get("content") is None:+ m["content"] = ""+ m["reasoning_content"] = messages[i].additional_kwargs.get("reasoning_content", "")+ return payloadelse:ChatOpenAIWithReasoning = None # type: ignorediff --git a/agent/tests/test_kimi_reasoning_content.py b/agent/tests/test_kimi_reasoning_content.pyindex 7ee7bf587..995746b16 100644--- a/agent/tests/test_kimi_reasoning_content.py+++ b/agent/tests/test_kimi_reasoning_content.py@@ -294,3 +294,92 @@ class TestChatOpenAIWithReasoningStreaming:# pass it through unchanged (no choices to read reasoning from).assert gen_chunk is not Noneassert "reasoning_content" not in gen_chunk.message.additional_kwargs+++class TestChatOpenAIWithReasoningOutboundPayload:+ """_get_request_payload path: re-inject reasoning_content on continuation+ calls and normalize content=None for strict providers (issue #39 round-trip).+ """++ def _instance(self, model: str = "kimi-k2-0905-preview") -> Any:+ os.environ.setdefault("OPENAI_API_KEY", "sk-test")+ return ChatOpenAIWithReasoning(model=model, api_key="sk-test")++ def test_reinjects_reasoning_content_from_additional_kwargs(self) -> None:+ """Assistant messages with reasoning_content in additional_kwargs are+ preserved across LangChain's dict → AIMessage → dict serialization."""+ from langchain_core.messages import AIMessage, HumanMessage++ instance = self._instance()+ history = [+ HumanMessage(content="hi"),+ AIMessage(+ content="",+ additional_kwargs={+ "reasoning_content": "I should call a tool",+ "tool_calls": [+ {"id": "c1", "type": "function",+ "function": {"name": "t", "arguments": "{}"}},+ ],+ },+ ),+ ]++ payload = instance._get_request_payload(history)++ assistant_msg = next(m for m in payload["messages"] if m["role"] == "assistant")+ assert assistant_msg["reasoning_content"] == "I should call a tool"++ def test_normalizes_none_content_on_assistant_messages(self) -> None:+ """LangChain serializes AIMessage(content='', tool_calls=[...]) as+ content=null; Moonshot kimi-k2.5 rejects that, so we normalize to ''."""+ from langchain_core.messages import AIMessage, HumanMessage++ instance = self._instance()+ history = [+ HumanMessage(content="hi"),+ AIMessage(+ content="",+ additional_kwargs={+ "tool_calls": [+ {"id": "c1", "type": "function",+ "function": {"name": "t", "arguments": "{}"}},+ ],+ },+ ),+ ]++ payload = instance._get_request_payload(history)++ assistant_msg = next(m for m in payload["messages"] if m["role"] == "assistant")+ assert assistant_msg["content"] == ""++ def test_injects_empty_reasoning_content_when_absent(self) -> None:+ """kimi-k2.5 requires reasoning_content on every assistant turn."""+ from langchain_core.messages import AIMessage, HumanMessage++ instance = self._instance()+ history = [+ HumanMessage(content="hi"),+ AIMessage(content="plain assistant reply"),+ ]++ payload = instance._get_request_payload(history)++ assistant_msg = next(m for m in payload["messages"] if m["role"] == "assistant")+ assert assistant_msg["reasoning_content"] == ""++ def test_user_and_system_messages_untouched(self) -> None:+ """Only assistant messages get the reasoning_content injection."""+ from langchain_core.messages import HumanMessage, SystemMessage++ instance = self._instance()+ history = [+ SystemMessage(content="be brief"),+ HumanMessage(content="hi"),+ ]++ payload = instance._get_request_payload(history)++ for m in payload["messages"]:+ assert "reasoning_content" not in m