Skip to content

armgit / camel

Public Imported from GitHub
0

🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org

feat: Support DeepSeek V4 thinking tool calls (#4026)

Tao Sunb2f65e913ec9
diff --git a/camel/configs/deepseek_config.py b/camel/configs/deepseek_config.py
index 09ba19a42..af17e9d87 100644
--- a/camel/configs/deepseek_config.py
+++ b/camel/configs/deepseek_config.py
@@ -16,7 +16,7 @@ from __future__ import annotations
from typing import Dict, Optional, Sequence, Type, Union
-from pydantic import BaseModel
+from pydantic import BaseModel, JsonValue
from camel.configs.base_config import BaseConfig
@@ -83,6 +83,17 @@ class DeepSeekConfig(BaseConfig):
include_usage (bool, optional): When streaming, specifies whether to
include usage information in `stream_options`.
(default: :obj:`None`)
+ reasoning_effort (str, optional): Controls DeepSeek thinking effort.
+ Current DeepSeek values are :obj:`"high"` and :obj:`"max"`;
+ compatibility values such as :obj:`"low"`, :obj:`"medium"`,
+ and :obj:`"xhigh"` are mapped by DeepSeek. (default: :obj:`None`)
+ thinking (dict, optional): DeepSeek thinking mode configuration,
+ such as :obj:`{"type": "enabled"}` or
+ :obj:`{"type": "disabled"}`. It will be moved into
+ :obj:`extra_body` by :obj:`DeepSeekModel` when using the OpenAI
+ SDK. (default: :obj:`None`)
+ extra_body (dict, optional): Additional request body parameters passed
+ through the OpenAI-compatible SDK. (default: :obj:`None`)
"""
temperature: Optional[float] = None # deepseek default: 1.0
@@ -99,6 +110,9 @@ class DeepSeekConfig(BaseConfig):
logprobs: Optional[bool] = None
top_logprobs: Optional[int] = None
stream_options: Optional[dict[str, bool]] = None
+ reasoning_effort: Optional[str] = None
+ thinking: Optional[Dict[str, JsonValue]] = None
+ extra_body: Optional[Dict[str, JsonValue]] = None
def __init__(self, include_usage: bool = True, **kwargs):
if kwargs.get("stream") and "stream_options" not in kwargs:
diff --git a/camel/models/deepseek_model.py b/camel/models/deepseek_model.py
index 7b268b702..5a2c20f6a 100644
--- a/camel/models/deepseek_model.py
+++ b/camel/models/deepseek_model.py
@@ -12,8 +12,21 @@
# limitations under the License.
# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========
+import copy
import os
-from typing import Any, Dict, List, Optional, Type, Union
+from typing import (
+ Any,
+ AsyncIterator,
+ Dict,
+ Iterator,
+ List,
+ Mapping,
+ Optional,
+ Set,
+ Type,
+ Union,
+ cast,
+)
from openai import AsyncStream, Stream
from pydantic import BaseModel
@@ -49,16 +62,19 @@ else:
logger = get_logger(__name__)
-REASONSER_UNSUPPORTED_PARAMS = [
- "temperature",
- "top_p",
- "presence_penalty",
- "frequency_penalty",
+DEEPSEEK_THINKING_MODE_MODELS = {
+ "deepseek-reasoner",
+ "deepseek-v4-flash",
+ "deepseek-v4-pro",
+}
+
+DEEPSEEK_THINKING_MODE_ERROR_PARAMS = [
"logprobs",
"top_logprobs",
- "tools",
]
+DEFAULT_REASONING_SESSION_ID = "__default__"
+
class DeepSeekModel(OpenAICompatibleModel):
r"""DeepSeek API in a unified OpenAICompatibleModel interface.
@@ -124,6 +140,312 @@ class DeepSeekModel(OpenAICompatibleModel):
max_retries=max_retries,
**kwargs,
)
+ self._tool_call_reasoning_by_session: Dict[str, Dict[str, str]] = {}
+ self._assistant_reasoning_by_session: Dict[str, Dict[str, str]] = {}
+
+ def _get_reasoning_session_id(self) -> str:
+ r"""Get the current agent session ID for reasoning cache isolation."""
+ try:
+ from camel.utils.agent_context import get_current_agent_id
+
+ return get_current_agent_id() or DEFAULT_REASONING_SESSION_ID
+ except Exception:
+ return DEFAULT_REASONING_SESSION_ID
+
+ @staticmethod
+ def _get_tool_call_id(tool_call: Any) -> Optional[str]:
+ if isinstance(tool_call, dict):
+ tool_call_id = tool_call.get("id")
+ else:
+ tool_call_id = getattr(tool_call, "id", None)
+
+ return tool_call_id if isinstance(tool_call_id, str) else None
+
+ @staticmethod
+ def _get_message_content(message: Any) -> Optional[str]:
+ if isinstance(message, dict):
+ content = message.get("content")
+ else:
+ content = getattr(message, "content", None)
+
+ return content if isinstance(content, str) else None
+
+ def _cache_tool_call_reasoning(self, response: Any) -> None:
+ r"""Cache reasoning content for DeepSeek thinking-mode tool calls.
+
+ DeepSeek requires the assistant ``reasoning_content`` generated with a
+ tool call to be passed back in later requests. CAMEL memory stores the
+ OpenAI-compatible tool-call message, so the model layer keeps the
+ DeepSeek-specific field keyed by tool_call_id and injects it before
+ the next request.
+ """
+ if not isinstance(response, ChatCompletion):
+ return
+
+ session_id = self._get_reasoning_session_id()
+ session_cache = self._tool_call_reasoning_by_session.setdefault(
+ session_id, {}
+ )
+ assistant_reasoning_cache = (
+ self._assistant_reasoning_by_session.setdefault(session_id, {})
+ )
+
+ for choice in response.choices:
+ message = getattr(choice, "message", None)
+ if message is None:
+ continue
+
+ reasoning_content = getattr(message, "reasoning_content", None)
+ content = self._get_message_content(message)
+ if reasoning_content and content:
+ assistant_reasoning_cache[content] = reasoning_content
+
+ tool_calls = getattr(message, "tool_calls", None)
+ if not reasoning_content or not tool_calls:
+ continue
+
+ for tool_call in tool_calls:
+ tool_call_id = self._get_tool_call_id(tool_call)
+ if tool_call_id:
+ session_cache[tool_call_id] = reasoning_content
+
+ def _cache_reasoning_content(
+ self,
+ reasoning_content: Optional[str],
+ tool_call_ids: List[str],
+ content: Optional[str] = None,
+ ) -> None:
+ r"""Cache DeepSeek reasoning collected from a streamed response."""
+ if not reasoning_content:
+ return
+
+ session_id = self._get_reasoning_session_id()
+ if tool_call_ids:
+ session_cache = self._tool_call_reasoning_by_session.setdefault(
+ session_id, {}
+ )
+ for tool_call_id in tool_call_ids:
+ session_cache[tool_call_id] = reasoning_content
+
+ if content:
+ assistant_reasoning_cache = (
+ self._assistant_reasoning_by_session.setdefault(session_id, {})
+ )
+ assistant_reasoning_cache[content] = reasoning_content
+
+ def _collect_stream_reasoning(
+ self,
+ chunk: ChatCompletionChunk,
+ reasoning_parts: List[str],
+ content_parts: List[str],
+ tool_call_ids: Set[str],
+ ) -> None:
+ r"""Collect reasoning/content/tool ids from a streaming chunk."""
+ for choice in getattr(chunk, "choices", []) or []:
+ delta = getattr(choice, "delta", None)
+ if delta is None:
+ continue
+
+ reasoning_delta = getattr(delta, "reasoning_content", None)
+ if isinstance(reasoning_delta, str) and reasoning_delta:
+ reasoning_parts.append(reasoning_delta)
+
+ content_delta = getattr(delta, "content", None)
+ if isinstance(content_delta, str) and content_delta:
+ content_parts.append(content_delta)
+
+ tool_calls = getattr(delta, "tool_calls", None)
+ if not tool_calls:
+ continue
+
+ for tool_call in tool_calls:
+ tool_call_id = self._get_tool_call_id(tool_call)
+ if tool_call_id:
+ tool_call_ids.add(tool_call_id)
+
+ @staticmethod
+ def _is_stream_response_complete(chunk: ChatCompletionChunk) -> bool:
+ r"""Return whether a streaming chunk completes one response."""
+ return any(
+ getattr(choice, "finish_reason", None)
+ for choice in getattr(chunk, "choices", []) or []
+ )
+
+ def _cache_collected_stream_reasoning(
+ self,
+ reasoning_parts: List[str],
+ content_parts: List[str],
+ tool_call_ids: Set[str],
+ ) -> None:
+ r"""Cache collected streaming reasoning once it is complete."""
+ self._cache_reasoning_content(
+ "".join(reasoning_parts) or None,
+ list(tool_call_ids),
+ "".join(content_parts) or None,
+ )
+
+ def _wrap_stream_reasoning_cache(
+ self, response: Stream[ChatCompletionChunk]
+ ) -> Iterator[ChatCompletionChunk]:
+ r"""Wrap a DeepSeek stream and cache reasoning after consumption."""
+ reasoning_parts: List[str] = []
+ content_parts: List[str] = []
+ tool_call_ids: Set[str] = set()
+ cached = False
+
+ try:
+ for chunk in response:
+ self._collect_stream_reasoning(
+ chunk, reasoning_parts, content_parts, tool_call_ids
+ )
+ if self._is_stream_response_complete(chunk):
+ self._cache_collected_stream_reasoning(
+ reasoning_parts, content_parts, tool_call_ids
+ )
+ cached = True
+ yield chunk
+ finally:
+ if not cached:
+ self._cache_collected_stream_reasoning(
+ reasoning_parts, content_parts, tool_call_ids
+ )
+
+ async def _wrap_async_stream_reasoning_cache(
+ self, response: AsyncStream[ChatCompletionChunk]
+ ) -> AsyncIterator[ChatCompletionChunk]:
+ r"""Wrap a DeepSeek async stream and cache reasoning after use."""
+ reasoning_parts: List[str] = []
+ content_parts: List[str] = []
+ tool_call_ids: Set[str] = set()
+ cached = False
+
+ try:
+ async for chunk in response:
+ self._collect_stream_reasoning(
+ chunk, reasoning_parts, content_parts, tool_call_ids
+ )
+ if self._is_stream_response_complete(chunk):
+ self._cache_collected_stream_reasoning(
+ reasoning_parts, content_parts, tool_call_ids
+ )
+ cached = True
+ yield chunk
+ finally:
+ if not cached:
+ self._cache_collected_stream_reasoning(
+ reasoning_parts, content_parts, tool_call_ids
+ )
+
+ def _inject_tool_call_reasoning(
+ self, messages: List[OpenAIMessage]
+ ) -> List[OpenAIMessage]:
+ r"""Inject cached reasoning into assistant tool-call messages."""
+ session_cache = self._tool_call_reasoning_by_session.get(
+ self._get_reasoning_session_id(), {}
+ )
+ assistant_reasoning_cache = self._assistant_reasoning_by_session.get(
+ self._get_reasoning_session_id(), {}
+ )
+ if not session_cache and not assistant_reasoning_cache:
+ return messages
+
+ processed_messages: List[OpenAIMessage] = []
+ for message in messages:
+ if (
+ isinstance(message, dict)
+ and message.get("role") == "assistant"
+ and message.get("tool_calls")
+ and not message.get("reasoning_content")
+ ):
+ reasoning_content = None
+ tool_calls = message.get("tool_calls") or []
+ if isinstance(tool_calls, list):
+ for tool_call in tool_calls:
+ tool_call_id = self._get_tool_call_id(tool_call)
+ if tool_call_id and tool_call_id in session_cache:
+ reasoning_content = session_cache[tool_call_id]
+ break
+
+ if reasoning_content:
+ message = self._with_reasoning_content(
+ message, reasoning_content
+ )
+ elif (
+ isinstance(message, dict)
+ and message.get("role") == "assistant"
+ and not message.get("reasoning_content")
+ ):
+ content = self._get_message_content(message)
+ if content and content in assistant_reasoning_cache:
+ message = self._with_reasoning_content(
+ message, assistant_reasoning_cache[content]
+ )
+
+ processed_messages.append(message)
+
+ return processed_messages
+
+ def _with_reasoning_content(
+ self, message: OpenAIMessage, reasoning_content: str
+ ) -> OpenAIMessage:
+ r"""Return a copy of an OpenAI message with DeepSeek reasoning."""
+ message_with_reasoning: Dict[str, object] = dict(
+ cast(Mapping[str, object], message)
+ )
+ message_with_reasoning["reasoning_content"] = reasoning_content
+ return cast(OpenAIMessage, message_with_reasoning)
+
+ def preprocess_messages(
+ self, messages: List[OpenAIMessage]
+ ) -> List[OpenAIMessage]:
+ r"""Preprocess messages and restore DeepSeek tool-call reasoning."""
+ messages = super().preprocess_messages(messages)
+ return self._inject_tool_call_reasoning(messages)
+
+ def postprocess_response(self, response: Any) -> Any:
+ r"""Postprocess responses and cache DeepSeek tool-call reasoning."""
+ response = super().postprocess_response(response)
+ if isinstance(response, Stream):
+ return self._wrap_stream_reasoning_cache(response)
+ if isinstance(response, AsyncStream):
+ return self._wrap_async_stream_reasoning_cache(response)
+
+ self._cache_tool_call_reasoning(response)
+ return response
+
+ def _normalize_thinking_config(
+ self, request_config: Dict[str, Any]
+ ) -> Dict[str, Any]:
+ r"""Move top-level ``thinking`` into ``extra_body`` for OpenAI SDK."""
+ thinking = request_config.pop("thinking", None)
+ if thinking is None:
+ return request_config
+
+ extra_body = request_config.get("extra_body") or {}
+ if not isinstance(extra_body, dict):
+ raise ValueError("DeepSeek `extra_body` must be a dictionary.")
+
+ extra_body = copy.deepcopy(extra_body)
+ extra_body["thinking"] = thinking
+ request_config["extra_body"] = extra_body
+ return request_config
+
+ def _is_thinking_mode_enabled(
+ self, request_config: Dict[str, Any]
+ ) -> bool:
+ extra_body = request_config.get("extra_body") or {}
+ thinking = None
+ if isinstance(extra_body, dict):
+ thinking = extra_body.get("thinking")
+
+ if isinstance(thinking, dict):
+ thinking_type = thinking.get("type")
+ if thinking_type == "disabled":
+ return False
+ if thinking_type == "enabled":
+ return True
+
+ return str(self.model_type) in DEEPSEEK_THINKING_MODE_MODELS
def _prepare_request(
self,
@@ -131,31 +453,21 @@ class DeepSeekModel(OpenAICompatibleModel):
response_format: Optional[Type[BaseModel]] = None,
tools: Optional[List[Dict[str, Any]]] = None,
) -> Dict[str, Any]:
- request_config = self.model_config_dict.copy()
-
- if self.model_type in [
- ModelType.DEEPSEEK_REASONER,
- ]:
- logger.warning(
- "Warning: You are using an DeepSeek Reasoner model, "
- "which has certain limitations, reference: "
- "`https://api-docs.deepseek.com/guides/reasoning_model"
- "#api-parameters`.",
- )
- request_config = {
- key: value
- for key, value in request_config.items()
- if key not in REASONSER_UNSUPPORTED_PARAMS
- }
- import copy
-
request_config = copy.deepcopy(self.model_config_dict)
- # Remove strict from each tool's function parameters since DeepSeek
- # does not support them
+ request_config = self._normalize_thinking_config(request_config)
+
+ if self._is_thinking_mode_enabled(request_config):
+ for param in DEEPSEEK_THINKING_MODE_ERROR_PARAMS:
+ if param in request_config:
+ logger.warning(
+ "`%s` is not supported by DeepSeek thinking mode "
+ "and will be ignored.",
+ param,
+ )
+ request_config.pop(param, None)
+
if tools:
- for tool in tools:
- function_dict = tool.get('function', {})
- function_dict.pop("strict", None)
+ tools = copy.deepcopy(tools)
request_config["tools"] = tools
elif response_format:
try_modify_message_with_format(messages[-1], response_format)
@@ -193,6 +505,10 @@ class DeepSeekModel(OpenAICompatibleModel):
model=self.model_type,
**request_config,
)
+ if isinstance(response, Stream):
+ return self._wrap_stream_reasoning_cache( # type: ignore[return-value]
+ response
+ )
return response
@@ -225,5 +541,9 @@ class DeepSeekModel(OpenAICompatibleModel):
model=self.model_type,
**request_config,
)
+ if isinstance(response, AsyncStream):
+ return self._wrap_async_stream_reasoning_cache( # type: ignore[return-value]
+ response
+ )
return response
diff --git a/camel/types/enums.py b/camel/types/enums.py
index 3aabd7084..6e93a346a 100644
--- a/camel/types/enums.py
+++ b/camel/types/enums.py
@@ -334,6 +334,8 @@ class ModelType(UnifiedModelType, Enum):
YI_LARGE_FC = "yi-large-fc"
# DeepSeek models
+ DEEPSEEK_V4_FLASH = "deepseek-v4-flash"
+ DEEPSEEK_V4_PRO = "deepseek-v4-pro"
DEEPSEEK_CHAT = "deepseek-chat"
DEEPSEEK_REASONER = "deepseek-reasoner"
# InternLM models
@@ -1001,6 +1003,8 @@ class ModelType(UnifiedModelType, Enum):
@property
def is_deepseek(self) -> bool:
return self in {
+ ModelType.DEEPSEEK_V4_FLASH,
+ ModelType.DEEPSEEK_V4_PRO,
ModelType.DEEPSEEK_CHAT,
ModelType.DEEPSEEK_REASONER,
}
@@ -1689,6 +1693,11 @@ class ModelType(UnifiedModelType, Enum):
ModelType.CLAUDE_OPUS_4_7,
}:
return 1_000_000
+ elif self in {
+ ModelType.DEEPSEEK_V4_FLASH,
+ ModelType.DEEPSEEK_V4_PRO,
+ }:
+ return 1_000_000
elif self in {
ModelType.QWEN_LONG,
ModelType.TOGETHER_LLAMA_4_SCOUT,
diff --git a/examples/models/deepseek_chat_model_example.py b/examples/models/deepseek_chat_model_example.py
deleted file mode 100644
index 701654e55..000000000
--- a/examples/models/deepseek_chat_model_example.py
+++ /dev/null
@@ -1,111 +0,0 @@
-# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========
-
-from camel.agents import ChatAgent
-from camel.configs import DeepSeekConfig
-from camel.models import ModelFactory
-from camel.types import ModelPlatformType, ModelType
-
-"""
-please set the below os environment:
-export DEEPSEEK_API_KEY=""
-"""
-
-model = ModelFactory.create(
- model_platform=ModelPlatformType.DEEPSEEK,
- model_type=ModelType.DEEPSEEK_CHAT,
- model_config_dict=DeepSeekConfig(temperature=0.2).as_dict(),
-)
-
-# Define system message
-sys_msg = "You are a helpful assistant."
-
-# Set agent
-camel_agent = ChatAgent(system_message=sys_msg, model=model)
-
-user_msg = """How many Rs are there in the word 'strawberry'?"""
-
-# Get response information
-response = camel_agent.step(user_msg)
-print(response.msgs[0].reasoning_content)
-print(response.msgs[0].content)
-
-# ruff: noqa: E501
-'''
-### Step 1: Understanding the Problem
-
-Before jumping into counting, it's essential to understand what's being asked. The question is: **"How many Rs are there in the word 'strawberry'?"** This means I need to look at the word "strawberry" and count how many times the letter 'R' appears in it.
-
-### Step 2: Writing Down the Word
-
-To avoid missing any letters, I'll write down the word clearly:
-
-**S T R A W B E R R Y**
-
-Breaking it down like this helps me visualize each letter individually.
-
-### Step 3: Identifying Each Letter
-
-Now, I'll go through each letter one by one to identify if it's an 'R':
-
-1. **S** - Not an 'R'.
-2. **T** - Not an 'R'.
-3. **R** - This is an 'R'. (First 'R' found)
-4. **A** - Not an 'R'.
-5. **W** - Not an 'R'.
-6. **B** - Not an 'R'.
-7. **E** - Not an 'R'.
-8. **R** - This is an 'R'. (Second 'R' found)
-9. **R** - This is another 'R'. (Third 'R' found)
-10. **Y** - Not an 'R'.
-
-### Step 4: Counting the Rs
-
-From the above identification:
-
-- The first 'R' is the 3rd letter.
-- The second 'R' is the 8th letter.
-- The third 'R' is the 9th letter.
-
-So, there are **three** instances of the letter 'R' in "strawberry."
-
-### Step 5: Double-Checking
-
-To ensure accuracy, I'll recount:
-
-1. **S** - Not 'R'.
-2. **T** - Not 'R'.
-3. **R** - 1st 'R'.
-4. **A** - Not 'R'.
-5. **W** - Not 'R'.
-6. **B** - Not 'R'.
-7. **E** - Not 'R'.
-8. **R** - 2nd 'R'.
-9. **R** - 3rd 'R'.
-10. **Y** - Not 'R'.
-
-Yes, the count remains consistent at three 'R's.
-
-### Step 6: Considering Pronunciation
-
-Sometimes, pronunciation can be misleading. In "strawberry," the 'R's are pronounced, but that doesn't affect the count. Whether silent or pronounced, each 'R' is still a distinct letter in the spelling.
-
-### Step 7: Final Answer
-
-After carefully analyzing and recounting, I conclude that there are **three** 'R's in the word "strawberry."
-
----
-
-**Final Answer:** There are **three** 'R's in the word "strawberry."
-'''
diff --git a/examples/models/deepseek_model_example.py b/examples/models/deepseek_model_example.py
new file mode 100644
index 000000000..b87f03417
--- /dev/null
+++ b/examples/models/deepseek_model_example.py
@@ -0,0 +1,86 @@
+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========
+
+import os
+
+from camel.agents import ChatAgent
+from camel.configs import DeepSeekConfig
+from camel.models import ModelFactory
+from camel.toolkits import TerminalToolkit
+from camel.types import ModelPlatformType, ModelType
+
+"""
+please set the below os environment:
+export DEEPSEEK_API_KEY=""
+"""
+
+base_dir = os.path.dirname(os.path.abspath(__file__))
+workspace_dir = os.path.join(
+ os.path.dirname(os.path.dirname(base_dir)), "workspace"
+)
+
+tools = TerminalToolkit(working_directory=workspace_dir).get_tools()
+
+model = ModelFactory.create(
+ model_platform=ModelPlatformType.DEEPSEEK,
+ model_type=ModelType.DEEPSEEK_V4_PRO,
+ model_config_dict=DeepSeekConfig(
+ reasoning_effort="high",
+ thinking={"type": "enabled"},
+ ).as_dict(),
+)
+
+# Define system message
+sys_msg = (
+ "You are a mission-control system operator. Use the provided terminal "
+ "tools for filesystem and log tasks inside the workspace."
+)
+
+# Set agent
+camel_agent = ChatAgent(system_message=sys_msg, model=model, tools=tools)
+
+
+def print_step_result(step_name: str, response) -> None:
+ r"""Print tool calls and final message for one agent step."""
+ print(f"\n{step_name}")
+ print("=" * len(step_name))
+ print("Tool calls:")
+ print(str(response.info["tool_calls"])[:1000])
+
+ if response.msgs:
+ message = response.msgs[0]
+ if message.reasoning_content:
+ print("\nReasoning content:")
+ print(message.reasoning_content[:1000])
+ print("\nFinal answer:")
+ print(message.content)
+
+
+# Round 1: the model should call terminal tools and return a final answer.
+user_msg = (
+ f"Create a 'mission_control' directory in '{workspace_dir}', write "
+ "'probe=voyager-x status=nominal battery=84' into telemetry.txt inside "
+ "that directory, then list the directory contents. Use the terminal "
+ "tools."
+)
+response = camel_agent.step(user_msg)
+print_step_result("Round 1", response)
+
+# Round 2: keep the same agent memory.
+user_msg = (
+ "Using the directory you just created, append 'relay=online' to "
+ "telemetry.txt and show the full file content. Use the terminal tools."
+)
+response = camel_agent.step(user_msg)
+print_step_result("Round 2", response)
diff --git a/test/models/test_deepseek_model.py b/test/models/test_deepseek_model.py
index 5369d3564..b495b934e 100644
--- a/test/models/test_deepseek_model.py
+++ b/test/models/test_deepseek_model.py
@@ -13,11 +13,29 @@
# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========
+from typing import Literal
+
import pytest
+from openai.types.chat.chat_completion import Choice
+from openai.types.chat.chat_completion_chunk import (
+ ChatCompletionChunk,
+ ChoiceDelta,
+ ChoiceDeltaToolCall,
+ ChoiceDeltaToolCallFunction,
+)
+from openai.types.chat.chat_completion_chunk import (
+ Choice as ChunkChoice,
+)
+from openai.types.chat.chat_completion_message import ChatCompletionMessage
+from openai.types.chat.chat_completion_message_function_tool_call import (
+ ChatCompletionMessageFunctionToolCall,
+ Function,
+)
+from openai.types.completion_usage import CompletionUsage
from camel.configs import DeepSeekConfig
from camel.models import DeepSeekModel, ModelFactory
-from camel.types import ModelPlatformType, ModelType
+from camel.types import ChatCompletion, ModelPlatformType, ModelType
from camel.utils import OpenAITokenCounter
@@ -25,13 +43,15 @@ from camel.utils import OpenAITokenCounter
@pytest.mark.parametrize(
"model_type",
[
+ ModelType.DEEPSEEK_V4_FLASH,
+ ModelType.DEEPSEEK_V4_PRO,
ModelType.DEEPSEEK_CHAT,
ModelType.DEEPSEEK_REASONER,
],
)
def test_deepseek_model(model_type):
model_config_dict = DeepSeekConfig().as_dict()
- model = DeepSeekModel(model_type, model_config_dict)
+ model = DeepSeekModel(model_type, model_config_dict, api_key="test")
assert model.model_type == model_type
assert model.model_config_dict == model_config_dict
assert isinstance(model.token_counter, OpenAITokenCounter)
@@ -43,6 +63,8 @@ def test_deepseek_model(model_type):
@pytest.mark.parametrize(
"model_type",
[
+ ModelType.DEEPSEEK_V4_FLASH,
+ ModelType.DEEPSEEK_V4_PRO,
ModelType.DEEPSEEK_CHAT,
ModelType.DEEPSEEK_REASONER,
],
@@ -52,5 +74,379 @@ def test_deepseek_model_create(model_type: ModelType):
model_platform=ModelPlatformType.DEEPSEEK,
model_type=model_type,
model_config_dict=DeepSeekConfig(temperature=1.3).as_dict(),
+ api_key="test",
)
assert model.model_type == model_type
+
+
+def test_deepseek_v4_model_types():
+ assert ModelType.DEEPSEEK_V4_FLASH.is_deepseek
+ assert ModelType.DEEPSEEK_V4_PRO.is_deepseek
+ assert ModelType.DEEPSEEK_V4_FLASH.token_limit == 1_000_000
+ assert ModelType.DEEPSEEK_V4_PRO.token_limit == 1_000_000
+
+
+def test_deepseek_config_supports_thinking_options():
+ config = DeepSeekConfig(
+ reasoning_effort="high",
+ thinking={"type": "enabled"},
+ extra_body={"custom": True},
+ ).as_dict()
+
+ assert config["reasoning_effort"] == "high"
+ assert config["thinking"] == {"type": "enabled"}
+ assert config["extra_body"] == {"custom": True}
+
+
+def test_deepseek_prepare_request_moves_thinking_to_extra_body():
+ model = DeepSeekModel(
+ ModelType.DEEPSEEK_V4_PRO,
+ DeepSeekConfig(
+ thinking={"type": "disabled"},
+ reasoning_effort="high",
+ ).as_dict(),
+ api_key="test",
+ )
+ tools = [
+ {
+ "type": "function",
+ "function": {
+ "name": "get_date",
+ "parameters": {"type": "object", "properties": {}},
+ "strict": True,
+ },
+ }
+ ]
+
+ request_config = model._prepare_request(
+ messages=[{"role": "user", "content": "hello"}],
+ tools=tools,
+ )
+
+ assert "thinking" not in request_config
+ assert request_config["extra_body"]["thinking"] == {"type": "disabled"}
+ assert request_config["reasoning_effort"] == "high"
+ assert request_config["tools"][0]["function"]["strict"] is True
+ assert tools[0]["function"]["strict"] is True
+
+
+def _make_chat_completion(
+ message: ChatCompletionMessage,
+ finish_reason: Literal[
+ "stop", "length", "tool_calls", "content_filter", "function_call"
+ ],
+) -> ChatCompletion:
+ return ChatCompletion(
+ id="mock_response_id",
+ choices=[
+ Choice(
+ finish_reason=finish_reason,
+ index=0,
+ logprobs=None,
+ message=message,
+ )
+ ],
+ created=123456789,
+ model="deepseek-v4-pro",
+ object="chat.completion",
+ usage=CompletionUsage(
+ completion_tokens=10,
+ prompt_tokens=20,
+ total_tokens=30,
+ ),
+ )
+
+
+def _make_chat_completion_chunk(
+ delta: ChoiceDelta,
+ finish_reason: Literal[
+ "stop", "length", "tool_calls", "content_filter", "function_call"
+ ]
+ | None = None,
+) -> ChatCompletionChunk:
+ return ChatCompletionChunk(
+ id="mock_chunk_id",
+ choices=[
+ ChunkChoice(
+ delta=delta,
+ finish_reason=finish_reason,
+ index=0,
+ logprobs=None,
+ )
+ ],
+ created=123456789,
+ model="deepseek-v4-pro",
+ object="chat.completion.chunk",
+ )
+
+
+def test_deepseek_model_injects_tool_call_reasoning_content():
+ model = DeepSeekModel(
+ ModelType.DEEPSEEK_V4_PRO,
+ DeepSeekConfig().as_dict(),
+ api_key="test",
+ )
+ tool_call = ChatCompletionMessageFunctionToolCall(
+ id="call_123",
+ type="function",
+ function=Function(name="get_date", arguments="{}"),
+ )
+ message = ChatCompletionMessage(
+ content="",
+ role="assistant",
+ function_call=None,
+ tool_calls=[tool_call],
+ )
+ message.reasoning_content = "Need the date before answering."
+
+ model.postprocess_response(_make_chat_completion(message, "tool_calls"))
+ messages = model.preprocess_messages(
+ [
+ {"role": "user", "content": "What is today's date?"},
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": "call_123",
+ "type": "function",
+ "function": {
+ "name": "get_date",
+ "arguments": "{}",
+ },
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_123", "content": "2026"},
+ ]
+ )
+
+ assert messages[1]["reasoning_content"] == (
+ "Need the date before answering."
+ )
+
+
+def test_deepseek_model_run_caches_streaming_tool_call_reasoning(
+ monkeypatch,
+):
+ model = DeepSeekModel(
+ ModelType.DEEPSEEK_V4_PRO,
+ DeepSeekConfig(stream=True).as_dict(),
+ api_key="test",
+ )
+ reasoning_delta = ChoiceDelta(content=None, role="assistant")
+ reasoning_delta.reasoning_content = "Need a streamed tool result."
+ tool_delta = ChoiceDelta(
+ content=None,
+ tool_calls=[
+ ChoiceDeltaToolCall(
+ index=0,
+ id="call_stream_run_123",
+ type="function",
+ function=ChoiceDeltaToolCallFunction(
+ name="get_date", arguments="{}"
+ ),
+ )
+ ],
+ )
+ chunks = [
+ _make_chat_completion_chunk(reasoning_delta),
+ _make_chat_completion_chunk(tool_delta, finish_reason="tool_calls"),
+ ]
+
+ class FakeStream:
+ def __iter__(self):
+ return iter(chunks)
+
+ monkeypatch.setattr("camel.models.deepseek_model.Stream", FakeStream)
+
+ def fake_call_client(call, *args, **kwargs):
+ return FakeStream()
+
+ monkeypatch.setattr(model, "_call_client", fake_call_client)
+
+ response = model.run(messages=[{"role": "user", "content": "hello"}])
+ response_iter = iter(response)
+ next(response_iter)
+ next(response_iter)
+
+ messages = model.preprocess_messages(
+ [
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": "call_stream_run_123",
+ "type": "function",
+ "function": {
+ "name": "get_date",
+ "arguments": "{}",
+ },
+ }
+ ],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "call_stream_run_123",
+ "content": "2026",
+ },
+ ]
+ )
+
+ assert messages[0]["reasoning_content"] == "Need a streamed tool result."
+
+
+def test_deepseek_model_injects_final_reasoning_after_tool_turn():
+ model = DeepSeekModel(
+ ModelType.DEEPSEEK_V4_PRO,
+ DeepSeekConfig().as_dict(),
+ api_key="test",
+ )
+ tool_call = ChatCompletionMessageFunctionToolCall(
+ id="call_123",
+ type="function",
+ function=Function(name="get_date", arguments="{}"),
+ )
+ tool_message = ChatCompletionMessage(
+ content="",
+ role="assistant",
+ function_call=None,
+ tool_calls=[tool_call],
+ )
+ tool_message.reasoning_content = "Need the date before answering."
+ model.postprocess_response(
+ _make_chat_completion(tool_message, "tool_calls")
+ )
+
+ final_message = ChatCompletionMessage(
+ content="I created the logs directory.",
+ role="assistant",
+ function_call=None,
+ tool_calls=None,
+ )
+ final_message.reasoning_content = "The tool succeeded, so I can answer."
+ model.postprocess_response(_make_chat_completion(final_message, "stop"))
+
+ messages = model.preprocess_messages(
+ [
+ {"role": "user", "content": "Create logs"},
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": "call_123",
+ "type": "function",
+ "function": {
+ "name": "get_date",
+ "arguments": "{}",
+ },
+ }
+ ],
+ },
+ {"role": "tool", "tool_call_id": "call_123", "content": "ok"},
+ {
+ "role": "assistant",
+ "content": "I created the logs directory.",
+ },
+ {"role": "user", "content": "Create app.log"},
+ ]
+ )
+
+ assert messages[1]["reasoning_content"] == (
+ "Need the date before answering."
+ )
+ assert messages[3]["reasoning_content"] == (
+ "The tool succeeded, so I can answer."
+ )
+
+
+def test_deepseek_chat_agent_preserves_reasoning_across_steps(monkeypatch):
+ from camel.agents import ChatAgent
+ from camel.toolkits import FunctionTool
+
+ def get_date() -> str:
+ r"""Get the current date."""
+ return "2026-04-24"
+
+ model = DeepSeekModel(
+ ModelType.DEEPSEEK_V4_PRO,
+ DeepSeekConfig().as_dict(),
+ api_key="test",
+ )
+
+ tool_call = ChatCompletionMessageFunctionToolCall(
+ id="call_123",
+ type="function",
+ function=Function(name="get_date", arguments="{}"),
+ )
+ tool_message = ChatCompletionMessage(
+ content="",
+ role="assistant",
+ function_call=None,
+ tool_calls=[tool_call],
+ )
+ tool_message.reasoning_content = "Need a tool result."
+
+ final_message = ChatCompletionMessage(
+ content="The date is 2026-04-24.",
+ role="assistant",
+ function_call=None,
+ tool_calls=None,
+ )
+ final_message.reasoning_content = "The tool returned the date."
+
+ second_turn_message = ChatCompletionMessage(
+ content="The log file has been created.",
+ role="assistant",
+ function_call=None,
+ tool_calls=None,
+ )
+ second_turn_message.reasoning_content = "Use prior context and answer."
+
+ responses = [
+ _make_chat_completion(tool_message, "tool_calls"),
+ _make_chat_completion(final_message, "stop"),
+ _make_chat_completion(second_turn_message, "stop"),
+ ]
+ captured_messages = []
+
+ def fake_call_client(call, *args, **kwargs):
+ captured_messages.append(kwargs["messages"])
+ return responses.pop(0)
+
+ monkeypatch.setattr(model, "_call_client", fake_call_client)
+
+ agent = ChatAgent(
+ system_message="You can use tools.",
+ model=model,
+ tools=[FunctionTool(get_date)],
+ )
+
+ agent.step("What is today's date?")
+ agent.step("Create a log file for that date.")
+
+ second_step_messages = captured_messages[2]
+ assistant_tool_message = next(
+ message
+ for message in second_step_messages
+ if (
+ message["role"] == "assistant"
+ and message.get("tool_calls")
+ and message["tool_calls"][0]["id"] == "call_123"
+ )
+ )
+ assistant_final_message = next(
+ message
+ for message in second_step_messages
+ if (
+ message["role"] == "assistant"
+ and message.get("content") == "The date is 2026-04-24."
+ )
+ )
+
+ assert assistant_tool_message["reasoning_content"] == "Need a tool result."
+ assert assistant_final_message["reasoning_content"] == (
+ "The tool returned the date."
+ )