🐫 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: Add Minimax M2 model support (#3404)
haoye28b56a009f184
diff --git a/.github/workflows/build_package.yml b/.github/workflows/build_package.ymlindex dfd01fded..325307a01 100644--- a/.github/workflows/build_package.yml+++ b/.github/workflows/build_package.yml@@ -144,6 +144,7 @@ jobs:QIANFAN_API_KEY: "${{ secrets.QIANFAN_API_KEY }}"ACI_API_KEY: "${{ secrets.ACI_API_KEY }}"BOHRIUM_API_KEY: "${{ secrets.BOHRIUM_API_KEY }}"+ MINIMAX_API_KEY: "${{ secrets.MINIMAX_API_KEY}}"CRYNUX_API_KEY: "${{ secrets.CRYNUX_API_KEY }}"NEBIUS_API_KEY: "${{ secrets.NEBIUS_API_KEY }}"COMETAPI_KEY: "${{ secrets.COMETAPI_KEY }}"diff --git a/.github/workflows/pytest_package.yml b/.github/workflows/pytest_package.ymlindex c4e17137d..dedbdc7d8 100644--- a/.github/workflows/pytest_package.yml+++ b/.github/workflows/pytest_package.yml@@ -90,6 +90,7 @@ jobs:CRYNUX_API_KEY: "${{ secrets.CRYNUX_API_KEY }}"NEBIUS_API_KEY: "${{ secrets.NEBIUS_API_KEY }}"COMETAPI_KEY: "${{ secrets.COMETAPI_KEY }}"+ MINIMAX_API_KEY: "${{ secrets.MINIMAX_API_KEY }}"run: |source .venv/bin/activateuv pip install -e ".[all, dev, docs]"@@ -177,6 +178,7 @@ jobs:NEBIUS_API_KEY: "${{ secrets.NEBIUS_API_KEY }}"AMD_API_KEY: "${{ secrets.AMD_API_KEY }}"COMETAPI_KEY: "${{ secrets.COMETAPI_KEY }}"+ MINIMAX_API_KEY: "${{ secrets.MINIMAX_API_KEY }}"run: |source .venv/bin/activateuv pip install -e ".[all, dev, docs]"@@ -262,6 +264,7 @@ jobs:NEBIUS_API_KEY: "${{ secrets.NEBIUS_API_KEY }}"AMD_API_KEY: "${{ secrets.AMD_API_KEY }}"COMETAPI_KEY: "${{ secrets.COMETAPI_KEY }}"+ MINIMAX_API_KEY: "${{ secrets.MINIMAX_API_KEY }}"run: |source .venv/bin/activateuv pip install -e ".[all, dev, docs]"diff --git a/camel/configs/__init__.py b/camel/configs/__init__.pyindex f6856ab5b..620ab9150 100644--- a/camel/configs/__init__.py+++ b/camel/configs/__init__.py@@ -26,6 +26,7 @@ from .groq_config import GROQ_API_PARAMS, GroqConfigfrom .internlm_config import INTERNLM_API_PARAMS, InternLMConfigfrom .litellm_config import LITELLM_API_PARAMS, LiteLLMConfigfrom .lmstudio_config import LMSTUDIO_API_PARAMS, LMStudioConfig+from .minimax_config import MINIMAX_API_PARAMS, MinimaxConfigfrom .mistral_config import MISTRAL_API_PARAMS, MistralConfigfrom .modelscope_config import MODELSCOPE_API_PARAMS, ModelScopeConfigfrom .moonshot_config import MOONSHOT_API_PARAMS, MoonshotConfig@@ -124,6 +125,8 @@ __all__ = ['OPENROUTER_API_PARAMS','LMSTUDIO_API_PARAMS','LMStudioConfig',+ 'MINIMAX_API_PARAMS',+ 'MinimaxConfig','WatsonXConfig','WATSONX_API_PARAMS','QianfanConfig',diff --git a/camel/configs/minimax_config.py b/camel/configs/minimax_config.pynew file mode 100644index 000000000..66da988de--- /dev/null+++ b/camel/configs/minimax_config.py@@ -0,0 +1,93 @@+# ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========+from __future__ import annotations++from typing import Optional, Sequence, Union++from camel.configs.base_config import BaseConfig+++class MinimaxConfig(BaseConfig):+ r"""Defines the parameters for generating chat completions using OpenAI+ compatibility with Minimax.++ Reference: https://api.minimax.chat/document/guides/chat-model++ Args:+ temperature (float, optional): Sampling temperature to use, between+ :obj:`0.0` and :obj:`1.0`. Higher values make the output more+ random, while lower values make it more focused and deterministic.+ Recommended to use :obj:`1.0`. Values outside this range will+ return an error. (default: :obj:`None`)+ top_p (float, optional): An alternative to sampling with temperature,+ called nucleus sampling, where the model considers the results of+ the tokens with top_p probability mass. So :obj:`0.1` means only+ the tokens comprising the top 10% probability mass are considered.+ (default: :obj:`None`)+ n (int, optional): How many chat completion choices to generate for+ each input message. Only supports value :obj:`1`.+ (default: :obj:`None`)+ response_format (object, optional): An object specifying the format+ that the model must output. Setting to+ {"type": "json_object"} enables JSON mode, which guarantees the+ message the model generates is valid JSON. Important: when using+ JSON mode, you must also instruct the model to produce JSON+ yourself via a system or user message. Without this, the model+ may generate an unending stream of whitespace until the generation+ reaches the token limit, resulting in a long-running and seemingly+ "stuck" request. Also note that the message content may be+ partially cut off if finish_reason="length", which indicates the+ generation exceeded max_tokens or the conversation exceeded the+ max context length. (default: :obj:`None`)+ stream (bool, optional): If set, partial message deltas will be sent,+ like in ChatGPT. Tokens will be sent as data-only server-sent+ events as they become available, with the stream terminated by+ a data: [DONE] message. (default: :obj:`None`)+ stop (str or list, optional): Up to :obj:`4` sequences where the API+ will stop generating further tokens. (default: :obj:`None`)+ max_tokens (int, optional): The maximum number of tokens to generate+ in the chat completion. The total length of input tokens and+ generated tokens is limited by the model's context length.+ (default: :obj:`None`)+ user (str, optional): A unique identifier representing your end-user,+ which can help to monitor and detect abuse.+ (default: :obj:`None`)+ tool_choice (Union[dict[str, str], str], optional): Controls which (if+ any) tool is called by the model. :obj:`"none"` means the model+ will not call any tool and instead generates a message.+ :obj:`"auto"` means the model can pick between generating a+ message or calling one or more tools. :obj:`"required"` means the+ model must call one or more tools. Specifying a particular tool+ via {"type": "function", "function": {"name": "my_function"}}+ forces the model to call that tool. :obj:`"none"` is the default+ when no tools are present. :obj:`"auto"` is the default if tools+ are present.++ Note:+ Some OpenAI parameters such as presence_penalty, frequency_penalty,+ and logit_bias will be ignored by Minimax.+ """++ temperature: Optional[float] = None+ top_p: Optional[float] = None+ n: Optional[int] = None+ stream: Optional[bool] = None+ stop: Optional[Union[str, Sequence[str]]] = None+ max_tokens: Optional[int] = None+ response_format: Optional[dict] = None+ user: Optional[str] = None+ tool_choice: Optional[Union[dict[str, str], str]] = None+++MINIMAX_API_PARAMS = {param for param in MinimaxConfig.model_fields.keys()}diff --git a/camel/models/__init__.py b/camel/models/__init__.pyindex 3978184b4..55f728a40 100644--- a/camel/models/__init__.py+++ b/camel/models/__init__.py@@ -29,6 +29,7 @@ from .groq_model import GroqModelfrom .internlm_model import InternLMModelfrom .litellm_model import LiteLLMModelfrom .lmstudio_model import LMStudioModel+from .minimax_model import MinimaxModelfrom .mistral_model import MistralModelfrom .model_factory import ModelFactoryfrom .model_manager import ModelManager, ModelProcessingError@@ -104,6 +105,7 @@ __all__ = ['SiliconFlowModel','VolcanoModel','LMStudioModel',+ 'MinimaxModel','WatsonXModel','QianfanModel','CrynuxModel',diff --git a/camel/models/minimax_model.py b/camel/models/minimax_model.pynew file mode 100644index 000000000..f5b644d5b--- /dev/null+++ b/camel/models/minimax_model.py@@ -0,0 +1,83 @@+# ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========+import os+from typing import Any, Dict, Optional, Union++from camel.configs import MinimaxConfig+from camel.models.openai_compatible_model import OpenAICompatibleModel+from camel.types import ModelType+from camel.utils import (+ BaseTokenCounter,+ api_keys_required,+)+++class MinimaxModel(OpenAICompatibleModel):+ r"""LLM API served by Minimax in a unified OpenAICompatibleModel+ interface.++ Args:+ model_type (Union[ModelType, str]): Model for which a backend is+ created.+ model_config_dict (Optional[Dict[str, Any]], optional): A dictionary+ that will be fed into:obj:`openai.ChatCompletion.create()`.+ If:obj:`None`, :obj:`MinimaxConfig().as_dict()` will be used.+ (default: :obj:`None`)+ api_key (Optional[str], optional): The API key for authenticating+ with the Minimax service. (default: :obj:`None`).+ url (Optional[str], optional): The url to the Minimax M2 service.+ (default: :obj:`None`)+ token_counter (Optional[BaseTokenCounter], optional): Token counter to+ use for the model. If not provided, :obj:`OpenAITokenCounter(+ ModelType.GPT_4O_MINI)` will be used.+ (default: :obj:`None`)+ timeout (Optional[float], optional): The timeout value in seconds for+ API calls. If not provided, will fall back to the MODEL_TIMEOUT+ environment variable or default to 180 seconds.+ (default: :obj:`None`)+ max_retries (int, optional): Maximum number of retries for API calls.+ (default: :obj:`3`)+ **kwargs (Any): Additional arguments to pass to the client+ initialization.+ """++ @api_keys_required([("api_key", "MINIMAX_API_KEY")])+ def __init__(+ self,+ model_type: Union[ModelType, str],+ model_config_dict: Optional[Dict[str, Any]] = None,+ api_key: Optional[str] = None,+ url: Optional[str] = None,+ token_counter: Optional[BaseTokenCounter] = None,+ timeout: Optional[float] = None,+ max_retries: int = 3,+ **kwargs: Any,+ ) -> None:+ if model_config_dict is None:+ model_config_dict = MinimaxConfig().as_dict()+ api_key = api_key or os.environ.get("MINIMAX_API_KEY")+ url = url or os.environ.get(+ "MINIMAX_API_BASE_URL", "https://api.minimaxi.com/v1"+ )+ timeout = timeout or float(os.environ.get("MODEL_TIMEOUT", 180))+ super().__init__(+ model_type=model_type,+ model_config_dict=model_config_dict,+ api_key=api_key,+ url=url,+ token_counter=token_counter,+ timeout=timeout,+ max_retries=max_retries,+ **kwargs,+ )diff --git a/camel/models/model_factory.py b/camel/models/model_factory.pyindex 736052324..6d05dcdfe 100644--- a/camel/models/model_factory.py+++ b/camel/models/model_factory.py@@ -31,6 +31,7 @@ from camel.models.groq_model import GroqModelfrom camel.models.internlm_model import InternLMModelfrom camel.models.litellm_model import LiteLLMModelfrom camel.models.lmstudio_model import LMStudioModel+from camel.models.minimax_model import MinimaxModelfrom camel.models.mistral_model import MistralModelfrom camel.models.modelscope_model import ModelScopeModelfrom camel.models.moonshot_model import MoonshotModel@@ -91,6 +92,7 @@ class ModelFactory:ModelPlatformType.COMETAPI: CometAPIModel,ModelPlatformType.NEBIUS: NebiusModel,ModelPlatformType.LMSTUDIO: LMStudioModel,+ ModelPlatformType.MINIMAX: MinimaxModel,ModelPlatformType.OPENROUTER: OpenRouterModel,ModelPlatformType.ZHIPU: ZhipuAIModel,ModelPlatformType.GEMINI: GeminiModel,diff --git a/camel/types/enums.py b/camel/types/enums.pyindex 3eafb06b2..ab30d8c4a 100644--- a/camel/types/enums.py+++ b/camel/types/enums.py@@ -502,6 +502,10 @@ 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_M2 = "MiniMax-M2"+ MINIMAX_M2_STABLE = "MiniMax-M2-Stable"+def __str__(self):return self.value@@ -1554,6 +1558,11 @@ class ModelType(UnifiedModelType, Enum):ModelType.TOGETHER_LLAMA_4_SCOUT,}:return 10_000_000+ elif self in {+ ModelType.MINIMAX_M2,+ ModelType.MINIMAX_M2_STABLE,+ }:+ return 32_000else:logger.warning(@@ -1787,6 +1796,7 @@ class ModelPlatformType(Enum):QIANFAN = "qianfan"CRYNUX = "crynux"AIHUBMIX = "aihubmix"+ MINIMAX = "minimax"@classmethoddef from_name(cls, name):@@ -1972,6 +1982,11 @@ class ModelPlatformType(Enum):r"""Returns whether this platform is AihubMix."""return self is ModelPlatformType.AIHUBMIX+ @property+ def is_minimax(self) -> bool:+ r"""Returns whether this platform is Minimax M2."""+ return self is ModelPlatformType.MINIMAX+class AudioModelType(Enum):TTS_1 = "tts-1"diff --git a/camel/types/unified_model_type.py b/camel/types/unified_model_type.pyindex a9d32a360..7bf404b40 100644--- a/camel/types/unified_model_type.py+++ b/camel/types/unified_model_type.py@@ -195,6 +195,11 @@ class UnifiedModelType(str):r"""Returns whether the model is a Crynux served model."""return True+ @property+ def is_minimax(self) -> bool:+ r"""Returns whether the model is a Minimax served model."""+ return True+@propertydef support_native_structured_output(self) -> bool:r"""Returns whether the model supports native structured output."""diff --git a/docs/mintlify/key_modules/models.mdx b/docs/mintlify/key_modules/models.mdxindex 4cedef76f..d0a059a32 100644--- a/docs/mintlify/key_modules/models.mdx+++ b/docs/mintlify/key_modules/models.mdx@@ -52,6 +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 |### API & Connector Platformsdiff --git a/examples/models/minimax_model_example.py b/examples/models/minimax_model_example.pynew file mode 100644index 000000000..40f8753d1--- /dev/null+++ b/examples/models/minimax_model_example.py@@ -0,0 +1,49 @@+# ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========++from camel.agents import ChatAgent+from camel.configs import MinimaxConfig+from camel.models import ModelFactory+from camel.types import ModelPlatformType, ModelType++model = ModelFactory.create(+ model_platform=ModelPlatformType.MINIMAX,+ model_type=ModelType.MINIMAX_M2,+ model_config_dict=MinimaxConfig(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 = """Say hi to CAMEL AI, one open-source community+ dedicated to the study of autonomous and communicative agents."""++# Get response information+response = camel_agent.step(user_msg)+print(response.msgs[0].content)++'''+===============================================================================+Hello to the CAMEL AI community! It's wonderful to connect with such a+dedicated open-source community focused on advancing the study of autonomous+and communicative agents. Your commitment to open collaboration and knowledge+sharing in the AI field is truly inspiring. I'm excited to see the innovative+work and breakthroughs that will emerge from your community's efforts in+pushing the boundaries of intelligent agent research. Keep up the fantastic+work in shaping the future of autonomous AI systems!+===============================================================================+'''diff --git a/test/models/test_minimax_model.py b/test/models/test_minimax_model.pynew file mode 100644index 000000000..5f831e764--- /dev/null+++ b/test/models/test_minimax_model.py@@ -0,0 +1,95 @@+# ========= Copyright 2023-2024 @ 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-2024 @ CAMEL-AI.org. All Rights Reserved. =========++import pytest++from camel.configs import MinimaxConfig+from camel.models import MinimaxModel+from camel.types import ModelType++[email protected]_backend+class TestMinimaxModel:+ @pytest.mark.parametrize(+ "model_type",+ [+ ModelType.MINIMAX_M2,+ ModelType.MINIMAX_M2_STABLE,+ ],+ )+ def test_minimax_m2_model_create(self, model_type: ModelType):+ model = MinimaxModel(model_type)+ assert model.model_type == model_type++ def test_minimax_m2_model_create_with_config(self):+ config_dict = MinimaxConfig(+ temperature=0.5,+ top_p=1.0,+ max_tokens=100,+ ).as_dict()++ model = MinimaxModel(+ model_type=ModelType.MINIMAX_M2,+ model_config_dict=config_dict,+ )++ assert model.model_type == ModelType.MINIMAX_M2+ assert model.model_config_dict == config_dict++ def test_minimax_m2_model_api_keys_required(self):+ # Test that the api_keys_required decorator is applied+ assert hasattr(MinimaxModel.__init__, "__wrapped__")++ def test_minimax_m2_model_default_url(self, monkeypatch):+ # Test default URL when no environment variable is set+ monkeypatch.delenv("MINIMAX_API_BASE_URL ", raising=False)+ monkeypatch.setenv("MINIMAX_API_KEY", "test_key")++ model = MinimaxModel(ModelType.MINIMAX_M2)+ assert model._url == "https://api.minimax.chat/v1"++ def test_minimax_m2_model_custom_url(self, monkeypatch):+ # Test custom URL from environment variable+ custom_url = "https://custom.minimax.endpoint/v1"+ monkeypatch.setenv("MINIMAX_M2_API_BASE_URL", custom_url)+ monkeypatch.setenv("MINIMAX_M2_API_KEY", "test_key")++ model = MinimaxModel(ModelType.MINIMAX_M2)+ assert model._url == custom_url++ def test_minimax_m2_model_extends_openai_compatible(self):+ # Test that MinimaxModel inherits from OpenAICompatibleModel+ from camel.models.openai_compatible_model import OpenAICompatibleModel++ model = MinimaxModel(ModelType.MINIMAX_M2)+ assert isinstance(model, OpenAICompatibleModel)++ def test_minimax_m2_model_token_counter(self):+ model = MinimaxModel(ModelType.MINIMAX_M2)+ # Should use the default OpenAI token counter+ assert model.token_counter is not None+ assert hasattr(model.token_counter, "count_tokens_from_messages")++ @pytest.mark.parametrize(+ "model_type",+ [+ 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+ assert model_type.is_minimax+ model = MinimaxModel(model_type)+ assert isinstance(model.model_type, ModelType)