"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(providers): cover streaming path and OpenRouter relay for reasoning_content (#39)
warren618f866e5fb148c
diff --git a/agent/src/providers/chat.py b/agent/src/providers/chat.pyindex 842f14c95..f2e44a7bd 100644--- a/agent/src/providers/chat.py+++ b/agent/src/providers/chat.py@@ -10,6 +10,24 @@ from typing import Any, Dict, List, Optionalfrom src.providers.llm import build_llm+# Canonical finish_reason markers, in priority order. Used to deduplicate+# relays (e.g. OpenRouter) that emit finish_reason on every stream chunk,+# which AIMessageChunk.__add__ concatenates into "stopstop", "tool_callstool_calls", etc.+_FINISH_REASON_MARKERS: tuple[str, ...] = (+ "tool_calls",+ "function_call",+ "content_filter",+ "length",+ "stop",+)+++def _normalize_finish_reason(raw: str) -> str:+ for marker in _FINISH_REASON_MARKERS:+ if marker in raw:+ return marker+ return raw or "stop"+@dataclassclass ToolCallRequest:@@ -134,32 +152,25 @@ class ChatLLM:@staticmethoddef _parse_response(ai_message: Any) -> LLMResponse:- """Convert a LangChain AIMessage to ``LLMResponse``.-- Args:- ai_message: LangChain AIMessage instance.+ """Convert a LangChain AIMessage (or AIMessageChunk) to ``LLMResponse``.- Returns:- ``LLMResponse``.+ Single source of truth for provider-specific reasoning fields:+ ``ai_message.additional_kwargs["reasoning_content"]``. Populated by+ ``ChatOpenAIWithReasoning`` for both streaming and non-streaming paths."""- content = ai_message.content if hasattr(ai_message, "content") else None- reasoning_content = (- getattr(ai_message, "reasoning_content", None)- or getattr(ai_message, "additional_kwargs", {}).get("reasoning_content")- or getattr(ai_message, "response_metadata", {}).get("reasoning_content")- )- raw_calls = getattr(ai_message, "tool_calls", None) or []- tool_calls = []- for tc in raw_calls:- tool_calls.append(ToolCallRequest(+ tool_calls = [+ ToolCallRequest(id=tc.get("id", ""),name=tc.get("name", ""),arguments=tc.get("args", {}),- ))- finish = getattr(ai_message, "response_metadata", {}).get("finish_reason", "stop")+ )+ for tc in (ai_message.tool_calls or [])+ ]return LLMResponse(- content=content,+ content=ai_message.content,tool_calls=tool_calls,- reasoning_content=reasoning_content,- finish_reason=finish,+ reasoning_content=ai_message.additional_kwargs.get("reasoning_content"),+ finish_reason=_normalize_finish_reason(+ ai_message.response_metadata.get("finish_reason", "stop")+ ),)diff --git a/agent/src/providers/llm.py b/agent/src/providers/llm.pyindex f8ccb1fa8..35c462977 100644--- a/agent/src/providers/llm.py+++ b/agent/src/providers/llm.py@@ -5,7 +5,7 @@ from __future__ import annotationsimport jsonimport osfrom pathlib import Path-from typing import Any, Dict, Optional+from typing import Any, Dict, Mapping, Optionaltry:from dotenv import load_dotenv@@ -18,30 +18,65 @@ except ImportError:ChatOpenAI = None # type: ignore+# Provider-specific reasoning field variants, in priority order.+# All normalize to the canonical key additional_kwargs["reasoning_content"].+# * Moonshot / DeepSeek official API → "reasoning_content"+# * OpenRouter relay (all thinking models) → "reasoning"+_REASONING_FIELDS: tuple[str, ...] = ("reasoning_content", "reasoning")+++def _preserve(src: Mapping[str, Any], target_msg: Any) -> None:+ """Copy provider reasoning field from src into target_msg.additional_kwargs.++ Src is a response message dict (non-streaming) or stream delta dict.+ The first non-empty variant in _REASONING_FIELDS wins; all write to the+ same canonical key so downstream reads one place.+ """+ for field in _REASONING_FIELDS:+ value = src.get(field)+ if value:+ target_msg.additional_kwargs["reasoning_content"] = value+ return++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.- """+ langchain-openai 0.3.x drops non-standard fields (reasoning_content+ from Moonshot K2.5, DeepSeek reasoner, Qwen thinking) in both+ response paths:+ * _convert_dict_to_message — invoke / ainvoke (non-streaming)+ * _convert_delta_to_message_chunk — stream / astream- _PRESERVE_FIELDS = ("reasoning_content",)+ This subclass hooks both so downstream code always reads one place:+ msg.additional_kwargs["reasoning_content"]. For streaming, per-delta+ writes are accumulated by AIMessageChunk.__add__ via merge_dicts.+ """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+ for gen, choice in zip(result.generations, raw["choices"]):+ _preserve(choice["message"], gen.message)return result++ def _convert_chunk_to_generation_chunk( # type: ignore[override]+ self,+ chunk: dict,+ default_chunk_class: type,+ base_generation_info: Optional[dict],+ ):+ gen_chunk = super()._convert_chunk_to_generation_chunk(+ chunk, default_chunk_class, base_generation_info+ )+ if gen_chunk is None:+ return None+ choices = chunk.get("choices") or chunk.get("chunk", {}).get("choices")+ if not choices:+ return gen_chunk+ _preserve(choices[0]["delta"], gen_chunk.message)+ return gen_chunkelse:ChatOpenAIWithReasoning = None # type: ignore@@ -156,13 +191,21 @@ 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 ChatOpenAIWithReasoning(+ kwargs: Dict[str, Any] = dict(model=name,temperature=temperature,timeout=timeout,max_retries=max_retries,callbacks=callbacks,)+ # Optional: enable reasoning on relays that require it (e.g. OpenRouter).+ # Moonshot/DeepSeek official APIs emit reasoning_content by default, so+ # this is only relevant for proxy layers. Unknown providers ignore the+ # extra_body field (OpenAI-compatible contract).+ effort = os.getenv("LANGCHAIN_REASONING_EFFORT", "").strip().lower()+ if effort:+ kwargs["extra_body"] = {"reasoning": {"effort": effort}}+ return ChatOpenAIWithReasoning(**kwargs)def _extract_balanced_json(text: str) -> Optional[Dict[str, Any]]:diff --git a/agent/tests/test_kimi_reasoning_content.py b/agent/tests/test_kimi_reasoning_content.pyindex ca074de5e..fdcae2855 100644--- a/agent/tests/test_kimi_reasoning_content.py+++ b/agent/tests/test_kimi_reasoning_content.py@@ -1,59 +1,104 @@-"""Regression tests for Kimi thinking/tool-call compatibility."""+"""Regression tests for provider reasoning_content preservation.++Invariant: ``ai_message.additional_kwargs["reasoning_content"]`` is the+single source of truth. ``ChatOpenAIWithReasoning`` populates it from both+the non-streaming response path and the streaming delta path.+"""from __future__ import annotationsimport osfrom types import SimpleNamespace+from typing import Anyfrom src.agent.context import ContextBuilder-from src.providers.chat import ChatLLM, ToolCallRequest+from src.providers.chat import ChatLLM, ToolCallRequest, _normalize_finish_reasonfrom src.providers.llm import ChatOpenAIWithReasoning-class TestKimiReasoningContent:- def test_parse_response_keeps_reasoning_content(self) -> None:+class TestParseResponseSingleSource:+ """_parse_response reads reasoning_content from exactly one place."""++ def test_reads_from_additional_kwargs(self) -> None:ai_message = SimpleNamespace(content="",- reasoning_content="step-by-step reasoning",- tool_calls=[- {- "id": "tc_1",- "name": "bash",- "args": {"command": "pwd"},- }- ],- additional_kwargs={},- response_metadata={"finish_reason": "tool_calls"},+ tool_calls=[],+ additional_kwargs={"reasoning_content": "step-by-step reasoning"},+ response_metadata={"finish_reason": "stop"},)response = ChatLLM._parse_response(ai_message)assert response.reasoning_content == "step-by-step reasoning"- assert response.finish_reason == "tool_calls"- assert len(response.tool_calls) == 1- assert response.tool_calls[0].arguments == {"command": "pwd"}- def test_parse_response_falls_back_to_additional_kwargs(self) -> None:+ def test_absent_reasoning_content_yields_none(self) -> None:+ """Non-thinking providers leave reasoning_content unset."""ai_message = SimpleNamespace(- content="",+ content="hello",tool_calls=[],- additional_kwargs={"reasoning_content": "fallback reasoning"},+ additional_kwargs={},response_metadata={"finish_reason": "stop"},)response = ChatLLM._parse_response(ai_message)- assert response.reasoning_content == "fallback reasoning"+ assert response.reasoning_content is None+ assert response.content == "hello"++ def test_tool_calls_are_preserved_alongside_reasoning(self) -> None:+ ai_message = SimpleNamespace(+ content="",+ tool_calls=[{"id": "tc_1", "name": "bash", "args": {"command": "pwd"}}],+ additional_kwargs={"reasoning_content": "think then call"},+ response_metadata={"finish_reason": "tool_calls"},+ )++ response = ChatLLM._parse_response(ai_message)++ assert response.reasoning_content == "think then call"+ assert response.finish_reason == "tool_calls"+ assert response.tool_calls[0].id == "tc_1"+ assert response.tool_calls[0].arguments == {"command": "pwd"}+++class TestNormalizeFinishReason:+ """OpenRouter-style relays emit finish_reason on every stream chunk;+ AIMessageChunk.__add__ concatenates them into 'stopstop', 'tool_callstool_calls', etc.+ ReAct loop uses finish_reason for exit decisions, so equality comparisons+ must survive this quirk."""++ def test_clean_stop_unchanged(self) -> None:+ assert _normalize_finish_reason("stop") == "stop"++ def test_clean_tool_calls_unchanged(self) -> None:+ assert _normalize_finish_reason("tool_calls") == "tool_calls"++ def test_duplicated_stop_dedupes(self) -> None:+ assert _normalize_finish_reason("stopstop") == "stop"+ assert _normalize_finish_reason("stopstopstop") == "stop"++ def test_duplicated_tool_calls_dedupes(self) -> None:+ assert _normalize_finish_reason("tool_callstool_calls") == "tool_calls"++ def test_tool_calls_wins_over_stop_when_both_present(self) -> None:+ # Defensive: if a relay ever emits "stoptool_calls" mid-stream,+ # tool_calls is more actionable than stop.+ assert _normalize_finish_reason("stoptool_calls") == "tool_calls"++ def test_empty_defaults_to_stop(self) -> None:+ assert _normalize_finish_reason("") == "stop"++ def test_unknown_marker_passed_through(self) -> None:+ # Future providers may introduce new markers; don't silently rewrite.+ assert _normalize_finish_reason("custom_reason") == "custom_reason"+++class TestContextBuilderToolCallReplay:+ """reasoning_content flows back into the next request's assistant message."""def test_format_assistant_tool_calls_preserves_reasoning_content(self) -> None:message = ContextBuilder.format_assistant_tool_calls(- [- ToolCallRequest(- id="tc_1",- name="bash",- arguments={"command": "pwd"},- )- ],+ [ToolCallRequest(id="tc_1", name="bash", arguments={"command": "pwd"})],content="",reasoning_content="step-by-step reasoning",)@@ -64,34 +109,25 @@ class TestKimiReasoningContent:def test_format_assistant_tool_calls_omits_reasoning_when_absent(self) -> None:message = ContextBuilder.format_assistant_tool_calls(- [- ToolCallRequest(- id="tc_1",- name="bash",- arguments={"command": "pwd"},- )- ],+ [ToolCallRequest(id="tc_1", name="bash", arguments={"command": "pwd"})],content="",)assert "reasoning_content" not in message-class TestChatOpenAIWithReasoning:- """End-to-end test that reasoning_content survives the langchain-openai layer.+class TestChatOpenAIWithReasoningNonStreaming:+ """_create_chat_result path: invoke / ainvoke."""- 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:+ def _instance(self, model: str = "kimi-k2-thinking") -> Any:os.environ.setdefault("OPENAI_API_KEY", "sk-test")- instance = ChatOpenAIWithReasoning(model="kimi-k2.5", api_key="sk-test")+ return ChatOpenAIWithReasoning(model=model, api_key="sk-test")- moonshot_like_response = {+ def test_preserves_reasoning_on_tool_call_response(self) -> None:+ instance = self._instance()+ response = {"id": "chatcmpl-test",- "model": "kimi-k2.5",+ "model": "kimi-k2-thinking","choices": [{"index": 0,@@ -105,7 +141,7 @@ class TestChatOpenAIWithReasoning:"type": "function","function": {"name": "bash",- "arguments": "{\"command\":\"pwd\"}",+ "arguments": '{"command":"pwd"}',},}],@@ -116,33 +152,151 @@ class TestChatOpenAIWithReasoning:"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},}- result = instance._create_chat_result(moonshot_like_response)- message = result.generations[0].message+ result = instance._create_chat_result(response)- assert message.additional_kwargs.get("reasoning_content") == "step-by-step reasoning from provider"+ assert result.generations[0].message.additional_kwargs["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 = {+ def test_no_reasoning_content_when_absent(self) -> None:+ """OpenAI / Claude / Groq-style responses leave additional_kwargs clean."""+ instance = self._instance(model="gpt-4")+ response = {"id": "chatcmpl-test","model": "gpt-4","choices": [{"index": 0,- "message": {- "role": "assistant",- "content": "hello",- },+ "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+ result = instance._create_chat_result(response)++ assert "reasoning_content" not in result.generations[0].message.additional_kwargs+++class TestChatOpenAIWithReasoningStreaming:+ """_convert_chunk_to_generation_chunk path: stream / astream.++ This is the path swarm workers take via ChatLLM.stream_chat → llm.stream.+ PR #41 only fixed the non-streaming path; this class covers the gap.+ """++ def _instance(self, model: str = "kimi-k2-thinking") -> Any:+ os.environ.setdefault("OPENAI_API_KEY", "sk-test")+ return ChatOpenAIWithReasoning(model=model, api_key="sk-test")++ def _delta_chunk(self, delta: dict, model: str = "kimi-k2-thinking") -> dict:+ return {+ "id": "chatcmpl-test",+ "model": model,+ "choices": [{"index": 0, "delta": delta, "finish_reason": None}],+ }++ def test_preserves_reasoning_on_streaming_delta(self) -> None:+ from langchain_core.messages import AIMessageChunk++ instance = self._instance()+ chunk = self._delta_chunk(+ {"role": "assistant", "content": "", "reasoning_content": "thinking step"}+ )++ gen_chunk = instance._convert_chunk_to_generation_chunk(chunk, AIMessageChunk, None)++ assert gen_chunk is not None+ assert gen_chunk.message.additional_kwargs["reasoning_content"] == "thinking step"++ def test_streaming_chunks_accumulate_reasoning_across_chunks(self) -> None:+ """Multiple deltas: AIMessageChunk.__add__ concatenates via merge_dicts."""+ from langchain_core.messages import AIMessageChunk++ instance = self._instance()+ chunks = [+ self._delta_chunk({"role": "assistant", "content": "", "reasoning_content": "first "}),+ self._delta_chunk({"content": "", "reasoning_content": "second "}),+ self._delta_chunk({"content": "", "reasoning_content": "third"}),+ ]++ accumulated = None+ for raw in chunks:+ gen = instance._convert_chunk_to_generation_chunk(raw, AIMessageChunk, None)+ assert gen is not None+ accumulated = gen.message if accumulated is None else accumulated + gen.message++ assert accumulated is not None+ assert accumulated.additional_kwargs["reasoning_content"] == "first second third"++ def test_streaming_delta_without_reasoning_is_unchanged(self) -> None:+ """OpenAI-style stream deltas (no reasoning_content) produce empty additional_kwargs."""+ from langchain_core.messages import AIMessageChunk++ instance = self._instance(model="gpt-4")+ chunk = self._delta_chunk({"role": "assistant", "content": "hello"}, model="gpt-4")++ gen_chunk = instance._convert_chunk_to_generation_chunk(chunk, AIMessageChunk, None)++ assert gen_chunk is not None+ assert "reasoning_content" not in gen_chunk.message.additional_kwargs++ def test_openrouter_field_name_reasoning_maps_to_reasoning_content(self) -> None:+ """OpenRouter relays Kimi/DeepSeek with delta.reasoning (not reasoning_content).++ All variants must normalize to additional_kwargs["reasoning_content"] so+ downstream reads one canonical key.+ """+ from langchain_core.messages import AIMessageChunk++ instance = self._instance(model="moonshotai/kimi-k2-thinking")+ chunk = self._delta_chunk(+ {"role": "assistant", "content": "", "reasoning": "openrouter-style reasoning"},+ model="moonshotai/kimi-k2-thinking",+ )++ gen_chunk = instance._convert_chunk_to_generation_chunk(chunk, AIMessageChunk, None)++ assert gen_chunk is not None+ # Canonical key — not "reasoning"+ assert gen_chunk.message.additional_kwargs["reasoning_content"] == \+ "openrouter-style reasoning"+ assert "reasoning" not in gen_chunk.message.additional_kwargs++ def test_reasoning_content_takes_priority_over_reasoning(self) -> None:+ """If both variants are present, reasoning_content wins (higher priority)."""+ from langchain_core.messages import AIMessageChunk++ instance = self._instance()+ chunk = self._delta_chunk(+ {+ "role": "assistant",+ "content": "",+ "reasoning_content": "canonical",+ "reasoning": "variant",+ }+ )++ gen_chunk = instance._convert_chunk_to_generation_chunk(chunk, AIMessageChunk, None)++ assert gen_chunk is not None+ assert gen_chunk.message.additional_kwargs["reasoning_content"] == "canonical"++ def test_usage_only_chunk_returns_without_modification(self) -> None:+ """Final usage-only chunks have no choices[] — must not crash."""+ from langchain_core.messages import AIMessageChunk++ instance = self._instance()+ usage_only = {+ "id": "chatcmpl-test",+ "model": "kimi-k2-thinking",+ "choices": [],+ "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},+ }++ gen_chunk = instance._convert_chunk_to_generation_chunk(usage_only, AIMessageChunk, None)- assert "reasoning_content" not in message.additional_kwargs+ # super() returns a default-content chunk for usage-only; we should+ # pass it through unchanged (no choices to read reasoning from).+ assert gen_chunk is not None+ assert "reasoning_content" not in gen_chunk.message.additional_kwargsdiff --git a/agent/tests/test_llm.py b/agent/tests/test_llm.pyindex b01329484..9dd4b95be 100644--- a/agent/tests/test_llm.py+++ b/agent/tests/test_llm.py@@ -174,6 +174,55 @@ class TestMinimaxTemperature:assert captured["temperature"] == 0.7+class TestReasoningEffortPassthrough:+ """LANGCHAIN_REASONING_EFFORT is forwarded as extra_body.reasoning.effort+ to the underlying OpenAI-compatible client. Used for OpenRouter-style+ relays that require opt-in to enable thinking."""++ def _capture(self, env: dict[str, str]) -> dict:+ 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)++ with patch.dict(os.environ, env, clear=True):+ with patch.object(llm_mod, "ChatOpenAIWithReasoning", _FakeChatOpenAI):+ build_llm()+ return captured++ def test_effort_unset_omits_extra_body(self) -> None:+ captured = self._capture({+ "LANGCHAIN_PROVIDER": "openai",+ "OPENAI_API_KEY": "sk-test",+ "LANGCHAIN_MODEL_NAME": "gpt-4",+ })+ assert "extra_body" not in captured++ def test_effort_medium_forwarded_as_extra_body(self) -> None:+ captured = self._capture({+ "LANGCHAIN_PROVIDER": "openrouter",+ "OPENROUTER_API_KEY": "or-test",+ "OPENROUTER_BASE_URL": "https://openrouter.ai/api/v1",+ "LANGCHAIN_MODEL_NAME": "moonshotai/kimi-k2-thinking",+ "LANGCHAIN_REASONING_EFFORT": "medium",+ })+ assert captured["extra_body"] == {"reasoning": {"effort": "medium"}}++ def test_effort_case_insensitive(self) -> None:+ captured = self._capture({+ "LANGCHAIN_PROVIDER": "openrouter",+ "OPENROUTER_API_KEY": "or-test",+ "OPENROUTER_BASE_URL": "https://openrouter.ai/api/v1",+ "LANGCHAIN_MODEL_NAME": "moonshotai/kimi-k2-thinking",+ "LANGCHAIN_REASONING_EFFORT": "HIGH",+ })+ assert captured["extra_body"]["reasoning"]["effort"] == "high"++class TestExtractBalancedJson:def test_simple_json(self) -> None:result = _extract_balanced_json('{"key": "value"}')