langchain - ✅(Solved) Fix langchain deepseek:_get_request_payload中缺少reasoning_content返回会导致多回合agent调用出现400错误 [1 pull requests, 6 comments, 2 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
langchain-ai/langchain#37178Fetched 2026-05-05 05:43:42
View on GitHub
Comments
6
Participants
2
Timeline
29
Reactions
0
Timeline (top)
mentioned ×8subscribed ×8commented ×6labeled ×3

用 langchain-deepseek(v1.0.1)调用deepseek-v4-flash时,跑 agent.invoke() 会在第二次内部调用 LLM 的时候挂掉,报 400 错误。 原因:DeepSeek API 要求,如果你在后续请求里要传回上一条助手消息,那这条消息里的 reasoning_content 字段必须原样带上。但是 ChatDeepSeek._get_request_payload() 用的是父类 BaseChatOpenAI._get_request_payload(),它调用的 _convert_message_to_dict() 在把 AIMessage 转成字典的时候,会把 additional_kwargs(包括 reasoning_content)给扔掉。 ChatDeepSeek._create_chat_result() 其实是能从 API 返回的结果里拿到 reasoning_content,并正确存放到 AIMessage.additional_kwargs["reasoning_content"] 里面的。但问题是,后面再发请求的时候,_get_request_payload() 里并没有对应的逻辑把它再塞回去。 修复方法:在 _get_request_payload() 里打了个补丁,让它先去拿到原始的 AIMessage 对象,然后从 additional_kwargs 里把 reasoning_content 捞出来,在发请求前塞到 API 的载荷字典里。

Error Message

openai.BadRequestError: Error code: 400 {'error': {'message': 'The reasoning_content in the thinking mode must be passed back to the API.', 'type': 'invalid_request_error', 'param': None, 'code': 'invalid_request_error'}}

Traceback (most recent call last): File "test_agent.py", line 17, in <module> res = agent.invoke({"messages": [{"role": "user", "content": "..."}]}) File ".../langgraph/pregel/main.py", line 3365, in invoke for chunk in self.stream(...) ... File ".../langchain_deepseek/chat_models.py", line 356, in _generate return super()._generate(...) File ".../langchain_openai/chat_models/base.py", line 1653, in _generate _handle_openai_bad_request(e) openai.BadRequestError: Error code: 400 - {'error': {'message': 'The reasoning_content in the thinking mode must be passed back to the API.'}}

Root Cause

用 langchain-deepseek(v1.0.1)调用deepseek-v4-flash时,跑 agent.invoke() 会在第二次内部调用 LLM 的时候挂掉,报 400 错误。 原因:DeepSeek API 要求,如果你在后续请求里要传回上一条助手消息,那这条消息里的 reasoning_content 字段必须原样带上。但是 ChatDeepSeek._get_request_payload() 用的是父类 BaseChatOpenAI._get_request_payload(),它调用的 _convert_message_to_dict() 在把 AIMessage 转成字典的时候,会把 additional_kwargs(包括 reasoning_content)给扔掉。 ChatDeepSeek._create_chat_result() 其实是能从 API 返回的结果里拿到 reasoning_content,并正确存放到 AIMessage.additional_kwargs["reasoning_content"] 里面的。但问题是,后面再发请求的时候,_get_request_payload() 里并没有对应的逻辑把它再塞回去。 修复方法:在 _get_request_payload() 里打了个补丁,让它先去拿到原始的 AIMessage 对象,然后从 additional_kwargs 里把 reasoning_content 捞出来,在发请求前塞到 API 的载荷字典里。

Fix Action

Fix / Workaround

  • This is a bug, not a usage question.
  • I added a clear and descriptive title that summarizes this issue.
  • I used the GitHub search to find a similar question and didn't find it.
  • I am sure that this is a bug in LangChain rather than my code.
  • The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package).
  • This is not related to the langchain-community package.
  • I posted a self-contained, minimal, reproducible example. A maintainer can copy it and run it AS IS.

PR fix notes

PR #37179: fix(deepseek): pass reasoning_content back in multi-turn requests

Description (problem / solution / changelog)

Summary

Fixes #37178

  • DeepSeek thinking models (deepseek-r1, deepseek-v4-flash) require reasoning_content to be echoed back in every subsequent API request when in thinking mode
  • _create_chat_result() already correctly stores it in AIMessage.additional_kwargs["reasoning_content"]
  • But _get_request_payload() delegates to the parent BaseChatOpenAI, which serializes messages via _convert_message_to_dict() — that function drops additional_kwargs entirely
  • Result: 400 - "The reasoning_content in the thinking mode must be passed back to the API." on the second LLM call in any agent loop

Fix: In _get_request_payload(), after the parent builds the payload, convert input_ back to original BaseMessage objects via self._convert_input(input_).to_messages(), collect reasoning_content values from AIMessage objects in order, then inject them into the corresponding "assistant" message dicts before the request is sent.

Test plan

  • Existing unit tests pass: cd libs/partners/deepseek && poetry run pytest tests/unit_tests/
  • Manual: create a multi-turn agent with a tool using deepseek-r1 or deepseek-v4-flash — no longer raises 400 on the second LLM call
  • Non-thinking models unaffected (no reasoning_content in additional_kwargs, so nothing is injected)

authored-by: Shweta Lodha [email protected]

Changed files

  • libs/partners/deepseek/langchain_deepseek/chat_models.py (modified, +28/-11)

Code Example

from langchain.agents import create_agent
  from langchain_core.tools import tool
  from langchain.chat_models import init_chat_model

  @tool(description="query weather")
  def get_weather() -> str:
      return "sunny"

  model = init_chat_model(model="deepseek-v4-flash")

  agent = create_agent(
      model=model,
      tools=[get_weather],
      system_prompt="You are a helpful assistant.",
  )

  res = agent.invoke({
      "messages": [
          {"role": "user", "content": "What is the weather tomorrow?"},
      ]
  })

  for msg in res["messages"]:
      print(type(msg).__name__, msg.content)

---

openai.BadRequestError: Error code: 400
  {'error': {'message': 'The `reasoning_content` in the thinking mode must be passed back to the API.', 'type': 'invalid_request_error',
  'param': None, 'code': 'invalid_request_error'}}

  Traceback (most recent call last):
    File "test_agent.py", line 17, in <module>
      res = agent.invoke({"messages": [{"role": "user", "content": "..."}]})
    File ".../langgraph/pregel/main.py", line 3365, in invoke
      for chunk in self.stream(...)
    ...
    File ".../langchain_deepseek/chat_models.py", line 356, in _generate
      return super()._generate(...)
    File ".../langchain_openai/chat_models/base.py", line 1653, in _generate
      _handle_openai_bad_request(e)
  openai.BadRequestError: Error code: 400 - {'error': {'message': 'The `reasoning_content` in the thinking mode must be passed back to the
  API.'}}
RAW_BUFFERClick to expand / collapse

Submission checklist

  • This is a bug, not a usage question.
  • I added a clear and descriptive title that summarizes this issue.
  • I used the GitHub search to find a similar question and didn't find it.
  • I am sure that this is a bug in LangChain rather than my code.
  • The bug is not resolved by updating to the latest stable version of LangChain (or the specific integration package).
  • This is not related to the langchain-community package.
  • I posted a self-contained, minimal, reproducible example. A maintainer can copy it and run it AS IS.

Package (Required)

  • langchain
  • langchain-openai
  • langchain-anthropic
  • langchain-classic
  • langchain-core
  • langchain-model-profiles
  • langchain-tests
  • langchain-text-splitters
  • langchain-chroma
  • langchain-deepseek
  • langchain-exa
  • langchain-fireworks
  • langchain-groq
  • langchain-huggingface
  • langchain-mistralai
  • langchain-nomic
  • langchain-ollama
  • langchain-openrouter
  • langchain-perplexity
  • langchain-qdrant
  • langchain-xai
  • Other / not sure / general

Related Issues / PRs

No response

Reproduction Steps / Example Code (Python)

from langchain.agents import create_agent
  from langchain_core.tools import tool
  from langchain.chat_models import init_chat_model

  @tool(description="query weather")
  def get_weather() -> str:
      return "sunny"

  model = init_chat_model(model="deepseek-v4-flash")

  agent = create_agent(
      model=model,
      tools=[get_weather],
      system_prompt="You are a helpful assistant.",
  )

  res = agent.invoke({
      "messages": [
          {"role": "user", "content": "What is the weather tomorrow?"},
      ]
  })

  for msg in res["messages"]:
      print(type(msg).__name__, msg.content)

Error Message and Stack Trace (if applicable)

openai.BadRequestError: Error code: 400
  {'error': {'message': 'The `reasoning_content` in the thinking mode must be passed back to the API.', 'type': 'invalid_request_error',
  'param': None, 'code': 'invalid_request_error'}}

  Traceback (most recent call last):
    File "test_agent.py", line 17, in <module>
      res = agent.invoke({"messages": [{"role": "user", "content": "..."}]})
    File ".../langgraph/pregel/main.py", line 3365, in invoke
      for chunk in self.stream(...)
    ...
    File ".../langchain_deepseek/chat_models.py", line 356, in _generate
      return super()._generate(...)
    File ".../langchain_openai/chat_models/base.py", line 1653, in _generate
      _handle_openai_bad_request(e)
  openai.BadRequestError: Error code: 400 - {'error': {'message': 'The `reasoning_content` in the thinking mode must be passed back to the
  API.'}}

Description

用 langchain-deepseek(v1.0.1)调用deepseek-v4-flash时,跑 agent.invoke() 会在第二次内部调用 LLM 的时候挂掉,报 400 错误。 原因:DeepSeek API 要求,如果你在后续请求里要传回上一条助手消息,那这条消息里的 reasoning_content 字段必须原样带上。但是 ChatDeepSeek._get_request_payload() 用的是父类 BaseChatOpenAI._get_request_payload(),它调用的 _convert_message_to_dict() 在把 AIMessage 转成字典的时候,会把 additional_kwargs(包括 reasoning_content)给扔掉。 ChatDeepSeek._create_chat_result() 其实是能从 API 返回的结果里拿到 reasoning_content,并正确存放到 AIMessage.additional_kwargs["reasoning_content"] 里面的。但问题是,后面再发请求的时候,_get_request_payload() 里并没有对应的逻辑把它再塞回去。 修复方法:在 _get_request_payload() 里打了个补丁,让它先去拿到原始的 AIMessage 对象,然后从 additional_kwargs 里把 reasoning_content 捞出来,在发请求前塞到 API 的载荷字典里。

System Info

Package: langchain-deepseek 1.0.1 Model: deepseek-v4-flash (also affects deepseek-r1) OS: Windows 11 Python: 3.10

我是一名来自中国天津的大学生,目前正在学习LangChain框架。我在构建一个简单用于测试目的agent时发现了此问题。

extent analysis

TL;DR

The issue can be fixed by modifying the _get_request_payload() method in ChatDeepSeek to include the reasoning_content from the additional_kwargs of the AIMessage object.

Guidance

  • Identify the _get_request_payload() method in ChatDeepSeek and modify it to retrieve the reasoning_content from the additional_kwargs of the AIMessage object.
  • Add the retrieved reasoning_content to the API payload dictionary before making the request.
  • Verify that the reasoning_content is correctly passed back to the API in subsequent requests.
  • Test the modified code to ensure that the 400 error is resolved and the agent invokes correctly.

Example

def _get_request_payload(self, messages):
    # ... existing code ...
    for message in messages:
        if message.additional_kwargs and 'reasoning_content' in message.additional_kwargs:
            payload['reasoning_content'] = message.additional_kwargs['reasoning_content']
    # ... existing code ...

Notes

The fix requires modifying the langchain-deepseek package, specifically the ChatDeepSeek class. The modified code should be tested thoroughly to ensure that it resolves the issue and does not introduce any new errors.

Recommendation

Apply the workaround by modifying the _get_request_payload() method to include the reasoning_content from the additional_kwargs of the AIMessage object. This should resolve the 400 error and allow the agent to invoke correctly.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING