From 20c06d48977b4af8719992bc3cd333a4d8f7e2b2 Mon Sep 17 00:00:00 2001 From: Xi Zhang <106144707+X-iZhang@users.noreply.github.com> Date: Sun, 26 Apr 2026 15:53:08 +0200 Subject: [PATCH] =?UTF-8?q?feat(deepseek):=20implement=20reasoning=5Fconte?= =?UTF-8?q?nt=20passback=20for=20multi-turn=20s=E2=80=A6=20(#190)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(deepseek): implement reasoning_content passback for multi-turn scenarios * fix(tests): ensure consistent import of EvoScientist.llm.patches in test cases * fix(tests): streamline tool_calls formatting in TestPatchDeepseekReasoningPassback * feat(patches): add reasoning_content capture and re-injection for DeepSeek assistant messages * fix(deepseek): optimize reasoning_content extraction and assignment in passback * fix(deepseek): refine reasoning_content handling in OpenAI capture patch --- EvoScientist/llm/models.py | 6 + EvoScientist/llm/patches.py | 130 +++++++++++++++ tests/test_llm.py | 315 ++++++++++++++++++++++++++++++++++++ 3 files changed, 451 insertions(+) diff --git a/EvoScientist/llm/models.py b/EvoScientist/llm/models.py index a7faa52..cc725bc 100644 --- a/EvoScientist/llm/models.py +++ b/EvoScientist/llm/models.py @@ -17,6 +17,7 @@ from langchain.chat_models import init_chat_model from .patches import ( _is_ccproxy_codex, _patch_ccproxy_system_to_developer, + _patch_deepseek_reasoning_passback, _patch_openai_compat_content, _patch_openrouter_reasoning_details, ) @@ -452,6 +453,11 @@ def get_chat_model( ) and _original_provider not in _no_patch_providers: _patch_openai_compat_content(chat_model) + # DeepSeek thinking mode requires reasoning_content passback in multi-turn + # + tool_use scenarios. + if _original_provider == "deepseek": + _patch_deepseek_reasoning_passback(chat_model) + if _is_openai_proxy: _patch_ccproxy_system_to_developer(chat_model) diff --git a/EvoScientist/llm/patches.py b/EvoScientist/llm/patches.py index 1bf7acf..fe95afb 100644 --- a/EvoScientist/llm/patches.py +++ b/EvoScientist/llm/patches.py @@ -9,6 +9,12 @@ Patches: - _patch_openai_compat_content: list content→string for strict APIs - _patch_ccproxy_codex_compat: ccproxy model fixes + langchain None guard - _patch_ccproxy_system_to_developer: system→developer role for ccproxy + - _patch_openai_capture_reasoning_content: capture provider + reasoning_content into AIMessage.additional_kwargs (module-level, + applied at import) + - _patch_deepseek_reasoning_passback: re-inject reasoning_content into + outgoing DeepSeek assistant messages for thinking-mode multi-turn / + tool_use scenarios Utilities: - _is_ccproxy_codex: detect ccproxy Codex OAuth adapter @@ -408,3 +414,127 @@ def _patch_ccproxy_system_to_developer(model: Any) -> None: yield chunk model._astream = _patched_astream + + +# --------------------------------------------------------------------------- +# Patch (module-level): langchain-openai's _convert_dict_to_message and +# _convert_delta_to_message_chunk discard provider-specific fields like +# `reasoning_content`. We monkey-patch them to capture reasoning_content +# into AIMessage.additional_kwargs so downstream code (incl. our passback +# patch) can find it. Benign for non-DeepSeek providers — they just don't +# return this field, so the patch is a no-op for them. +# --------------------------------------------------------------------------- +_openai_capture_patched = False + + +def _patch_openai_capture_reasoning_content() -> None: + global _openai_capture_patched + if _openai_capture_patched: + return + try: + import langchain_openai.chat_models.base as _base + + _orig_dict_to_msg = _base._convert_dict_to_message + _orig_delta_to_chunk = _base._convert_delta_to_message_chunk + + def _patched_dict_to_msg(_dict, *args, **kwargs): + msg = _orig_dict_to_msg(_dict, *args, **kwargs) + rc = _dict.get("reasoning_content") if isinstance(_dict, dict) else None + if isinstance(rc, str) and rc and hasattr(msg, "additional_kwargs"): + msg.additional_kwargs["reasoning_content"] = rc + return msg + + def _patched_delta_to_chunk(_dict, *args, **kwargs): + chunk = _orig_delta_to_chunk(_dict, *args, **kwargs) + rc = _dict.get("reasoning_content") if isinstance(_dict, dict) else None + if isinstance(rc, str) and rc and hasattr(chunk, "additional_kwargs"): + # Per-chunk: stash this delta's reasoning_content on the chunk. + # Cross-chunk accumulation is handled by AIMessageChunk.__add__ + # via merge_dicts (string values in additional_kwargs concatenate). + chunk.additional_kwargs["reasoning_content"] = ( + chunk.additional_kwargs.get("reasoning_content", "") + rc + ) + return chunk + + _base._convert_dict_to_message = _patched_dict_to_msg + _base._convert_delta_to_message_chunk = _patched_delta_to_chunk + _openai_capture_patched = True + except Exception: + pass + + +_patch_openai_capture_reasoning_content() + + +# --------------------------------------------------------------------------- +# Patch: DeepSeek thinking mode requires reasoning_content to be passed back +# in all assistant messages for multi-turn + tool_use scenarios. +# langchain-openai's _convert_message_to_dict drops this field, causing +# HTTP 400 "The reasoning_content in the thinking mode must be passed back". +# Mirrors langchain-ai/langchain PR #34516 (which patches langchain-deepseek; +# we apply equivalent logic to a langchain-openai ChatOpenAI instance). +# --------------------------------------------------------------------------- +def _patch_deepseek_reasoning_passback(model: Any) -> None: + """Inject reasoning_content into outgoing payload assistant messages. + + DeepSeek V4 thinking mode + tool_use requires every historical assistant + message to carry its reasoning_content as a top-level field (sibling to + content / tool_calls). Without this, multi-turn requests fail with 400. + + For deepseek-reasoner models, also injects an empty reasoning_content + when none is present (DeepSeek API requires the field even if empty). + + Args: + model: A langchain-openai ChatOpenAI instance configured for DeepSeek. + """ + import functools + + from langchain_core.messages import AIMessage + + orig = getattr(model, "_get_request_payload", None) + if orig is None: + return + + import logging as _logging + + _logger = _logging.getLogger(__name__) + + @functools.wraps(orig) + def _patched(input_: Any, *, stop: Any = None, **kwargs: Any) -> dict: + try: + lc_messages = model._convert_input(input_).to_messages() + except Exception: + _logger.warning( + "DeepSeek passback patch: _convert_input failed, " + "falling back to unpatched payload (reasoning_content " + "will not be injected)", + exc_info=True, + ) + return orig(input_, stop=stop, **kwargs) + + ai_rcs: list[str | None] = [ + m.additional_kwargs.get("reasoning_content") + for m in lc_messages + if isinstance(m, AIMessage) + ] + + payload = orig(input_, stop=stop, **kwargs) + msgs = payload.get("messages") + if not isinstance(msgs, list): + return payload + + is_reasoner = "deepseek-reasoner" in str(getattr(model, "model_name", "")) + ai_idx = 0 + for msg in msgs: + if not isinstance(msg, dict) or msg.get("role") != "assistant": + continue + rc = ai_rcs[ai_idx] if ai_idx < len(ai_rcs) else None + if rc: + msg["reasoning_content"] = rc + elif is_reasoner and "reasoning_content" not in msg: + msg["reasoning_content"] = "" + ai_idx += 1 + + return payload + + model._get_request_payload = _patched diff --git a/tests/test_llm.py b/tests/test_llm.py index d1f3dfa..9a4c24f 100644 --- a/tests/test_llm.py +++ b/tests/test_llm.py @@ -4,6 +4,10 @@ from unittest.mock import patch import pytest +# Side-effect import: applies module-level monkey-patches (e.g., +# _patch_openai_capture_reasoning_content) before tests reference patched +# functions from langchain_openai. +import EvoScientist.llm.patches # noqa: F401 from EvoScientist.llm import ( DEFAULT_MODEL, MODELS, @@ -799,6 +803,317 @@ class TestPatchOpenAICompatContent: assert received_msgs[0].content == "hello" +# ============================================================================= +# Test _patch_deepseek_reasoning_passback +# ============================================================================= + + +class TestPatchDeepseekReasoningPassback: + """Verify reasoning_content is injected into DeepSeek payload assistant messages. + + This patch fixes the 400 error from DeepSeek V4 thinking mode in multi-turn + + tool_use scenarios. See langchain PR #34516 for upstream reference. + """ + + def _make_model(self, model_name="deepseek-v4-pro", payload_messages=None): + """Create a mock ChatOpenAI-like model for the DeepSeek base URL.""" + from unittest.mock import MagicMock + + if payload_messages is None: + payload_messages = [ + {"role": "user", "content": "hi"}, + {"role": "assistant", "content": "hello"}, + {"role": "user", "content": "ok"}, + ] + + model = MagicMock() + model.model_name = model_name + + class _Wrapped: + def __init__(self, msgs): + self._msgs = msgs + + def to_messages(self): + return self._msgs + + model._convert_input = lambda x: _Wrapped(x) + model._get_request_payload = MagicMock( + return_value={"messages": payload_messages} + ) + return model + + def test_injects_reasoning_content_from_additional_kwargs(self): + from langchain_core.messages import AIMessage, HumanMessage + + from EvoScientist.llm.patches import _patch_deepseek_reasoning_passback + + model = self._make_model() + _patch_deepseek_reasoning_passback(model) + + messages = [ + HumanMessage("hi"), + AIMessage( + content="hello", + additional_kwargs={"reasoning_content": "let me think..."}, + ), + HumanMessage("ok"), + ] + payload = model._get_request_payload(messages) + + assert payload["messages"][1]["reasoning_content"] == "let me think..." + + def test_empty_reasoning_for_reasoner_model(self): + from langchain_core.messages import AIMessage, HumanMessage + + from EvoScientist.llm.patches import _patch_deepseek_reasoning_passback + + model = self._make_model(model_name="deepseek-reasoner") + _patch_deepseek_reasoning_passback(model) + + messages = [ + HumanMessage("hi"), + AIMessage(content="hello"), # no reasoning_content + HumanMessage("ok"), + ] + payload = model._get_request_payload(messages) + + assert payload["messages"][1]["reasoning_content"] == "" + + def test_no_injection_for_non_reasoner_without_rc(self): + from langchain_core.messages import AIMessage, HumanMessage + + from EvoScientist.llm.patches import _patch_deepseek_reasoning_passback + + model = self._make_model(model_name="deepseek-v4-pro") + _patch_deepseek_reasoning_passback(model) + + messages = [ + HumanMessage("hi"), + AIMessage(content="hello"), # no reasoning_content + HumanMessage("ok"), + ] + payload = model._get_request_payload(messages) + + assert "reasoning_content" not in payload["messages"][1] + + def test_handles_multiple_ai_messages(self): + from langchain_core.messages import AIMessage, HumanMessage + + from EvoScientist.llm.patches import _patch_deepseek_reasoning_passback + + model = self._make_model( + payload_messages=[ + {"role": "user", "content": "q1"}, + {"role": "assistant", "content": "a1"}, + {"role": "user", "content": "q2"}, + {"role": "assistant", "content": "a2"}, + {"role": "user", "content": "q3"}, + ] + ) + _patch_deepseek_reasoning_passback(model) + + messages = [ + HumanMessage("q1"), + AIMessage(content="a1", additional_kwargs={"reasoning_content": "rc1"}), + HumanMessage("q2"), + AIMessage(content="a2", additional_kwargs={"reasoning_content": "rc2"}), + HumanMessage("q3"), + ] + payload = model._get_request_payload(messages) + + assert payload["messages"][1]["reasoning_content"] == "rc1" + assert payload["messages"][3]["reasoning_content"] == "rc2" + + def test_real_world_tool_use_flow(self): + """The real scenario this patch was built for: AI thinks → tool_call → + ToolMessage → next turn must carry reasoning_content from prior AI msg. + + This mirrors what happens in /tmp/verify_deepseek.py and what the user + actually triggers via 'create file then read it' in EvoSci CLI. + """ + from langchain_core.messages import AIMessage, HumanMessage, ToolMessage + + from EvoScientist.llm.patches import _patch_deepseek_reasoning_passback + + # Mock payload that mirrors what langchain-openai produces: + # user → assistant (with tool_calls) → tool_result → user (next turn) + model = self._make_model( + payload_messages=[ + {"role": "user", "content": "Read hello.txt"}, + { + "role": "assistant", + "content": "", + "tool_calls": [ + { + "id": "call_1", + "type": "function", + "function": {"name": "read_file", "arguments": "{}"}, + } + ], + }, + {"role": "tool", "content": "file contents", "tool_call_id": "call_1"}, + {"role": "user", "content": "now what?"}, + ] + ) + _patch_deepseek_reasoning_passback(model) + + messages = [ + HumanMessage("Read hello.txt"), + AIMessage( + content="", + additional_kwargs={"reasoning_content": "I should call read_file"}, + tool_calls=[{"name": "read_file", "args": {}, "id": "call_1"}], + ), + ToolMessage(content="file contents", tool_call_id="call_1"), + HumanMessage("now what?"), + ] + payload = model._get_request_payload(messages) + + # The assistant message (index 1) must carry reasoning_content + assistant_msg = payload["messages"][1] + assert assistant_msg["role"] == "assistant" + assert assistant_msg["reasoning_content"] == "I should call read_file" + # tool_calls preserved + assert "tool_calls" in assistant_msg + # ToolMessage (index 2) untouched + assert "reasoning_content" not in payload["messages"][2] + + def test_mixed_ai_messages_with_and_without_rc(self): + """Some AIMessages have reasoning_content, some don't (e.g., legacy turns + before patch was deployed). Each should be handled independently.""" + from langchain_core.messages import AIMessage, HumanMessage + + from EvoScientist.llm.patches import _patch_deepseek_reasoning_passback + + model = self._make_model( + model_name="deepseek-v4-pro", # NOT reasoner — empty fallback off + payload_messages=[ + {"role": "user", "content": "q1"}, + {"role": "assistant", "content": "a1"}, # no rc + {"role": "user", "content": "q2"}, + {"role": "assistant", "content": "a2"}, # has rc + {"role": "user", "content": "q3"}, + ], + ) + _patch_deepseek_reasoning_passback(model) + + messages = [ + HumanMessage("q1"), + AIMessage(content="a1"), # no reasoning_content + HumanMessage("q2"), + AIMessage( + content="a2", + additional_kwargs={"reasoning_content": "rc2"}, + ), + HumanMessage("q3"), + ] + payload = model._get_request_payload(messages) + + # First AI msg: no rc → not injected (V4 Pro doesn't get empty fallback) + assert "reasoning_content" not in payload["messages"][1] + # Second AI msg: has rc → injected + assert payload["messages"][3]["reasoning_content"] == "rc2" + + def test_handles_responses_api_payload(self): + """Payload without 'messages' key (e.g. Responses API) should not crash.""" + from unittest.mock import MagicMock + + from langchain_core.messages import HumanMessage + + from EvoScientist.llm.patches import _patch_deepseek_reasoning_passback + + model = MagicMock() + model.model_name = "deepseek-v4-pro" + + class _Wrapped: + def __init__(self, msgs): + self._msgs = msgs + + def to_messages(self): + return self._msgs + + model._convert_input = lambda x: _Wrapped(x) + # Simulate Responses API payload (no 'messages' key) + model._get_request_payload = MagicMock( + return_value={"input": [{"role": "user", "content": "hi"}]} + ) + + _patch_deepseek_reasoning_passback(model) + + # Should not raise, just return the payload as-is + payload = model._get_request_payload([HumanMessage("hi")]) + assert "input" in payload + assert "messages" not in payload + + +# ============================================================================= +# Test _patch_openai_capture_reasoning_content (module-level monkey-patch) +# ============================================================================= + + +class TestPatchOpenAICaptureReasoningContent: + """Verify reasoning_content is captured into AIMessage.additional_kwargs. + + This patch is applied at import time and globally affects langchain-openai's + _convert_dict_to_message and _convert_delta_to_message_chunk. + """ + + def test_capture_from_non_streaming_response(self): + """reasoning_content in OpenAI response dict → AIMessage.additional_kwargs.""" + from langchain_openai.chat_models.base import _convert_dict_to_message + + msg = _convert_dict_to_message( + { + "role": "assistant", + "content": "hi", + "reasoning_content": "let me think...", + } + ) + assert msg.additional_kwargs.get("reasoning_content") == "let me think..." + + def test_capture_absent_when_field_missing(self): + """No reasoning_content in response → not added to additional_kwargs.""" + from langchain_openai.chat_models.base import _convert_dict_to_message + + msg = _convert_dict_to_message({"role": "assistant", "content": "hi"}) + assert "reasoning_content" not in msg.additional_kwargs + + def test_capture_from_streaming_chunk(self): + """reasoning_content delta is captured onto the chunk's additional_kwargs.""" + from langchain_core.messages import AIMessageChunk + from langchain_openai.chat_models.base import ( + _convert_delta_to_message_chunk, + ) + + chunk = _convert_delta_to_message_chunk( + {"role": "assistant", "content": "", "reasoning_content": "thinking"}, + AIMessageChunk, + ) + assert chunk.additional_kwargs.get("reasoning_content") == "thinking" + + def test_capture_does_not_affect_other_fields(self): + """Existing tool_calls / function_call extraction unaffected.""" + from langchain_openai.chat_models.base import _convert_dict_to_message + + msg = _convert_dict_to_message( + { + "role": "assistant", + "content": "calling tool", + "tool_calls": [ + { + "id": "call_1", + "type": "function", + "function": {"name": "get_weather", "arguments": "{}"}, + } + ], + "reasoning_content": "use the tool", + } + ) + assert len(msg.tool_calls) == 1 + assert msg.tool_calls[0]["name"] == "get_weather" + assert msg.additional_kwargs.get("reasoning_content") == "use the tool" + + # ============================================================================= # Test _apply_auto_config # =============================================================================