"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
refactor(providers): collapse reasoning_content path helpers
warren618e6ceb5a3b395
diff --git a/agent/src/providers/chat.py b/agent/src/providers/chat.pyindex f2e44a7bd..b7fd9ff35 100644--- a/agent/src/providers/chat.py+++ b/agent/src/providers/chat.py@@ -10,23 +10,17 @@ 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"+def _dedupe_finish_reason(raw: str) -> str:+ """Relays (OpenRouter) emit finish_reason per chunk; AIMessageChunk.__add__+ concatenates into 'stopstop', 'tool_callstool_calls', etc. Return the+ canonical suffix so ReAct equality checks survive.+ """+ return next(+ (m for m in ("tool_calls", "function_call", "content_filter", "length", "stop")+ if raw.endswith(m)),+ raw,+ )@dataclass@@ -154,23 +148,17 @@ class ChatLLM:def _parse_response(ai_message: Any) -> LLMResponse:"""Convert a LangChain AIMessage (or AIMessageChunk) to ``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.+ Single source for reasoning: ``additional_kwargs["reasoning_content"]``,+ populated by ``ChatOpenAIWithReasoning`` on both stream and non-stream paths."""- tool_calls = [- ToolCallRequest(- id=tc.get("id", ""),- name=tc.get("name", ""),- arguments=tc.get("args", {}),- )- for tc in (ai_message.tool_calls or [])- ]return LLMResponse(content=ai_message.content,- tool_calls=tool_calls,+ tool_calls=[+ ToolCallRequest(id=tc["id"], name=tc["name"], arguments=tc["args"])+ for tc in ai_message.tool_calls+ ],reasoning_content=ai_message.additional_kwargs.get("reasoning_content"),- finish_reason=_normalize_finish_reason(+ finish_reason=_dedupe_finish_reason(ai_message.response_metadata.get("finish_reason", "stop")),)diff --git a/agent/src/providers/llm.py b/agent/src/providers/llm.pyindex 35c462977..0ecb84d4f 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, Mapping, Optional+from typing import Any, Dict, Optionaltry:from dotenv import load_dotenv@@ -18,47 +18,28 @@ 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.+ """ChatOpenAI that preserves provider reasoning across invoke + stream.- 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)+ 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-- 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.+ Moonshot/DeepSeek emit `reasoning_content`; OpenRouter relays as+ `reasoning`. Both normalize to additional_kwargs["reasoning_content"],+ so downstream reads one canonical key."""+ @staticmethod+ def _capture(src: Any, msg: Any) -> None:+ if value := src.get("reasoning_content") or src.get("reasoning"):+ msg.additional_kwargs["reasoning_content"] = value+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["choices"]):- _preserve(choice["message"], gen.message)+ self._capture(choice["message"], gen.message)return resultdef _convert_chunk_to_generation_chunk( # type: ignore[override]@@ -67,16 +48,15 @@ if ChatOpenAI is not None:default_chunk_class: type,base_generation_info: Optional[dict],):- gen_chunk = super()._convert_chunk_to_generation_chunk(+ gen = super()._convert_chunk_to_generation_chunk(chunk, default_chunk_class, base_generation_info)- if gen_chunk is None:+ if gen is None:return Nonechoices = chunk.get("choices") or chunk.get("chunk", {}).get("choices")- if not choices:- return gen_chunk- _preserve(choices[0]["delta"], gen_chunk.message)- return gen_chunk+ if choices:+ self._capture(choices[0]["delta"], gen.message)+ return genelse:ChatOpenAIWithReasoning = None # type: ignore@@ -189,23 +169,17 @@ def build_llm(*, model_name: Optional[str] = None, callbacks: Any = None) -> Any# default 0.0 is used to avoid an API validation error.if os.getenv("LANGCHAIN_PROVIDER", "openai").lower() == "minimax" and temperature <= 0.0:temperature = 0.01- timeout = int(os.getenv("TIMEOUT_SECONDS", "120"))- max_retries = int(os.getenv("MAX_RETRIES", "2"))- kwargs: Dict[str, Any] = dict(+ # Optional reasoning activation for relays requiring opt-in (e.g. OpenRouter).+ # Moonshot/DeepSeek official APIs emit reasoning by default and ignore this field.+ effort = os.getenv("LANGCHAIN_REASONING_EFFORT", "").strip().lower()+ return ChatOpenAIWithReasoning(model=name,temperature=temperature,- timeout=timeout,- max_retries=max_retries,+ timeout=int(os.getenv("TIMEOUT_SECONDS", "120")),+ max_retries=int(os.getenv("MAX_RETRIES", "2")),callbacks=callbacks,+ extra_body={"reasoning": {"effort": effort}} if effort else None,)- # 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 fdcae2855..7ee7bf587 100644--- a/agent/tests/test_kimi_reasoning_content.py+++ b/agent/tests/test_kimi_reasoning_content.py@@ -12,7 +12,7 @@ from types import SimpleNamespacefrom typing import Anyfrom src.agent.context import ContextBuilder-from src.providers.chat import ChatLLM, ToolCallRequest, _normalize_finish_reason+from src.providers.chat import ChatLLM, ToolCallRequest, _dedupe_finish_reasonfrom src.providers.llm import ChatOpenAIWithReasoning@@ -61,36 +61,30 @@ class TestParseResponseSingleSource:assert response.tool_calls[0].arguments == {"command": "pwd"}-class TestNormalizeFinishReason:+class TestDedupeFinishReason:"""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."""+ AIMessageChunk.__add__ concatenates them into 'stopstop', etc. ReAct+ loop uses finish_reason for exit decisions, so equality must survive."""- def test_clean_stop_unchanged(self) -> None:- assert _normalize_finish_reason("stop") == "stop"+ def test_clean_values_unchanged(self) -> None:+ assert _dedupe_finish_reason("stop") == "stop"+ assert _dedupe_finish_reason("tool_calls") == "tool_calls"- def test_clean_tool_calls_unchanged(self) -> None:- assert _normalize_finish_reason("tool_calls") == "tool_calls"+ def test_duplicated_dedupes(self) -> None:+ assert _dedupe_finish_reason("stopstop") == "stop"+ assert _dedupe_finish_reason("stopstopstop") == "stop"+ assert _dedupe_finish_reason("tool_callstool_calls") == "tool_calls"- def test_duplicated_stop_dedupes(self) -> None:- assert _normalize_finish_reason("stopstop") == "stop"- assert _normalize_finish_reason("stopstopstop") == "stop"+ def test_suffix_match_picks_longest_valid_marker(self) -> None:+ # endswith — "stoptool_calls" ends with "tool_calls"+ assert _dedupe_finish_reason("stoptool_calls") == "tool_calls"- 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_empty_returns_empty(self) -> None:+ # No marker matches; raw is returned. Callers supply a default upstream.+ assert _dedupe_finish_reason("") == ""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"+ assert _dedupe_finish_reason("custom_reason") == "custom_reason"class TestContextBuilderToolCallReplay:diff --git a/agent/tests/test_llm.py b/agent/tests/test_llm.pyindex 9dd4b95be..d0c92263c 100644--- a/agent/tests/test_llm.py+++ b/agent/tests/test_llm.py@@ -194,13 +194,13 @@ class TestReasoningEffortPassthrough:build_llm()return captured- def test_effort_unset_omits_extra_body(self) -> None:+ def test_effort_unset_leaves_extra_body_none(self) -> None:captured = self._capture({"LANGCHAIN_PROVIDER": "openai","OPENAI_API_KEY": "sk-test","LANGCHAIN_MODEL_NAME": "gpt-4",})- assert "extra_body" not in captured+ assert captured["extra_body"] is Nonedef test_effort_medium_forwarded_as_extra_body(self) -> None:captured = self._capture({