Fix #5878: Preserve reasoning_content from DeepSeek thinking mode in conversation history
Summary
Fixes #5878. DeepSeek V4 models return reasoning_content alongside content in thinking mode. The DeepSeek API requires this reasoning_content to be passed back in subsequent API calls for multi-turn conversations. Previously, CrewAI discarded reasoning_content from LLM responses, causing DeepSeek API errors in multi-turn conversations.
This PR:
- Extracts
reasoning_contentfrom the litellm response inLLM._handle_non_streaming_response()and stores it on the LLM instance - Resets
reasoning_contentat the start of eachLLM.call()to avoid stale values - Propagates
reasoning_contentinto assistant messages viaformat_message_for_llm(),_append_message(), and_append_message_to_state() - Adds
reasoning_contentas an optional field onLLMMessageTypedDict
Files changed:
lib/crewai/src/crewai/llm.py— extract + store reasoning_contentlib/crewai/src/crewai/utilities/types.py— add field to LLMMessagelib/crewai/src/crewai/utilities/agent_utils.py— format_message_for_llm now accepts reasoning_contentlib/crewai/src/crewai/agents/crew_agent_executor.py— propagate in all sync/async loopslib/crewai/src/crewai/experimental/agent_executor.py— propagate in native tools pathlib/crewai/tests/llms/litellm/test_reasoning_content.py— 13 new tests
Review & Testing Checklist for Human
- [ ] Verify that
reasoning_contentis correctly extracted from a real DeepSeek API response (the mock tests verify the extraction logic, but a manual test withdeepseek/deepseek-reasonerwould confirm end-to-end) - [ ] Check that normal models (GPT-4o, Claude, etc.) are unaffected —
reasoning_contentshould beNoneand assistant messages should not contain the field - [ ] Confirm the
reasoning_contentfield inLLMMessageTypedDict doesn't break any downstream serialization or message processing
Notes
- The fix uses a dual extraction approach (
getattr+.get()) to handle both attribute-style and dict-style access patterns from litellm's Message object reasoning_contentis only added to assistant messages (not user/system) per the DeepSeek API specification- The
CrewAgentExecutoris deprecated but still receives the fix for backward compatibility; the experimentalAgentExecutoris also updated - Supersedes #5879 which had merge conflicts due to the monorepo restructuring
Link to Devin session: https://app.devin.ai/sessions/584ca5a82022414490972068929d4d53
Summary by CodeRabbit
-
New Features
- Capture and preserve AI model "reasoning" content in assistant messages so conversation history reflects model explanations.
- Ensure reasoning content is included only for assistant outputs and is reset between model calls.
-
Tests
- Added tests covering extraction, storage, formatting rules, and propagation of reasoning content through agent execution.
🤖 Devin AI Engineer
I'll be helping with this pull request! Here's what you should know:
✅ I will automatically:
- Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
- Look at CI failures and help fix them
Note: I can only respond to comments from users who have write access to this repository.
⚙️ Control Options:
- [ ] Disable automatic comment and CI monitoring
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: a636db4b-8be0-4780-b30a-3bbf96471aad
📥 Commits
Reviewing files that changed from the base of the PR and between d93040efa71b86aeb046236a96401696711d5948 and ce4399e769bbc9c2534c756f22b997e1d95cffca.
📒 Files selected for processing (3)
lib/crewai/src/crewai/agents/crew_agent_executor.pylib/crewai/src/crewai/experimental/agent_executor.pylib/crewai/src/crewai/llm.py
📝 Walkthrough
Walkthrough
This PR adds end-to-end support for capturing and propagating LLM reasoning_content (from DeepSeek thinking mode) through agent execution flows. The LLM layer extracts reasoning from responses, executors retrieve it via a new helper, and message formatting conditionally includes it in assistant messages.
Changes
Reasoning Content Propagation
| Layer / File(s) | Summary |
|---|---|
Type contracts and messaging infrastructure lib/crewai/src/crewai/utilities/types.py, lib/crewai/src/crewai/utilities/agent_utils.py |
LLMMessage TypedDict adds optional reasoning_content: NotRequired[str | None] field; format_message_for_llm() signature extends to accept optional reasoning_content parameter and includes it in returned message dict when role is "assistant". |
LLM response handling lib/crewai/src/crewai/llm.py |
LLM.call() initializes self.reasoning_content = None at invocation start; _handle_non_streaming_response() extracts reasoning_content from response messages (via attribute or dict-style access) and stores it in self.reasoning_content. |
CrewAgentExecutor reasoning propagation lib/crewai/src/crewai/agents/crew_agent_executor.py |
New _get_llm_reasoning_content() helper reads reasoning_content from the configured LLM; _append_message() signature extended with optional reasoning_content parameter forwarded to format_message_for_llm(); applied across synchronous and asynchronous execution loops in ReAct and native tool-calling paths. |
Experimental AgentExecutor reasoning propagation lib/crewai/src/crewai/experimental/agent_executor.py |
New _get_llm_reasoning_content() helper; _append_message_to_state() signature extended with optional reasoning_content parameter; applied in native tool-calling response paths for BaseModel, string, and unexpected outputs. |
Test coverage lib/crewai/tests/llms/litellm/test_reasoning_content.py |
New test module with three test classes: TestLLMReasoningContent verifies extraction and reset behavior; TestFormatMessageReasoningContent validates conditional inclusion based on role; TestCrewExecutorReasoningContent ensures propagation through executor invoke loops with reasoning preserved for DeepSeek-style models and omitted for normal models. |
Estimated code review effort
🎯 3 (Moderate) | ⏱️ ~20 minutes
Suggested labels
enhancement
Suggested reviewers
- greysonlalonde
Poem
🐰 I tunneled through code to catch the thought, Collected DeepSeek whispers that models brought. Now messages carry the mind's quiet art, From LLM to history, reasoning plays its part. Hooray — the crew keeps every thinking heart.
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | ⚠️ Warning | Docstring coverage is 65.63% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |
✅ Passed checks (4 passed)
| Check name | Status | Explanation |
|---|---|---|
| Description Check | ✅ Passed | Check skipped - CodeRabbit’s high-level summary is enabled. |
| Title check | ✅ Passed | The title clearly identifies the issue being fixed (#5878) and describes the main change: preserving reasoning_content from DeepSeek thinking mode in conversation history. |
| Linked Issues check | ✅ Passed | The PR successfully implements all coding requirements from #5878: extracts and stores reasoning_content from LLM responses, resets it between calls, propagates it through message history for assistant messages, updates LLMMessage TypedDict, and handles multi-turn conversations. |
| Out of Scope Changes check | ✅ Passed | All changes are directly aligned with the linked issue #5878 requirements. Modifications to LLM extraction, message formatting, and executor propagation are all in-scope, plus comprehensive test coverage. |
✏️ Tip: You can configure your own custom pre-merge checks in the settings.
✨ Finishing Touches
📝 Generate docstrings
- [ ] Create stacked PR
- [ ] Commit on current branch
🧪 Generate unit tests (beta)
- [ ] Create PR with unit tests
- [ ] Commit unit tests in branch
devin/1779340749-fix-reasoning-content-5878
Comment @coderabbitai help to get the list of available commands and usage tips.
Could you provide an example of a working Python code?