"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(providers): subclass ChatOpenAI to preserve reasoning_content
warren61873b179a28d3b
diff --git a/agent/src/providers/llm.py b/agent/src/providers/llm.pyindex 7ed9c699d..f8ccb1fa8 100644--- a/agent/src/providers/llm.py+++ b/agent/src/providers/llm.py@@ -17,6 +17,34 @@ try:except ImportError:ChatOpenAI = None # type: ignore++if ChatOpenAI is not None:+ class ChatOpenAIWithReasoning(ChatOpenAI): # type: ignore[misc,valid-type]+ """ChatOpenAI that preserves provider-specific reasoning fields.++ langchain-openai 0.3.x's _convert_dict_to_message only copies+ function_call / tool_calls / audio into additional_kwargs; unknown+ fields like reasoning_content (Moonshot K2.5, DeepSeek reasoner,+ Qwen thinking) are silently dropped. This subclass re-reads the+ raw response and restores those fields so callers relying on+ `msg.additional_kwargs["reasoning_content"]` can find them.+ """++ _PRESERVE_FIELDS = ("reasoning_content",)++ def _create_chat_result(self, response, generation_info=None): # type: ignore[override]+ result = super()._create_chat_result(response, generation_info)+ raw = response if isinstance(response, dict) else response.model_dump()+ for gen, choice in zip(result.generations, raw.get("choices", []) or []):+ message_dict = (choice or {}).get("message") or {}+ for field in self._PRESERVE_FIELDS:+ value = message_dict.get(field)+ if value:+ gen.message.additional_kwargs[field] = value+ return result+else:+ ChatOpenAIWithReasoning = None # type: ignore+AGENT_DIR = Path(__file__).resolve().parents[2]# .env search order: ~/.vibe-trading/.env → agent/.env → $CWD/.env@@ -128,7 +156,7 @@ def build_llm(*, model_name: Optional[str] = None, callbacks: Any = None) -> Anytemperature = 0.01timeout = int(os.getenv("TIMEOUT_SECONDS", "120"))max_retries = int(os.getenv("MAX_RETRIES", "2"))- return ChatOpenAI(+ return ChatOpenAIWithReasoning(model=name,temperature=temperature,timeout=timeout,diff --git a/agent/tests/test_kimi_reasoning_content.py b/agent/tests/test_kimi_reasoning_content.pyindex cf39768a8..ca074de5e 100644--- a/agent/tests/test_kimi_reasoning_content.py+++ b/agent/tests/test_kimi_reasoning_content.py@@ -2,10 +2,12 @@from __future__ import annotations+import osfrom types import SimpleNamespacefrom src.agent.context import ContextBuilderfrom src.providers.chat import ChatLLM, ToolCallRequest+from src.providers.llm import ChatOpenAIWithReasoningclass TestKimiReasoningContent:@@ -73,3 +75,74 @@ class TestKimiReasoningContent:)assert "reasoning_content" not in message+++class TestChatOpenAIWithReasoning:+ """End-to-end test that reasoning_content survives the langchain-openai layer.++ langchain-openai 0.3.x's _convert_dict_to_message drops unknown fields+ (reasoning_content included). Our subclass re-reads the raw response+ and restores them into additional_kwargs.+ """++ def test_subclass_preserves_reasoning_content_on_tool_call_response(self) -> None:+ os.environ.setdefault("OPENAI_API_KEY", "sk-test")+ instance = ChatOpenAIWithReasoning(model="kimi-k2.5", api_key="sk-test")++ moonshot_like_response = {+ "id": "chatcmpl-test",+ "model": "kimi-k2.5",+ "choices": [+ {+ "index": 0,+ "message": {+ "role": "assistant",+ "content": "",+ "reasoning_content": "step-by-step reasoning from provider",+ "tool_calls": [+ {+ "id": "tc_1",+ "type": "function",+ "function": {+ "name": "bash",+ "arguments": "{\"command\":\"pwd\"}",+ },+ }+ ],+ },+ "finish_reason": "tool_calls",+ }+ ],+ "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},+ }++ result = instance._create_chat_result(moonshot_like_response)+ message = result.generations[0].message++ assert message.additional_kwargs.get("reasoning_content") == "step-by-step reasoning from provider"++ def test_subclass_no_reasoning_content_when_absent(self) -> None:+ """Non-thinking providers (OpenAI, Claude, etc.) must see no change."""+ os.environ.setdefault("OPENAI_API_KEY", "sk-test")+ instance = ChatOpenAIWithReasoning(model="gpt-4", api_key="sk-test")++ openai_like_response = {+ "id": "chatcmpl-test",+ "model": "gpt-4",+ "choices": [+ {+ "index": 0,+ "message": {+ "role": "assistant",+ "content": "hello",+ },+ "finish_reason": "stop",+ }+ ],+ "usage": {"prompt_tokens": 5, "completion_tokens": 2, "total_tokens": 7},+ }++ result = instance._create_chat_result(openai_like_response)+ message = result.generations[0].message++ assert "reasoning_content" not in message.additional_kwargs