š« CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
feat: Interleaved thinking for kimi k2 and glm (#3737)
Xiangyu Shib89344935e03
diff --git a/camel/configs/__init__.py b/camel/configs/__init__.pyindex a9547754c..ceaf77520 100644--- a/camel/configs/__init__.py+++ b/camel/configs/__init__.py@@ -57,6 +57,7 @@ from .sglang_config import SGLANG_API_PARAMS, SGLangConfigfrom .siliconflow_config import SILICONFLOW_API_PARAMS, SiliconFlowConfigfrom .togetherai_config import TOGETHERAI_API_PARAMS, TogetherAIConfigfrom .vllm_config import VLLM_API_PARAMS, VLLMConfig+from .volcano_config import VOLCANO_API_PARAMS, VolcanoConfigfrom .watsonx_config import WATSONX_API_PARAMS, WatsonXConfigfrom .yi_config import YI_API_PARAMS, YiConfigfrom .zhipuai_config import ZHIPUAI_API_PARAMS, ZhipuAIConfig@@ -145,4 +146,6 @@ __all__ = ['CRYNUX_API_PARAMS','FunctionGemmaConfig','FUNCTION_GEMMA_API_PARAMS',+ 'VolcanoConfig',+ 'VOLCANO_API_PARAMS',]diff --git a/camel/configs/minimax_config.py b/camel/configs/minimax_config.pyindex 84594ae3a..885749e5e 100644--- a/camel/configs/minimax_config.py+++ b/camel/configs/minimax_config.py@@ -73,6 +73,12 @@ class MinimaxConfig(BaseConfig):forces the model to call that tool. :obj:`"none"` is the defaultwhen no tools are present. :obj:`"auto"` is the default if toolsare present.+ interleaved_thinking (Optional[bool], optional): Whether to enable+ interleaved thinking mode. When enabled, the model performs+ step-by-step reasoning while dynamically invoking tools. This sets+ `reasoning_split=True` in the API request, which separates+ reasoning into a `reasoning_details`+ field. (default: :obj:`None`)Note:Some OpenAI parameters such as presence_penalty, frequency_penalty,@@ -90,6 +96,7 @@ class MinimaxConfig(BaseConfig):tool_choice: Optional[Union[Dict[str, Union[str, Dict[str, str]]], str]] = None+ interleaved_thinking: Optional[bool] = NoneMINIMAX_API_PARAMS = {param for param in MinimaxConfig.model_fields.keys()}diff --git a/camel/configs/moonshot_config.py b/camel/configs/moonshot_config.pyindex eed43a599..e6b379984 100644--- a/camel/configs/moonshot_config.py+++ b/camel/configs/moonshot_config.py@@ -47,6 +47,10 @@ class MoonshotConfig(BaseConfig):stop (Optional[Union[str, List[str]]], optional): Up to 4 sequenceswhere the API will stop generating further tokens.(default: :obj:`None`)+ interleaved_thinking (Optional[bool], optional): Whether to enable+ interleaved thinking mode. When enabled, the model performs+ step-by-step reasoning while dynamically invoking tools.+ (default: :obj:`None`)"""temperature: Optional[float] = None@@ -58,6 +62,7 @@ class MoonshotConfig(BaseConfig):presence_penalty: Optional[float] = Nonefrequency_penalty: Optional[float] = Nonestop: Optional[Union[str, List[str]]] = None+ interleaved_thinking: Optional[bool] = NoneMOONSHOT_API_PARAMS = {param for param in MoonshotConfig.model_fields.keys()}diff --git a/camel/configs/volcano_config.py b/camel/configs/volcano_config.pynew file mode 100644index 000000000..c10bf587e--- /dev/null+++ b/camel/configs/volcano_config.py@@ -0,0 +1,45 @@+# ========= 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 typing import Optional++from camel.configs.base_config import BaseConfig+++class VolcanoConfig(BaseConfig):+ r"""Defines the parameters for generating chat completions using the+ Volcano Engine API.++ Args:+ temperature (Optional[float], optional): Sampling temperature to use.+ (default: :obj:`None`)+ max_tokens (Optional[int], optional): The maximum number of tokens to+ generate in the chat completion.+ (default: :obj:`None`)+ stream (Optional[bool], optional): Whether to stream the response.+ (default: :obj:`None`)+ interleaved_thinking (Optional[bool], optional): Whether to enable+ interleaved thinking mode for doubao-seed models. When enabled,+ the model performs step-by-step reasoning while dynamically+ invoking tools.+ (default: :obj:`None`)+ """++ temperature: Optional[float] = None+ max_tokens: Optional[int] = None+ stream: Optional[bool] = None+ interleaved_thinking: Optional[bool] = None+++VOLCANO_API_PARAMS = {param for param in VolcanoConfig.model_fields.keys()}diff --git a/camel/configs/zhipuai_config.py b/camel/configs/zhipuai_config.pyindex 046983026..9dd7a7076 100644--- a/camel/configs/zhipuai_config.py+++ b/camel/configs/zhipuai_config.py@@ -57,6 +57,10 @@ class ZhipuAIConfig(BaseConfig):forces the model to call that tool. :obj:`"none"` is the defaultwhen no tools are present. :obj:`"auto"` is the default if toolsare present.+ interleaved_thinking (Optional[bool], optional): Whether to enable+ interleaved thinking mode for GLM-4.5+ models. When enabled, the+ model reasons before each response and tool call.+ (default: :obj:`None`)"""temperature: Optional[float] = None@@ -67,6 +71,7 @@ class ZhipuAIConfig(BaseConfig):tool_choice: Optional[Union[Dict[str, Union[str, Dict[str, str]]], str]] = None+ interleaved_thinking: Optional[bool] = NoneZHIPUAI_API_PARAMS = {param for param in ZhipuAIConfig.model_fields.keys()}diff --git a/camel/models/_interleaved_thinking_mixin.py b/camel/models/_interleaved_thinking_mixin.pynew file mode 100644index 000000000..aaa5e94f9--- /dev/null+++ b/camel/models/_interleaved_thinking_mixin.py@@ -0,0 +1,210 @@+# ========= 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 typing import Any, Dict, List, Optional, Type, Union++from openai import AsyncStream, Stream+from pydantic import BaseModel++from camel.logger import get_logger+from camel.messages import OpenAIMessage+from camel.types import ChatCompletion, ChatCompletionChunk++logger = get_logger(__name__)+++class InterleavedThinkingMixin:+ r"""Mixin class for models that support interleaved thinking.++ This mixin provides shared functionality for handling reasoning content+ in multi-turn conversations with tool calls. Models like ZhipuAI,+ Moonshot, Minimax, and Volcano require the reasoning content from a+ model response to be passed back in subsequent requests for proper+ context management.++ Class attributes:+ _reasoning_field (str): The field name used for reasoning content.+ Defaults to "reasoning_content". Subclasses can override this+ (e.g., Minimax uses "reasoning_details").++ Instance attributes:+ _last_reasoning (Optional[Any]): Stores the reasoning content from+ the last model response to be injected into the next request.+ """++ # Field name for reasoning content - subclasses can override+ _reasoning_field: str = "reasoning_content"++ # Type hints for attributes that should exist on the model class+ model_config_dict: Dict[str, Any]++ def _init_thinking_state(self) -> None:+ r"""Initialize the thinking state.++ Should be called in the subclass's __init__ method after+ super().__init__().+ """+ self._last_reasoning: Optional[Any] = None++ def _is_thinking_enabled(self) -> bool:+ r"""Check if interleaved thinking mode is enabled.++ Returns:+ bool: True if interleaved_thinking is enabled in the model config.+ """+ return bool(self.model_config_dict.get("interleaved_thinking", False))++ def _extract_reasoning(self, response: ChatCompletion) -> Optional[Any]:+ r"""Extract reasoning content from the model response.++ Args:+ response: The model response.++ Returns:+ The reasoning content if available, None otherwise.+ """+ if response.choices:+ return getattr(+ response.choices[0].message, self._reasoning_field, None+ )+ return None++ def _inject_reasoning(+ self,+ messages: List[OpenAIMessage],+ ) -> List[OpenAIMessage]:+ r"""Inject the last reasoning content into assistant messages.++ For models with interleaved thinking enabled, the reasoning content+ from the model response needs to be passed back in subsequent requests+ for proper context management. This is especially important when using+ tools with interleaved thinking.++ Args:+ messages: The original messages list.++ Returns:+ Messages with reasoning content added to the last assistant+ message that has tool_calls.+ """+ if not self._last_reasoning or not self._is_thinking_enabled():+ return messages++ # Find the last assistant message with tool_calls and inject+ # reasoning content+ processed: List[OpenAIMessage] = []+ reasoning_injected = False++ for msg in reversed(messages):+ if (+ not reasoning_injected+ and isinstance(msg, dict)+ and msg.get("role") == "assistant"+ and msg.get("tool_calls")+ and self._reasoning_field not in msg+ ):+ # Inject reasoning content into this message+ new_msg = dict(msg)+ new_msg[self._reasoning_field] = self._last_reasoning+ processed.append(new_msg) # type: ignore[arg-type]+ reasoning_injected = True+ else:+ processed.append(msg)++ # Only clear after successful injection+ if reasoning_injected:+ self._last_reasoning = None++ return list(reversed(processed))++ def _prepare_thinking_config(+ self,+ config: Dict[str, Any],+ ) -> Dict[str, Any]:+ r"""Prepare the request config for thinking-enabled requests.++ Removes the interleaved_thinking parameter which is only used+ internally. Subclasses can override this to add model-specific+ configuration (e.g., Minimax adds reasoning_split=True).++ Args:+ config: The request configuration dictionary.++ Returns:+ The modified configuration dictionary.+ """+ config.pop("interleaved_thinking", None)+ return config++ def run(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Union[ChatCompletion, Stream[ChatCompletionChunk]]:+ r"""Run inference with interleaved thinking support.++ Note:+ Interleaved thinking is not supported with stream=True. When+ streaming is enabled, reasoning content cannot be captured and+ injected into subsequent requests.+ """+ if self._is_thinking_enabled() and self.model_config_dict.get(+ "stream", False+ ):+ logger.warning(+ "Interleaved thinking is not supported with stream=True. "+ "Reasoning content cannot be captured or injected into "+ "subsequent requests."+ )+ processed_messages = self._inject_reasoning(messages)+ response = super().run( # type: ignore[misc]+ processed_messages, response_format, tools+ )++ if isinstance(response, ChatCompletion):+ self._last_reasoning = self._extract_reasoning(response)++ return response++ async def arun(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:+ r"""Run async inference with interleaved thinking support.++ Note:+ Interleaved thinking is not supported with stream=True. When+ streaming is enabled, reasoning content cannot be captured and+ injected into subsequent requests.+ """+ if self._is_thinking_enabled() and self.model_config_dict.get(+ "stream", False+ ):+ logger.warning(+ "Interleaved thinking is not supported with stream=True. "+ "Reasoning content cannot be captured or injected into "+ "subsequent requests."+ )+ processed_messages = self._inject_reasoning(messages)+ response = await super().arun( # type: ignore[misc]+ processed_messages, response_format, tools+ )++ if isinstance(response, ChatCompletion):+ self._last_reasoning = self._extract_reasoning(response)++ return responsediff --git a/camel/models/minimax_model.py b/camel/models/minimax_model.pyindex c27a4ba30..d1c19bf67 100644--- a/camel/models/minimax_model.py+++ b/camel/models/minimax_model.py@@ -12,9 +12,10 @@# limitations under the License.# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========import os-from typing import Any, Dict, Optional, Union+from typing import Any, Dict, List, Optional, Unionfrom camel.configs import MinimaxConfig+from camel.models._interleaved_thinking_mixin import InterleavedThinkingMixinfrom camel.models.openai_compatible_model import OpenAICompatibleModelfrom camel.types import ModelTypefrom camel.utils import (@@ -23,7 +24,7 @@ from camel.utils import ()-class MinimaxModel(OpenAICompatibleModel):+class MinimaxModel(InterleavedThinkingMixin, OpenAICompatibleModel):r"""LLM API served by Minimax in a unified OpenAICompatibleModelinterface.@@ -52,6 +53,9 @@ class MinimaxModel(OpenAICompatibleModel):initialization."""+ # Minimax uses "reasoning_details" instead of "reasoning_content"+ _reasoning_field = "reasoning_details"+@api_keys_required([("api_key", "MINIMAX_API_KEY")])def __init__(self,@@ -81,3 +85,44 @@ class MinimaxModel(OpenAICompatibleModel):max_retries=max_retries,**kwargs,)+ # Initialize interleaved thinking state+ self._init_thinking_state()++ def _prepare_thinking_config(+ self,+ config: Dict[str, Any],+ ) -> Dict[str, Any]:+ r"""Prepare the request config for thinking-enabled requests.++ Overrides base method to add reasoning_split=True to extra_body+ when interleaved thinking is enabled.++ Args:+ config: The request configuration dictionary.++ Returns:+ The modified configuration dictionary.+ """+ config = super()._prepare_thinking_config(config)++ # Add reasoning_split to extra_body when interleaved thinking is+ # enabled+ if self._is_thinking_enabled():+ extra_body = config.get("extra_body", {})+ extra_body["reasoning_split"] = True+ config["extra_body"] = extra_body++ return config++ def _prepare_request_config(+ self,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Dict[str, Any]:+ r"""Prepare the request configuration dictionary.++ Overrides the base method to:+ 1. Remove interleaved_thinking parameter (internal use only)+ 2. Add reasoning_split=True to extra_body when thinking is enabled+ """+ request_config = super()._prepare_request_config(tools)+ return self._prepare_thinking_config(request_config)diff --git a/camel/models/moonshot_model.py b/camel/models/moonshot_model.pyindex 09d053722..85d7eb649 100644--- a/camel/models/moonshot_model.py+++ b/camel/models/moonshot_model.py@@ -16,12 +16,13 @@ import copyimport osfrom typing import Any, Dict, List, Optional, Type, Union-from openai import AsyncStream+from openai import AsyncStream, Streamfrom pydantic import BaseModelfrom camel.configs import MoonshotConfigfrom camel.logger import get_loggerfrom camel.messages import OpenAIMessage+from camel.models._interleaved_thinking_mixin import InterleavedThinkingMixinfrom camel.models._utils import try_modify_message_with_formatfrom camel.models.openai_compatible_model import OpenAICompatibleModelfrom camel.types import (@@ -50,7 +51,7 @@ else:from camel.utils import observe-class MoonshotModel(OpenAICompatibleModel):+class MoonshotModel(InterleavedThinkingMixin, OpenAICompatibleModel):r"""Moonshot API in a unified OpenAICompatibleModel interface.Args:@@ -112,6 +113,8 @@ class MoonshotModel(OpenAICompatibleModel):max_retries=max_retries,**kwargs,)+ # Initialize interleaved thinking state+ self._init_thinking_state()def _prepare_request(self,@@ -134,6 +137,9 @@ class MoonshotModel(OpenAICompatibleModel):"""request_config = copy.deepcopy(self.model_config_dict)+ # Remove internal config params that are not part of the API+ request_config.pop("interleaved_thinking", None)+if tools:# Clean tools to remove null types (Moonshot API incompatibility)cleaned_tools = self._clean_tool_schemas(tools)@@ -233,6 +239,40 @@ class MoonshotModel(OpenAICompatibleModel):return cleaned_tools+ @observe()+ def _run(+ self,+ messages: List[OpenAIMessage],+ response_format: Optional[Type[BaseModel]] = None,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Union[ChatCompletion, Stream[ChatCompletionChunk]]:+ r"""Runs inference of Moonshot chat completion.++ Args:+ messages (List[OpenAIMessage]): Message list with the chat history+ in OpenAI API format.+ response_format (Optional[Type[BaseModel]]): The format of the+ response.+ tools (Optional[List[Dict[str, Any]]]): The schema of the tools to+ use for the request.++ Returns:+ Union[ChatCompletion, Stream[ChatCompletionChunk]]:+ `ChatCompletion` in the non-stream mode, or+ `Stream[ChatCompletionChunk]` in the stream mode.+ """+ self._log_and_trace()++ request_config = self._prepare_request(+ messages, response_format, tools+ )++ return self._client.chat.completions.create(+ messages=messages,+ model=self.model_type,+ **request_config,+ )+@observe()async def _arun(self,diff --git a/camel/models/volcano_model.py b/camel/models/volcano_model.pyindex 2c77da46c..6b6898583 100644--- a/camel/models/volcano_model.py+++ b/camel/models/volcano_model.py@@ -13,21 +13,18 @@# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========import os-from typing import Any, Dict, List, Optional, Type, Union+from typing import Any, Dict, List, Optional, Union-from openai import AsyncStream, Stream-from pydantic import BaseModel--from camel.messages import OpenAIMessage+from camel.models._interleaved_thinking_mixin import InterleavedThinkingMixinfrom camel.models.openai_compatible_model import OpenAICompatibleModel-from camel.types import ChatCompletion, ChatCompletionChunk, ModelType+from camel.types import ModelTypefrom camel.utils import (BaseTokenCounter,api_keys_required,)-class VolcanoModel(OpenAICompatibleModel):+class VolcanoModel(InterleavedThinkingMixin, OpenAICompatibleModel):r"""Volcano Engine API in a unified OpenAICompatibleModel interface.Args:@@ -89,142 +86,17 @@ class VolcanoModel(OpenAICompatibleModel):max_retries,**kwargs,)- # Store the last reasoning_content from model response- # This will be injected into the next request's assistant message- self._last_reasoning_content: Optional[str] = None-- def _inject_reasoning_content(- self,- messages: List[OpenAIMessage],- ) -> List[OpenAIMessage]:- r"""Inject the last reasoning_content into assistant messages.-- For Volcano Engine's doubao-seed models with deep thinking enabled,- the reasoning_content from the model response needs to be passed back- in subsequent requests for proper context management.-- Args:- messages: The original messages list.-- Returns:- Messages with reasoning_content added to the last assistant- message that has tool_calls.- """- if not self._last_reasoning_content:- return messages-- # Find the last assistant message with tool_calls and inject- # reasoning_content- processed: List[OpenAIMessage] = []- reasoning_injected = False+ # Initialize interleaved thinking state+ self._init_thinking_state()- for msg in reversed(messages):- if (- not reasoning_injected- and isinstance(msg, dict)- and msg.get("role") == "assistant"- and msg.get("tool_calls")- and "reasoning_content" not in msg- ):- # Inject reasoning_content into this message- new_msg = dict(msg)- new_msg["reasoning_content"] = self._last_reasoning_content- processed.append(new_msg) # type: ignore[arg-type]- reasoning_injected = True- else:- processed.append(msg)-- # Only clear after successful injection- if reasoning_injected:- self._last_reasoning_content = None-- return list(reversed(processed))-- def _extract_reasoning_content(- self, response: ChatCompletion- ) -> Optional[str]:- r"""Extract reasoning_content from the model response.-- Args:- response: The model response.-- Returns:- The reasoning_content if available, None otherwise.- """- if response.choices:- return getattr(- response.choices[0].message, "reasoning_content", None- )- return None-- def run(+ def _prepare_request_config(self,- messages: List[OpenAIMessage],- response_format: Optional[Type[BaseModel]] = None,tools: Optional[List[Dict[str, Any]]] = None,- ) -> Union[ChatCompletion, Stream[ChatCompletionChunk]]:- r"""Runs inference of Volcano Engine chat completion.-- Overrides the base run method to inject reasoning_content from- previous responses into subsequent requests, as required by- Volcano Engine's doubao-seed models with deep thinking enabled.+ ) -> Dict[str, Any]:+ r"""Prepare the request configuration dictionary.- Args:- messages: Message list with the chat history in OpenAI API format.- response_format: The format of the response.- tools: The schema of the tools to use for the request.-- Returns:- ChatCompletion in the non-stream mode, or- Stream[ChatCompletionChunk] in the stream mode.+ Overrides the base method to remove interleaved_thinking parameter+ which is only used internally."""- # Inject reasoning_content from previous response- processed_messages = self._inject_reasoning_content(messages)-- # Call parent's run- response = super().run(processed_messages, response_format, tools)-- # Extract and store reasoning_content for next request- if isinstance(response, ChatCompletion):- self._last_reasoning_content = self._extract_reasoning_content(- response- )-- return response-- async def arun(- self,- messages: List[OpenAIMessage],- response_format: Optional[Type[BaseModel]] = None,- tools: Optional[List[Dict[str, Any]]] = None,- ) -> Union[ChatCompletion, AsyncStream[ChatCompletionChunk]]:- r"""Runs async inference of Volcano Engine chat completion.-- Overrides the base arun method to inject reasoning_content from- previous responses into subsequent requests, as required by- Volcano Engine's doubao-seed models with deep thinking enabled.-- Args:- messages: Message list with the chat history in OpenAI API format.- response_format: The format of the response.- tools: The schema of the tools to use for the request.-- Returns:- ChatCompletion in the non-stream mode, or- AsyncStream[ChatCompletionChunk] in the stream mode.- """- # Inject reasoning_content from previous response- processed_messages = self._inject_reasoning_content(messages)-- # Call parent's arun- response = await super().arun(- processed_messages, response_format, tools- )-- # Extract and store reasoning_content for next request- if isinstance(response, ChatCompletion):- self._last_reasoning_content = self._extract_reasoning_content(- response- )-- return response+ request_config = super()._prepare_request_config(tools)+ return self._prepare_thinking_config(request_config)diff --git a/camel/models/zhipuai_model.py b/camel/models/zhipuai_model.pyindex e3015e942..e7b5667c6 100644--- a/camel/models/zhipuai_model.py+++ b/camel/models/zhipuai_model.py@@ -20,12 +20,10 @@ from pydantic import BaseModelfrom camel.configs import ZhipuAIConfigfrom camel.logger import get_loggerfrom camel.messages import OpenAIMessage+from camel.models._interleaved_thinking_mixin import InterleavedThinkingMixinfrom camel.models._utils import try_modify_message_with_formatfrom camel.models.openai_compatible_model import OpenAICompatibleModel-from camel.types import (- ChatCompletion,- ModelType,-)+from camel.types import ChatCompletion, ModelTypefrom camel.utils import (BaseTokenCounter,api_keys_required,@@ -34,7 +32,7 @@ from camel.utils import (logger = get_logger(__name__)-class ZhipuAIModel(OpenAICompatibleModel):+class ZhipuAIModel(InterleavedThinkingMixin, OpenAICompatibleModel):r"""ZhipuAI API in a unified OpenAICompatibleModel interface.Args:@@ -95,6 +93,20 @@ class ZhipuAIModel(OpenAICompatibleModel):max_retries=max_retries,**kwargs,)+ # Initialize interleaved thinking state+ self._init_thinking_state()++ def _prepare_request_config(+ self,+ tools: Optional[List[Dict[str, Any]]] = None,+ ) -> Dict[str, Any]:+ r"""Prepare the request configuration dictionary.++ Overrides the base method to remove interleaved_thinking parameter+ which is only used internally.+ """+ request_config = super()._prepare_request_config(tools)+ return self._prepare_thinking_config(request_config)def _request_parse(self,@@ -106,6 +118,7 @@ class ZhipuAIModel(OpenAICompatibleModel):request_config = copy.deepcopy(self.model_config_dict)request_config.pop("stream", None)+ request_config.pop("interleaved_thinking", None)if tools is not None:request_config["tools"] = tools@@ -131,6 +144,7 @@ class ZhipuAIModel(OpenAICompatibleModel):request_config = copy.deepcopy(self.model_config_dict)request_config.pop("stream", None)+ request_config.pop("interleaved_thinking", None)if tools is not None:request_config["tools"] = toolstry_modify_message_with_format(messages[-1], response_format)diff --git a/camel/types/enums.py b/camel/types/enums.pyindex abf706ae8..964cb1b43 100644--- a/camel/types/enums.py+++ b/camel/types/enums.py@@ -69,12 +69,11 @@ class ModelType(UnifiedModelType, Enum):AMD_GPT4 = "dvue-aoai-001-gpt-4.1"+ # ZhipuAI GLM-4.7 series (latest)GLM_4_7 = "glm-4.7"- GLM_4_7_FLASH = "glm-4.7-flash"GLM_4_7_FLASHX = "glm-4.7-flashx"+ GLM_4_7_FLASH = "glm-4.7-flash"GLM_4_6 = "glm-4.6"- GLM_4_6V = "glm-4.6v"- GLM_4_6V_FLASH = "glm-4.6v-flash"GLM_4 = "glm-4"GLM_4_5_AIR = "glm-4.5-air"GLM_4_5_AIRX = "glm-4.5-airx"@@ -96,6 +95,12 @@ class ModelType(UnifiedModelType, Enum):GLM_ZERO_PREVIEW = "glm-zero-preview"GLM_3_TURBO = "glm-3-turbo"+ # ZhipuAI GLM Vision models (VLM)+ GLM_4_6V = "glm-4.6v"+ GLM_4_6V_FLASHX = "glm-4.6v-flashx"+ GLM_4_5V = "glm-4.5v"+ GLM_4_6V_FLASH = "glm-4.6v-flash"+# Groq platform modelsGROQ_LLAMA_3_1_8B = "llama-3.1-8b-instant"GROQ_LLAMA_3_3_70B = "llama-3.3-70b-versatile"@@ -337,6 +342,9 @@ class ModelType(UnifiedModelType, Enum):MOONSHOT_V1_128K = "moonshot-v1-128k"MOONSHOT_KIMI_K2 = "kimi-k2-0905-Preview"MOONSHOT_KIMI_K2_5 = "kimi-k2.5"+ MOONSHOT_KIMI_K2_TURBO_PREVIEW = "kimi-k2-turbo-preview"+ MOONSHOT_KIMI_K2_THINKING = "kimi-k2-thinking"+ MOONSHOT_KIMI_K2_THINKING_TURBO = "kimi-k2-thinking-turbo"# SiliconFlow models support tool callingSILICONFLOW_DEEPSEEK_V2_5 = "deepseek-ai/DeepSeek-V2.5"@@ -516,7 +524,9 @@ class ModelType(UnifiedModelType, Enum):CRYNUX_NOUS_HERMES_3_LLAMA_3_1_8B = "NousResearch/Hermes-3-Llama-3.1-8B"CRYNUX_NOUS_HERMES_3_LLAMA_3_2_3B = "NousResearch/Hermes-3-Llama-3.2-3B"- # Minimax M2 models+ # Minimax models+ MINIMAX_M2_1 = "MiniMax-M2.1"+ MINIMAX_M2_1_LIGHTNING = "MiniMax-M2.1-lightning"MINIMAX_M2 = "MiniMax-M2"MINIMAX_M2_STABLE = "MiniMax-M2-Stable"@@ -685,10 +695,12 @@ class ModelType(UnifiedModelType, Enum):ModelType.GLM_4_FLASH_250414,ModelType.GLM_ZERO_PREVIEW,ModelType.GLM_4_7,- ModelType.GLM_4_7_FLASH,ModelType.GLM_4_7_FLASHX,+ ModelType.GLM_4_7_FLASH,ModelType.GLM_4_6,ModelType.GLM_4_6V,+ ModelType.GLM_4_6V_FLASHX,+ ModelType.GLM_4_5V,ModelType.GLM_4_6V_FLASH,}@@ -1030,6 +1042,9 @@ class ModelType(UnifiedModelType, Enum):ModelType.MOONSHOT_V1_128K,ModelType.MOONSHOT_KIMI_K2,ModelType.MOONSHOT_KIMI_K2_5,+ ModelType.MOONSHOT_KIMI_K2_TURBO_PREVIEW,+ ModelType.MOONSHOT_KIMI_K2_THINKING,+ ModelType.MOONSHOT_KIMI_K2_THINKING_TURBO,}@property@@ -1189,9 +1204,7 @@ class ModelType(UnifiedModelType, Enum):Returns:int: The maximum token limit for the given model."""- if self is ModelType.GLM_4V:- return 1024- elif self in {+ if self in {ModelType.STUB,ModelType.REKA_CORE,ModelType.REKA_EDGE,@@ -1210,8 +1223,6 @@ class ModelType(UnifiedModelType, Enum):elif self in {ModelType.CEREBRAS_LLAMA_3_1_8B,ModelType.GPT_4,- ModelType.GLM_3_TURBO,- ModelType.GLM_4,ModelType.QWEN_VL_PLUS,ModelType.NVIDIA_LLAMA3_70B,ModelType.TOGETHER_MISTRAL_7B,@@ -1381,6 +1392,7 @@ class ModelType(UnifiedModelType, Enum):ModelType.SILICONFLOW_PRO_DEEPSEEK_R1_DISTILL_QWEN_1_5B,ModelType.GLM_4_1V_THINKING_FLASHX,ModelType.GLM_4_1V_THINKING_FLASH,+ ModelType.GLM_4_5V,}:return 64_000elif self in {@@ -1440,7 +1452,10 @@ class ModelType(UnifiedModelType, Enum):ModelType.GLM_4_5_AIR,ModelType.GLM_4_5_AIRX,ModelType.GLM_4_5_FLASH,+ ModelType.GLM_3_TURBO,+ ModelType.GLM_4,ModelType.GLM_4_6V,+ ModelType.GLM_4_6V_FLASHX,ModelType.GLM_4_6V_FLASH,ModelType.AWS_LLAMA_3_3_70B_INSTRUCT,ModelType.AWS_LLAMA_3_2_90B_INSTRUCT,@@ -1497,8 +1512,8 @@ class ModelType(UnifiedModelType, Enum):ModelType.MODELSCOPE_ERNIE_4_5_VL_28B_A3B_THINKING,ModelType.ERNIE_5_0_THINKING,ModelType.ERNIE_4_5_TURBO_VL,- ModelType.GLM_4_6V,- ModelType.GLM_4_6V_FLASH,+ ModelType.GLM_4_5_AIR,+ ModelType.GLM_4_5_AIRX,}:return 128_000elif self in {@@ -1560,9 +1575,10 @@ class ModelType(UnifiedModelType, Enum):ModelType.O4_MINI,ModelType.O3,ModelType.GLM_4_7,- ModelType.GLM_4_7_FLASH,ModelType.GLM_4_7_FLASHX,+ ModelType.GLM_4_7_FLASH,ModelType.GLM_4_6,+ ModelType.GLM_4_5_FLASH,}:return 200_000elif self in {@@ -1571,6 +1587,9 @@ class ModelType(UnifiedModelType, Enum):ModelType.OPENROUTER_HORIZON_ALPHA,ModelType.MOONSHOT_KIMI_K2,ModelType.MOONSHOT_KIMI_K2_5,+ ModelType.MOONSHOT_KIMI_K2_TURBO_PREVIEW,+ ModelType.MOONSHOT_KIMI_K2_THINKING,+ ModelType.MOONSHOT_KIMI_K2_THINKING_TURBO,}:return 256_000@@ -1622,10 +1641,12 @@ class ModelType(UnifiedModelType, Enum):}:return 10_000_000elif self in {+ ModelType.MINIMAX_M2_1,+ ModelType.MINIMAX_M2_1_LIGHTNING,ModelType.MINIMAX_M2,ModelType.MINIMAX_M2_STABLE,}:- return 32_000+ return 204_800else:logger.warning(diff --git a/docs/key_modules/models.md b/docs/key_modules/models.mdindex f9686ab0b..d356dea2e 100644--- a/docs/key_modules/models.md+++ b/docs/key_modules/models.md@@ -39,7 +39,7 @@ CAMEL supports a wide range of models, including [OpenAIās GPT series](https:/| **OpenAI** | gpt-4.5-preview<br/>gpt-4o, gpt-4o-mini<br/>o1, o1-preview, o1-mini<br/>o3-mini, o3-pro, o3<br/>o4-mini<br/>gpt-4.1, gpt-4.1-mini, gpt-4.1-nano<br/>gpt-5, gpt-5-mini, gpt-5-nano<br/>gpt-4-turbo, gpt-4, gpt-3.5-turbo || **Azure OpenAI** | gpt-4o, gpt-4-turbo<br/>gpt-4, gpt-3.5-turbo || **Mistral AI** | mistral-large-latest, pixtral-12b-2409<br/>ministral-8b-latest, ministral-3b-latest<br/>open-mistral-nemo, codestral-latest<br/>open-mistral-7b, open-mixtral-8x7b<br/>open-mixtral-8x22b, open-codestral-mamba<br/>mistral-small-2506, mistral-medium-2508<br/>magistral-small-1.2, magistral-medium-1.2 |-| **Moonshot** | moonshot-v1-8k<br/>moonshot-v1-32k<br/>moonshot-v1-128k |+| **Moonshot** | kimi-k2-0905-Preview, kimi-k2.5, kimi-k2-turbo-preview<br/>kimi-k2-thinking, kimi-k2-thinking-turbo<br/>moonshot-v1-8k, moonshot-v1-32k, moonshot-v1-128k || **Anthropic** | claude-3-7-sonnet-latest<br/>claude-sonnet-4-5, claude-opus-4-5, claude-haiku-4-5<br/>claude-sonnet-4-20250514, claude-opus-4-20250514, claude-opus-4-1-20250805 || **Gemini** | gemini-3-pro-preview, gemini-3-flash-preview<br/>gemini-2.5-pro, gemini-2.5-flash<br/>gemini-2.0-flash, gemini-2.0-flash-thinking-exp<br/> gemini-2.0-flash-lite|| **Lingyiwanwu** | yi-lightning, yi-large, yi-medium<br/>yi-large-turbo, yi-vision, yi-medium-200k<br/>yi-spark, yi-large-rag, yi-large-fc |@@ -52,7 +52,7 @@ CAMEL supports a wide range of models, including [OpenAIās GPT series](https:/| **Reka** | reka-core, reka-flash, reka-edge || **COHERE** | command-r-plus, command-r, command-light, command, command-nightly || **ERNIE** | ernie-x1-turbo-32k, ernie-x1-32k, ernie-x1-32k-preview<br/>ernie-4.5-turbo-128k, ernie-4.5-turbo-32k<br/>deepseek-v3, deepseek-r1, qwen3-235b-a22b |-| **MiniMax** | MiniMax-M2, MiniMax-M2-Stable |+| **MiniMax** | MiniMax-M2.1, MiniMax-M2.1-lightning, MiniMax-M2, MiniMax-M2-Stable || **AtlasCloud** | openai/gpt-oss-120b, zai-org/glm-4-7 |diff --git a/docs/mintlify/key_modules/models.mdx b/docs/mintlify/key_modules/models.mdxindex f9686ab0b..d356dea2e 100644--- a/docs/mintlify/key_modules/models.mdx+++ b/docs/mintlify/key_modules/models.mdx@@ -39,7 +39,7 @@ CAMEL supports a wide range of models, including [OpenAIās GPT series](https:/| **OpenAI** | gpt-4.5-preview<br/>gpt-4o, gpt-4o-mini<br/>o1, o1-preview, o1-mini<br/>o3-mini, o3-pro, o3<br/>o4-mini<br/>gpt-4.1, gpt-4.1-mini, gpt-4.1-nano<br/>gpt-5, gpt-5-mini, gpt-5-nano<br/>gpt-4-turbo, gpt-4, gpt-3.5-turbo || **Azure OpenAI** | gpt-4o, gpt-4-turbo<br/>gpt-4, gpt-3.5-turbo || **Mistral AI** | mistral-large-latest, pixtral-12b-2409<br/>ministral-8b-latest, ministral-3b-latest<br/>open-mistral-nemo, codestral-latest<br/>open-mistral-7b, open-mixtral-8x7b<br/>open-mixtral-8x22b, open-codestral-mamba<br/>mistral-small-2506, mistral-medium-2508<br/>magistral-small-1.2, magistral-medium-1.2 |-| **Moonshot** | moonshot-v1-8k<br/>moonshot-v1-32k<br/>moonshot-v1-128k |+| **Moonshot** | kimi-k2-0905-Preview, kimi-k2.5, kimi-k2-turbo-preview<br/>kimi-k2-thinking, kimi-k2-thinking-turbo<br/>moonshot-v1-8k, moonshot-v1-32k, moonshot-v1-128k || **Anthropic** | claude-3-7-sonnet-latest<br/>claude-sonnet-4-5, claude-opus-4-5, claude-haiku-4-5<br/>claude-sonnet-4-20250514, claude-opus-4-20250514, claude-opus-4-1-20250805 || **Gemini** | gemini-3-pro-preview, gemini-3-flash-preview<br/>gemini-2.5-pro, gemini-2.5-flash<br/>gemini-2.0-flash, gemini-2.0-flash-thinking-exp<br/> gemini-2.0-flash-lite|| **Lingyiwanwu** | yi-lightning, yi-large, yi-medium<br/>yi-large-turbo, yi-vision, yi-medium-200k<br/>yi-spark, yi-large-rag, yi-large-fc |@@ -52,7 +52,7 @@ CAMEL supports a wide range of models, including [OpenAIās GPT series](https:/| **Reka** | reka-core, reka-flash, reka-edge || **COHERE** | command-r-plus, command-r, command-light, command, command-nightly || **ERNIE** | ernie-x1-turbo-32k, ernie-x1-32k, ernie-x1-32k-preview<br/>ernie-4.5-turbo-128k, ernie-4.5-turbo-32k<br/>deepseek-v3, deepseek-r1, qwen3-235b-a22b |-| **MiniMax** | MiniMax-M2, MiniMax-M2-Stable |+| **MiniMax** | MiniMax-M2.1, MiniMax-M2.1-lightning, MiniMax-M2, MiniMax-M2-Stable || **AtlasCloud** | openai/gpt-oss-120b, zai-org/glm-4-7 |diff --git a/examples/models/minimax_interleaved_thinking_example.py b/examples/models/minimax_interleaved_thinking_example.pynew file mode 100644index 000000000..2c224a3ff--- /dev/null+++ b/examples/models/minimax_interleaved_thinking_example.py@@ -0,0 +1,70 @@+# ========= 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 MinimaxConfig+from camel.models import ModelFactory+from camel.toolkits import FunctionTool+from camel.types import ModelPlatformType, ModelType++"""+Please set the following environment variable:+export MINIMAX_API_KEY="your_minimax_api_key"++This example demonstrates interleaved thinking with tool calls.+Note: stream must be disabled for interleaved thinking to work.+"""+++def calculate_total(+ subtotal: float, discount_rate: float, tax_rate: float, shipping: float+) -> float:+ """Calculate final total after discount, tax, and shipping."""+ discounted = subtotal * (1.0 - discount_rate)+ taxed = discounted * (1.0 + tax_rate)+ return taxed + shipping+++calculate_total_tool = FunctionTool(calculate_total)++model = ModelFactory.create(+ model_platform=ModelPlatformType.MINIMAX,+ model_type=ModelType.MINIMAX_M2,+ model_config_dict=MinimaxConfig(+ temperature=0.2,+ interleaved_thinking=True,+ tool_choice="required",+ ).as_dict(),+)++agent = ChatAgent(+ system_message=(+ "You are a helpful assistant. Always use the calculate_total tool "+ "for price calculations."+ ),+ model=model,+ tools=[calculate_total_tool],+)++response = agent.step(+ "Order A: subtotal $120, discount 15%, tax 8%, shipping $6. "+ "Use the tool to compute the final total and briefly explain."+)+print(response.msgs[0].content)++response = agent.step(+ "Order B: subtotal $75, same discount and tax rates as before, "+ "shipping $10. Use the tool to compute the final total."+)+print(response.msgs[0].content)diff --git a/examples/models/moonshot_interleaved_thinking_example.py b/examples/models/moonshot_interleaved_thinking_example.pynew file mode 100644index 000000000..75380b6df--- /dev/null+++ b/examples/models/moonshot_interleaved_thinking_example.py@@ -0,0 +1,68 @@+# ========= 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 MoonshotConfig+from camel.models import ModelFactory+from camel.toolkits import FunctionTool+from camel.types import ModelPlatformType, ModelType++"""+Please set the following environment variable:+export MOONSHOT_API_KEY="your_moonshot_api_key"++This example demonstrates interleaved thinking with tool calls.+Note: stream must be disabled for interleaved thinking to work.+"""+++def calculate_total(+ subtotal: float, discount_rate: float, tax_rate: float, shipping: float+) -> float:+ """Calculate final total after discount, tax, and shipping."""+ discounted = subtotal * (1.0 - discount_rate)+ taxed = discounted * (1.0 + tax_rate)+ return taxed + shipping+++calculate_total_tool = FunctionTool(calculate_total)++model = ModelFactory.create(+ model_platform=ModelPlatformType.MOONSHOT,+ model_type=ModelType.MOONSHOT_KIMI_K2,+ model_config_dict=MoonshotConfig(+ temperature=0.2, interleaved_thinking=True+ ).as_dict(),+)++agent = ChatAgent(+ system_message=(+ "You are a helpful assistant. Always use the calculate_total tool "+ "for price calculations."+ ),+ model=model,+ tools=[calculate_total_tool],+)++response = agent.step(+ "Order A: subtotal $120, discount 15%, tax 8%, shipping $6. "+ "Use the tool to compute the final total and briefly explain."+)+print(response.msgs[0].content)++response = agent.step(+ "Order B: subtotal $75, same discount and tax rates as before, "+ "shipping $10. Use the tool to compute the final total."+)+print(response.msgs[0].content)diff --git a/examples/models/openai_compatibility_model_examples/zhipu_response_format.py b/examples/models/openai_compatibility_model_examples/zhipu_response_format.pyindex 8831eb6fe..2685bf578 100644--- a/examples/models/openai_compatibility_model_examples/zhipu_response_format.py+++ b/examples/models/openai_compatibility_model_examples/zhipu_response_format.py@@ -29,7 +29,7 @@ class ResponseFormat(BaseModel):# Refer: https://dashscope.console.aliyun.com/overviewmodel = ModelFactory.create(model_platform=ModelPlatformType.OPENAI_COMPATIBLE_MODEL,- model_type="glm-4",+ model_type="glm-4-plus",api_key="fb75bxxxxx",url="https://open.bigmodel.cn/api/paas/v4/",model_config_dict={"temperature": 0.4},diff --git a/examples/models/volcano_interleaved_thinking_example.py b/examples/models/volcano_interleaved_thinking_example.pynew file mode 100644index 000000000..b1b8b5548--- /dev/null+++ b/examples/models/volcano_interleaved_thinking_example.py@@ -0,0 +1,71 @@+# ========= 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 VolcanoConfig+from camel.models import ModelFactory+from camel.toolkits import FunctionTool+from camel.types import ModelPlatformType++"""+Please set the following environment variable:+export VOLCANO_API_KEY="your_volcano_api_key"++This example demonstrates interleaved thinking with tool calls.+Note: stream must be disabled for interleaved thinking to work.++Replace model_type with a doubao-seed model that supports interleaved+thinking for best results.+"""+++def calculate_total(+ subtotal: float, discount_rate: float, tax_rate: float, shipping: float+) -> float:+ """Calculate final total after discount, tax, and shipping."""+ discounted = subtotal * (1.0 - discount_rate)+ taxed = discounted * (1.0 + tax_rate)+ return taxed + shipping+++calculate_total_tool = FunctionTool(calculate_total)++model = ModelFactory.create(+ model_platform=ModelPlatformType.VOLCANO,+ model_type="doubao-seed-1-6-thinking",+ model_config_dict=VolcanoConfig(+ temperature=0.2, interleaved_thinking=True+ ).as_dict(),+)++agent = ChatAgent(+ system_message=(+ "You are a helpful assistant. Always use the calculate_total tool "+ "for price calculations."+ ),+ model=model,+ tools=[calculate_total_tool],+)++response = agent.step(+ "Order A: subtotal $120, discount 15%, tax 8%, shipping $6. "+ "Use the tool to compute the final total and briefly explain."+)+print(response.msgs[0].content)++response = agent.step(+ "Order B: subtotal $75, same discount and tax rates as before, "+ "shipping $10. Use the tool to compute the final total."+)+print(response.msgs[0].content)diff --git a/examples/models/zhipuai_interleaved_thinking_example.py b/examples/models/zhipuai_interleaved_thinking_example.pynew file mode 100644index 000000000..170ce79cb--- /dev/null+++ b/examples/models/zhipuai_interleaved_thinking_example.py@@ -0,0 +1,70 @@+# ========= 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 ZhipuAIConfig+from camel.models import ModelFactory+from camel.toolkits import FunctionTool+from camel.types import ModelPlatformType, ModelType++"""+Please set the following environment variable:+export ZHIPUAI_API_KEY="your_zhipuai_api_key"++This example demonstrates interleaved thinking with tool calls.+Note: stream must be disabled for interleaved thinking to work.+"""+++def calculate_total(+ subtotal: float, discount_rate: float, tax_rate: float, shipping: float+) -> float:+ """Calculate final total after discount, tax, and shipping."""+ discounted = subtotal * (1.0 - discount_rate)+ taxed = discounted * (1.0 + tax_rate)+ return taxed + shipping+++calculate_total_tool = FunctionTool(calculate_total)++model = ModelFactory.create(+ model_platform=ModelPlatformType.ZHIPUAI,+ model_type=ModelType.GLM_4_PLUS,+ model_config_dict=ZhipuAIConfig(+ temperature=0.2,+ interleaved_thinking=True,+ tool_choice="required",+ ).as_dict(),+)++agent = ChatAgent(+ system_message=(+ "You are a helpful assistant. Always use the calculate_total tool "+ "for price calculations."+ ),+ model=model,+ tools=[calculate_total_tool],+)++response = agent.step(+ "Order A: subtotal $120, discount 15%, tax 8%, shipping $6. "+ "Use the tool to compute the final total and briefly explain."+)+print(response.msgs[0].content)++response = agent.step(+ "Order B: subtotal $75, same discount and tax rates as before, "+ "shipping $10. Use the tool to compute the final total."+)+print(response.msgs[0].content)diff --git a/examples/models/zhipuai_model_example.py b/examples/models/zhipuai_model_example.pyindex 9b5111080..b7c35b76c 100644--- a/examples/models/zhipuai_model_example.py+++ b/examples/models/zhipuai_model_example.py@@ -19,7 +19,7 @@ from camel.types import ModelPlatformType, ModelTypemodel = ModelFactory.create(model_platform=ModelPlatformType.ZHIPU,- model_type=ModelType.GLM_4,+ model_type=ModelType.GLM_4_PLUS,model_config_dict=ZhipuAIConfig(temperature=0.2).as_dict(),)diff --git a/test/models/test_minimax_model.py b/test/models/test_minimax_model.pyindex 73bb43057..bcd8c4c72 100644--- a/test/models/test_minimax_model.py+++ b/test/models/test_minimax_model.py@@ -24,11 +24,13 @@ class TestMinimaxModel:@pytest.mark.parametrize("model_type",[+ ModelType.MINIMAX_M2_1,+ ModelType.MINIMAX_M2_1_LIGHTNING,ModelType.MINIMAX_M2,ModelType.MINIMAX_M2_STABLE,],)- def test_minimax_m2_model_create(self, model_type: ModelType, monkeypatch):+ def test_minimax_model_create(self, model_type: ModelType, monkeypatch):monkeypatch.setenv("MINIMAX_API_KEY", "test_key")model = MinimaxModel(model_type)assert model.model_type == model_type@@ -88,12 +90,50 @@ class TestMinimaxModel:@pytest.mark.parametrize("model_type",[+ ModelType.MINIMAX_M2_1,+ ModelType.MINIMAX_M2_1_LIGHTNING,ModelType.MINIMAX_M2,ModelType.MINIMAX_M2_STABLE,],)- def test_minimax_m2_model_types_available(self, model_type: ModelType):- # Test that all defined Minimax M2 model types are recognized+ def test_minimax_model_types_available(+ self, model_type: ModelType, monkeypatch+ ):+ # Test that all defined Minimax model types are recognized+ monkeypatch.setenv("MINIMAX_API_KEY", "test_key")assert model_type.is_minimaxmodel = MinimaxModel(model_type)assert isinstance(model.model_type, ModelType)++ def test_minimax_model_interleaved_thinking_config(self, monkeypatch):+ # Test interleaved thinking configuration+ monkeypatch.setenv("MINIMAX_API_KEY", "test_key")+ config_dict = MinimaxConfig(+ interleaved_thinking=True,+ ).as_dict()++ model = MinimaxModel(+ model_type=ModelType.MINIMAX_M2,+ model_config_dict=config_dict,+ )++ assert model._is_thinking_enabled() is True+ # Verify reasoning_split is added to extra_body+ request_config = model._prepare_request_config()+ assert (+ request_config.get("extra_body", {}).get("reasoning_split") is True+ )+ assert "interleaved_thinking" not in request_config++ def test_minimax_model_interleaved_thinking_disabled(self, monkeypatch):+ # Test that interleaved thinking is disabled by default+ monkeypatch.setenv("MINIMAX_API_KEY", "test_key")++ model = MinimaxModel(model_type=ModelType.MINIMAX_M2)++ assert model._is_thinking_enabled() is False+ request_config = model._prepare_request_config()+ assert (+ "extra_body" not in request_config+ or "reasoning_split" not in request_config.get("extra_body", {})+ )diff --git a/test/models/test_moonshot_model.py b/test/models/test_moonshot_model.pyindex a0ab9d028..12077b67f 100644--- a/test/models/test_moonshot_model.py+++ b/test/models/test_moonshot_model.py@@ -13,6 +13,8 @@# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========+from unittest.mock import MagicMock+import pytestfrom camel.configs import MoonshotConfig@@ -27,11 +29,130 @@ from camel.types import ModelTypeModelType.MOONSHOT_V1_8K,ModelType.MOONSHOT_V1_32K,ModelType.MOONSHOT_V1_128K,+ ModelType.MOONSHOT_KIMI_K2,+ ModelType.MOONSHOT_KIMI_K2_5,+ ModelType.MOONSHOT_KIMI_K2_TURBO_PREVIEW,+ ModelType.MOONSHOT_KIMI_K2_THINKING,+ ModelType.MOONSHOT_KIMI_K2_THINKING_TURBO,],)-def test_moonshot_model(model_type: ModelType):+def test_moonshot_model(model_type: ModelType, monkeypatch):+ monkeypatch.setenv("MOONSHOT_API_KEY", "test_key")model = MoonshotModel(model_type)assert model.model_type == model_typeassert model.model_config_dict == MoonshotConfig().as_dict()assert isinstance(model.model_type.value_for_tiktoken, str)assert isinstance(model.model_type.token_limit, int)++[email protected]_backend+def test_moonshot_model_thinking_config(monkeypatch):+ """Test that interleaved_thinking configuration is properly set."""+ monkeypatch.setenv("MOONSHOT_API_KEY", "test_key")+ config = MoonshotConfig(interleaved_thinking=True)+ model = MoonshotModel(+ ModelType.MOONSHOT_KIMI_K2,+ model_config_dict=config.as_dict(),+ )+ assert model.model_config_dict.get("interleaved_thinking") is True+ assert model._is_thinking_enabled() is True++[email protected]_backend+def test_moonshot_model_thinking_disabled(monkeypatch):+ """Test that interleaved_thinking is disabled by default."""+ monkeypatch.setenv("MOONSHOT_API_KEY", "test_key")+ model = MoonshotModel(ModelType.MOONSHOT_V1_8K)+ assert model._is_thinking_enabled() is False++[email protected]_backend+def test_moonshot_model_inject_reasoning_content(monkeypatch):+ """Test reasoning_content injection into assistant messages."""+ monkeypatch.setenv("MOONSHOT_API_KEY", "test_key")+ config = MoonshotConfig(interleaved_thinking=True)+ model = MoonshotModel(+ ModelType.MOONSHOT_KIMI_K2,+ model_config_dict=config.as_dict(),+ )++ # Set up test messages with tool calls+ messages = [+ {"role": "user", "content": "Hello"},+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [{"id": "call_123", "function": {"name": "test"}}],+ },+ {"role": "tool", "content": "result", "tool_call_id": "call_123"},+ ]++ # Set the last reasoning content+ model._last_reasoning = "This is my reasoning"++ # Inject reasoning content+ processed = model._inject_reasoning(messages)++ # Check that reasoning_content was injected+ assert processed[1].get("reasoning_content") == "This is my reasoning"+ # Check that _last_reasoning was cleared+ assert model._last_reasoning is None++[email protected]_backend+def test_moonshot_model_inject_reasoning_content_disabled(monkeypatch):+ """Test that reasoning_content is not injected when disabled."""+ monkeypatch.setenv("MOONSHOT_API_KEY", "test_key")+ model = MoonshotModel(ModelType.MOONSHOT_V1_8K)++ messages = [+ {"role": "user", "content": "Hello"},+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [{"id": "call_123", "function": {"name": "test"}}],+ },+ ]++ model._last_reasoning = "This is my reasoning"+ processed = model._inject_reasoning(messages)++ # Should return original messages unchanged+ assert processed == messages+ # reasoning content should not be cleared when thinking is disabled+ assert model._last_reasoning == "This is my reasoning"++[email protected]_backend+def test_moonshot_model_extract_reasoning_content(monkeypatch):+ """Test extraction of reasoning_content from response."""+ monkeypatch.setenv("MOONSHOT_API_KEY", "test_key")+ model = MoonshotModel(ModelType.MOONSHOT_KIMI_K2)++ # Create a mock response with reasoning_content+ mock_response = MagicMock()+ mock_message = MagicMock()+ mock_message.reasoning_content = "Extracted reasoning"+ mock_choice = MagicMock()+ mock_choice.message = mock_message+ mock_response.choices = [mock_choice]++ result = model._extract_reasoning(mock_response)+ assert result == "Extracted reasoning"++[email protected]_backend+def test_moonshot_model_extract_reasoning_content_none(monkeypatch):+ """Test extraction returns None when no reasoning_content."""+ monkeypatch.setenv("MOONSHOT_API_KEY", "test_key")+ model = MoonshotModel(ModelType.MOONSHOT_KIMI_K2)++ # Create a mock response without reasoning_content+ mock_response = MagicMock()+ mock_message = MagicMock(spec=[]) # No reasoning_content attribute+ mock_choice = MagicMock()+ mock_choice.message = mock_message+ mock_response.choices = [mock_choice]++ result = model._extract_reasoning(mock_response)+ assert result is Nonediff --git a/test/models/test_volcano_model.py b/test/models/test_volcano_model.pyindex 5e7f4bddd..a13a1bcfb 100644--- a/test/models/test_volcano_model.py+++ b/test/models/test_volcano_model.py@@ -12,17 +12,134 @@# limitations under the License.# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========+from unittest.mock import MagicMock+import pytest+from camel.configs import VolcanoConfigfrom camel.models import VolcanoModelfrom camel.utils import OpenAITokenCounter@pytest.mark.model_backend-def test_volcano_model():+def test_volcano_model(monkeypatch):+ monkeypatch.setenv("VOLCANO_API_KEY", "test_key")# Using a string model type since Volcano supports various modelsmodel_type = "deepseek-r1-250120"model = VolcanoModel(model_type)assert model.model_type == model_typeassert model.model_config_dict == {}assert isinstance(model.token_counter, OpenAITokenCounter)++[email protected]_backend+def test_volcano_model_thinking_config(monkeypatch):+ """Test that interleaved_thinking configuration is properly set."""+ monkeypatch.setenv("VOLCANO_API_KEY", "test_key")+ config = VolcanoConfig(interleaved_thinking=True)+ model = VolcanoModel(+ "doubao-seed-1-6-250615",+ model_config_dict=config.as_dict(),+ )+ assert model.model_config_dict.get("interleaved_thinking") is True+ assert model._is_thinking_enabled() is True++[email protected]_backend+def test_volcano_model_thinking_disabled(monkeypatch):+ """Test that interleaved_thinking is disabled by default."""+ monkeypatch.setenv("VOLCANO_API_KEY", "test_key")+ model = VolcanoModel("deepseek-r1-250120")+ assert model._is_thinking_enabled() is False++[email protected]_backend+def test_volcano_model_inject_reasoning_content(monkeypatch):+ """Test reasoning_content injection into assistant messages."""+ monkeypatch.setenv("VOLCANO_API_KEY", "test_key")+ config = VolcanoConfig(interleaved_thinking=True)+ model = VolcanoModel(+ "doubao-seed-1-6-250615",+ model_config_dict=config.as_dict(),+ )++ # Set up test messages with tool calls+ messages = [+ {"role": "user", "content": "Hello"},+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [{"id": "call_123", "function": {"name": "test"}}],+ },+ {"role": "tool", "content": "result", "tool_call_id": "call_123"},+ ]++ # Set the last reasoning content+ model._last_reasoning = "This is my reasoning"++ # Inject reasoning content+ processed = model._inject_reasoning(messages)++ # Check that reasoning_content was injected+ assert processed[1].get("reasoning_content") == "This is my reasoning"+ # Check that _last_reasoning was cleared+ assert model._last_reasoning is None++[email protected]_backend+def test_volcano_model_inject_reasoning_content_disabled(monkeypatch):+ """Test that reasoning_content is not injected when disabled."""+ monkeypatch.setenv("VOLCANO_API_KEY", "test_key")+ model = VolcanoModel("deepseek-r1-250120")++ messages = [+ {"role": "user", "content": "Hello"},+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [{"id": "call_123", "function": {"name": "test"}}],+ },+ ]++ model._last_reasoning = "This is my reasoning"+ processed = model._inject_reasoning(messages)++ # Should return original messages unchanged+ assert processed == messages+ # reasoning content should not be cleared when thinking is disabled+ assert model._last_reasoning == "This is my reasoning"++[email protected]_backend+def test_volcano_model_extract_reasoning_content(monkeypatch):+ """Test extraction of reasoning_content from response."""+ monkeypatch.setenv("VOLCANO_API_KEY", "test_key")+ model = VolcanoModel("doubao-seed-1-6-250615")++ # Create a mock response with reasoning_content+ mock_response = MagicMock()+ mock_message = MagicMock()+ mock_message.reasoning_content = "Extracted reasoning"+ mock_choice = MagicMock()+ mock_choice.message = mock_message+ mock_response.choices = [mock_choice]++ result = model._extract_reasoning(mock_response)+ assert result == "Extracted reasoning"++[email protected]_backend+def test_volcano_model_extract_reasoning_content_none(monkeypatch):+ """Test extraction returns None when no reasoning_content."""+ monkeypatch.setenv("VOLCANO_API_KEY", "test_key")+ model = VolcanoModel("doubao-seed-1-6-250615")++ # Create a mock response without reasoning_content+ mock_response = MagicMock()+ mock_message = MagicMock(spec=[]) # No reasoning_content attribute+ mock_choice = MagicMock()+ mock_choice.message = mock_message+ mock_response.choices = [mock_choice]++ result = model._extract_reasoning(mock_response)+ assert result is Nonediff --git a/test/models/test_zhipuai_model.py b/test/models/test_zhipuai_model.pyindex 122e7d5b5..78c102f14 100644--- a/test/models/test_zhipuai_model.py+++ b/test/models/test_zhipuai_model.py@@ -12,6 +12,8 @@# limitations under the License.# ========= Copyright 2023-2026 @ CAMEL-AI.org. All Rights Reserved. =========+from unittest.mock import MagicMock+import pytestfrom camel.configs import ZhipuAIConfig@@ -24,25 +26,160 @@ from camel.utils import OpenAITokenCounter@pytest.mark.parametrize("model_type",[- ModelType.GLM_3_TURBO,+ # GLM-4.7 series (latest)+ ModelType.GLM_4_7,+ ModelType.GLM_4_7_FLASHX,+ ModelType.GLM_4_7_FLASH,+ # GLM-4.6 series+ ModelType.GLM_4_6,+ # GLM-4 seriesModelType.GLM_4,+ ModelType.GLM_4_5_AIR,+ ModelType.GLM_4_5_AIRX,+ ModelType.GLM_4_5_FLASH,ModelType.GLM_4V,+ ModelType.GLM_4_1V_THINKING_FLASHX,+ ModelType.GLM_4_1V_THINKING_FLASH,ModelType.GLM_4V_FLASH,ModelType.GLM_4V_PLUS_0111,+ # GLM-4 legacy modelsModelType.GLM_4_PLUS,ModelType.GLM_4_AIR,ModelType.GLM_4_AIR_0111,ModelType.GLM_4_AIRX,ModelType.GLM_4_LONG,ModelType.GLM_4_FLASHX,+ ModelType.GLM_4_FLASHX_250414,ModelType.GLM_4_FLASH,+ ModelType.GLM_4_FLASH_250414,+ # GLM-Zero series (reasoning models)ModelType.GLM_ZERO_PREVIEW,+ ModelType.GLM_3_TURBO,+ # GLM Vision models (VLM)+ ModelType.GLM_4_6V,+ ModelType.GLM_4_6V_FLASHX,+ ModelType.GLM_4_5V,+ ModelType.GLM_4_6V_FLASH,],)-def test_zhipuai_model(model_type: ModelType):+def test_zhipuai_model(model_type: ModelType, monkeypatch):+ monkeypatch.setenv("ZHIPUAI_API_KEY", "test_key")model = ZhipuAIModel(model_type)assert model.model_type == model_typeassert model.model_config_dict == ZhipuAIConfig().as_dict()assert isinstance(model.token_counter, OpenAITokenCounter)assert isinstance(model.model_type.value_for_tiktoken, str)assert isinstance(model.model_type.token_limit, int)++[email protected]_backend+def test_zhipuai_model_thinking_config(monkeypatch):+ """Test that interleaved_thinking configuration is properly set."""+ monkeypatch.setenv("ZHIPUAI_API_KEY", "test_key")+ config = ZhipuAIConfig(interleaved_thinking=True)+ model = ZhipuAIModel(+ ModelType.GLM_4_PLUS,+ model_config_dict=config.as_dict(),+ )+ assert model.model_config_dict.get("interleaved_thinking") is True+ assert model._is_thinking_enabled() is True++[email protected]_backend+def test_zhipuai_model_thinking_disabled(monkeypatch):+ """Test that interleaved_thinking is disabled by default."""+ monkeypatch.setenv("ZHIPUAI_API_KEY", "test_key")+ model = ZhipuAIModel(ModelType.GLM_4_PLUS)+ assert model._is_thinking_enabled() is False++[email protected]_backend+def test_zhipuai_model_inject_reasoning_content(monkeypatch):+ """Test reasoning_content injection into assistant messages."""+ monkeypatch.setenv("ZHIPUAI_API_KEY", "test_key")+ config = ZhipuAIConfig(interleaved_thinking=True)+ model = ZhipuAIModel(+ ModelType.GLM_4_PLUS,+ model_config_dict=config.as_dict(),+ )++ # Set up test messages with tool calls+ messages = [+ {"role": "user", "content": "Hello"},+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [{"id": "call_123", "function": {"name": "test"}}],+ },+ {"role": "tool", "content": "result", "tool_call_id": "call_123"},+ ]++ # Set the last reasoning content+ model._last_reasoning = "This is my reasoning"++ # Inject reasoning content+ processed = model._inject_reasoning(messages)++ # Check that reasoning_content was injected+ assert processed[1].get("reasoning_content") == "This is my reasoning"+ # Check that _last_reasoning was cleared+ assert model._last_reasoning is None++[email protected]_backend+def test_zhipuai_model_inject_reasoning_content_disabled(monkeypatch):+ """Test that reasoning_content is not injected when disabled."""+ monkeypatch.setenv("ZHIPUAI_API_KEY", "test_key")+ model = ZhipuAIModel(ModelType.GLM_4_PLUS)++ messages = [+ {"role": "user", "content": "Hello"},+ {+ "role": "assistant",+ "content": None,+ "tool_calls": [{"id": "call_123", "function": {"name": "test"}}],+ },+ ]++ model._last_reasoning = "This is my reasoning"+ processed = model._inject_reasoning(messages)++ # Should return original messages unchanged+ assert processed == messages+ # reasoning content should not be cleared when thinking is disabled+ assert model._last_reasoning == "This is my reasoning"++[email protected]_backend+def test_zhipuai_model_extract_reasoning_content(monkeypatch):+ """Test extraction of reasoning_content from response."""+ monkeypatch.setenv("ZHIPUAI_API_KEY", "test_key")+ model = ZhipuAIModel(ModelType.GLM_4_PLUS)++ # Create a mock response with reasoning_content+ mock_response = MagicMock()+ mock_message = MagicMock()+ mock_message.reasoning_content = "Extracted reasoning"+ mock_choice = MagicMock()+ mock_choice.message = mock_message+ mock_response.choices = [mock_choice]++ result = model._extract_reasoning(mock_response)+ assert result == "Extracted reasoning"++[email protected]_backend+def test_zhipuai_model_extract_reasoning_content_none(monkeypatch):+ """Test extraction returns None when no reasoning_content."""+ monkeypatch.setenv("ZHIPUAI_API_KEY", "test_key")+ model = ZhipuAIModel(ModelType.GLM_4_PLUS)++ # Create a mock response without reasoning_content+ mock_response = MagicMock()+ mock_message = MagicMock(spec=[]) # No reasoning_content attribute+ mock_choice = MagicMock()+ mock_choice.message = mock_message+ mock_response.choices = [mock_choice]++ result = model._extract_reasoning(mock_response)+ assert result is None