Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(models): add MiniMax chat model support (M3 default) (#1764)
Octopus1e00641c8ae3
diff --git a/scripts/model_examples/README.md b/scripts/model_examples/README.mdindex fe9bfcb07..b07d02203 100644--- a/scripts/model_examples/README.md+++ b/scripts/model_examples/README.md@@ -28,6 +28,11 @@ scripts/model_examples/├── anthropic_multimodal.py├── anthropic_multiagent_multimodal.py│+├── minimax_call.py # MiniMax M-series+├── minimax_multiagent.py+├── minimax_multimodal.py+├── minimax_multiagent_multimodal.py+│├── dashscope_call.py # Alibaba DashScope / Qwen├── dashscope_multiagent.py├── dashscope_multimodal.py@@ -80,6 +85,7 @@ scripts/model_examples/| `openai_chat` | `OPENAI_API_KEY` | Chat Completions API – gpt-4.1, etc. || `openai_response` | `OPENAI_API_KEY` | Responses API – o1, o3, o4-mini, etc. || `anthropic` | `ANTHROPIC_API_KEY` | Claude models, supports extended thinking |+| `minimax` | `MINIMAX_API_KEY` | MiniMax M-series via the Anthropic-compatible API || `dashscope` | `DASHSCOPE_API_KEY` | Qwen series, supports `thinking_enable` || `deepseek` | `DEEPSEEK_API_KEY` | Supports only `call` / `multiagent` (no multimodal) || `gemini` | `GEMINI_API_KEY` | Gemini models, supports `thinking_budget` |@@ -99,6 +105,7 @@ Set the environment variables for the providers you want to test:```bashexport OPENAI_API_KEY="sk-..."export ANTHROPIC_API_KEY="sk-ant-..."+export MINIMAX_API_KEY="sk-..."export DASHSCOPE_API_KEY="sk-..."export DEEPSEEK_API_KEY="sk-..."export GEMINI_API_KEY="AIza..."@@ -220,7 +227,8 @@ Each script typically defines two or more async functions:- `example_structured_output()` – force a Pydantic-validated JSON output (in `_call.py` variants, uses a thinking-enabled model)- `example_image_url()` / `example_image_local_path()` / `example_image_base64()` – image + text input (in `_multimodal.py` variants)- `example_audio()` – audio input (e.g. `openai_chat_multimodal.py`, `dashscope_multimodal.py`)-- `example_video()` – video input (e.g. `dashscope_multimodal.py`)+- `example_video()` / `example_video_url()` – video input (e.g.+ `dashscope_multimodal.py`, `minimax_multimodal.py`)---diff --git a/scripts/model_examples/minimax_call.py b/scripts/model_examples/minimax_call.pynew file mode 100644index 000000000..dc9d1a5c1--- /dev/null+++ b/scripts/model_examples/minimax_call.py@@ -0,0 +1,191 @@+# -*- coding: utf-8 -*-+"""Examples of MiniMax chat model calls.++The MiniMax M-series chat models (e.g. ``MiniMax-M3``) are exposed via+MiniMax's officially recommended Anthropic-compatible API, so the+controls and outputs match+``scripts/model_examples/anthropic_call.py``.+"""++import asyncio+import json+import os++from pydantic import BaseModel, Field++from _utils import stream_and_collect+from agentscope.credential import MiniMaxCredential+from agentscope.message import (+ Msg,+ TextBlock,+ ToolCallBlock,+ ToolResultBlock,+ ToolResultState,+)+from agentscope.model import MiniMaxChatModel+from agentscope.tool import Toolkit, ToolChoice, FunctionTool+++# ---------------------------------------------------------------------------+# Example 1: Simple user message (streaming, with extended thinking)+# ---------------------------------------------------------------------------+++async def example_simple_call() -> None:+ """Call MiniMax-M3 with a simple text message and extended thinking."""+ model = MiniMaxChatModel(+ credential=MiniMaxCredential(+ api_key=os.environ["MINIMAX_API_KEY"],+ ),+ model="MiniMax-M3",+ stream=True,+ parameters=MiniMaxChatModel.Parameters(+ thinking_enable=True,+ ),+ )++ msgs = [+ Msg(+ name="user",+ content=[TextBlock(text="What is 1 + 1? Answer briefly.")],+ role="user",+ ),+ ]++ print("=== Simple Call ===")+ await stream_and_collect(await model(msgs))+++# ---------------------------------------------------------------------------+# Example 2: Tool calling (streaming)+# ---------------------------------------------------------------------------+++def get_weather(city: str) -> str:+ """Get the current weather for a city.++ Args:+ city: The city name to query the weather for.++ Returns:+ A description of the current weather.+ """+ return f"The weather in {city} is sunny and 25°C."+++async def example_tool_call() -> None:+ """Call MiniMax-M3 with tool calling enabled."""+ toolkit = Toolkit(tools=[FunctionTool(get_weather)])+ tools = await toolkit.get_tool_schemas()++ model = MiniMaxChatModel(+ credential=MiniMaxCredential(+ api_key=os.environ["MINIMAX_API_KEY"],+ ),+ model="MiniMax-M3",+ stream=True,+ parameters=MiniMaxChatModel.Parameters(+ thinking_enable=True,+ ),+ )++ msgs = [+ Msg(+ name="user",+ content=[TextBlock(text="What is the weather in Shanghai?")],+ role="user",+ ),+ ]++ print("=== Tool Call - Round 1 ===")+ response = await stream_and_collect(+ await model(msgs, tools=tools, tool_choice=ToolChoice(mode="auto")),+ )+ print(response)++ tool_calls = [b for b in response.content if isinstance(b, ToolCallBlock)]+ if tool_calls:+ tool_result_blocks = []+ for tool_call in tool_calls:+ args = json.loads(tool_call.input)+ result = get_weather(**args)+ tool_result_blocks.append(+ ToolResultBlock(+ id=tool_call.id,+ name=tool_call.name,+ output=result,+ state=ToolResultState.SUCCESS,+ ),+ )++ assistant_msg = Msg(+ name="assistant",+ content=response.content,+ role="assistant",+ )+ tool_result_msg = Msg(+ name="tool",+ content=tool_result_blocks,+ role="assistant",+ )+ msgs = msgs + [assistant_msg, tool_result_msg]++ print("=== Tool Call - Round 2 (Final) ===")+ await stream_and_collect(await model(msgs))+++# ---------------------------------------------------------------------------+# Example 3: Structured output+# ---------------------------------------------------------------------------+++class MathSolution(BaseModel):+ """Structured solution to a math problem."""++ problem: str = Field(description="The original problem statement")+ answer: float = Field(description="The final numeric answer")+ steps: list[str] = Field(+ description="Step-by-step reasoning leading to the answer",+ )+++async def example_structured_output() -> None:+ """Call MiniMax-M3 and force a structured (JSON) output."""+ model = MiniMaxChatModel(+ credential=MiniMaxCredential(+ api_key=os.environ["MINIMAX_API_KEY"],+ ),+ model="MiniMax-M3",+ stream=True,+ parameters=MiniMaxChatModel.Parameters(+ thinking_enable=True,+ ),+ )++ msgs = [+ Msg(+ name="user",+ content=[+ TextBlock(+ text=(+ "Solve this: A train travels at 60 km/h for "+ "2.5 hours. How far does it travel in km?"+ ),+ ),+ ],+ role="user",+ ),+ ]++ print("=== Structured Output ===")+ response = await model.generate_structured_output(+ msgs,+ structured_model=MathSolution,+ )+ print(response.content)+++if __name__ == "__main__":+ asyncio.run(example_simple_call())+ asyncio.run(example_tool_call())+ asyncio.run(example_structured_output())diff --git a/scripts/model_examples/minimax_multiagent.py b/scripts/model_examples/minimax_multiagent.pynew file mode 100644index 000000000..5efba5f11--- /dev/null+++ b/scripts/model_examples/minimax_multiagent.py@@ -0,0 +1,108 @@+# -*- coding: utf-8 -*-+"""Example of MiniMax chat model calls with MiniMaxMultiAgentFormatter.++The multi-agent formatter wraps prior conversation history in+``<history></history>`` tags, enabling MiniMax-M3 to handle multi-agent+conversations where more than one non-user agent is involved.+"""++import asyncio+import os++from _utils import stream_and_collect+from agentscope.credential import MiniMaxCredential+from agentscope.formatter import MiniMaxMultiAgentFormatter+from agentscope.message import Msg, TextBlock+from agentscope.model import MiniMaxChatModel+++async def example_multiagent() -> None:+ """Simulate a multi-agent conversation and let MiniMax-M3 summarize.++ Alice and Bob discuss the weather, then a moderator (the model) is asked+ to summarize the conversation.+ """+ formatter = MiniMaxMultiAgentFormatter()++ model = MiniMaxChatModel(+ credential=MiniMaxCredential(+ api_key=os.environ["MINIMAX_API_KEY"],+ ),+ model="MiniMax-M3",+ stream=True,+ parameters=MiniMaxChatModel.Parameters(+ thinking_enable=True,+ ),+ formatter=formatter,+ )++ msgs = [+ Msg(+ name="system",+ content=[+ TextBlock(+ text=(+ "You are a helpful moderator. Summarize the "+ "conversation."+ ),+ ),+ ],+ role="system",+ ),+ Msg(+ name="alice",+ content=[+ TextBlock(+ text="Hi Bob! What do you think about the weather today?",+ ),+ ],+ role="user",+ ),+ Msg(+ name="bob",+ content=[+ TextBlock(+ text=(+ "It's quite sunny and warm, Alice. Perfect for a "+ "walk!"+ ),+ ),+ ],+ role="assistant",+ ),+ Msg(+ name="alice",+ content=[+ TextBlock(text="Agreed! I might head to the park later."),+ ],+ role="user",+ ),+ Msg(+ name="bob",+ content=[+ TextBlock(+ text="Great idea. I'll join you if I finish work early.",+ ),+ ],+ role="assistant",+ ),+ Msg(+ name="moderator",+ content=[+ TextBlock(+ text=(+ "Please summarize the conversation above in one "+ "sentence."+ ),+ ),+ ],+ role="user",+ ),+ ]++ print("=== Multi-Agent Formatter Call ===")+ await stream_and_collect(await model(msgs))+++if __name__ == "__main__":+ asyncio.run(example_multiagent())diff --git a/scripts/model_examples/minimax_multiagent_multimodal.py b/scripts/model_examples/minimax_multiagent_multimodal.pynew file mode 100644index 000000000..e868ab60a--- /dev/null+++ b/scripts/model_examples/minimax_multiagent_multimodal.py@@ -0,0 +1,98 @@+# -*- coding: utf-8 -*-+"""Example of MiniMax chat model calls with MultiAgentFormatter and image+input.++Demonstrates combining MiniMaxMultiAgentFormatter with multimodal (vision)+content: Alice shares an image in a multi-agent conversation, and the model+is asked to summarize what everyone is looking at.+"""++import asyncio+import os++from _utils import stream_and_collect+from agentscope.credential import MiniMaxCredential+from agentscope.formatter import MiniMaxMultiAgentFormatter+from agentscope.message import Msg, TextBlock, DataBlock, URLSource+from agentscope.model import MiniMaxChatModel++TEST_IMAGE_URL = (+ "https://help-static-aliyun-doc.aliyuncs.com/file-manage"+ "-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"+)+++async def example_multiagent_image_url() -> None:+ """Multi-agent conversation where Alice shares an image for the group."""+ formatter = MiniMaxMultiAgentFormatter()++ model = MiniMaxChatModel(+ credential=MiniMaxCredential(+ api_key=os.environ["MINIMAX_API_KEY"],+ ),+ model="MiniMax-M3",+ stream=True,+ parameters=MiniMaxChatModel.Parameters(+ thinking_enable=True,+ ),+ formatter=formatter,+ )++ image_block = DataBlock(+ source=URLSource(url=TEST_IMAGE_URL, media_type="image/jpeg"),+ )++ msgs = [+ Msg(+ name="system",+ content=[+ TextBlock(+ text=(+ "You are a helpful moderator in a group chat. "+ "Summarize what the image shows and what the "+ "participants said."+ ),+ ),+ ],+ role="system",+ ),+ Msg(+ name="alice",+ content=[+ TextBlock(+ text="Hey everyone, look at this cute photo I took!",+ ),+ image_block,+ ],+ role="user",+ ),+ Msg(+ name="bob",+ content=[+ TextBlock(text="Aww, that's adorable! Where was this taken?"),+ ],+ role="assistant",+ ),+ Msg(+ name="alice",+ content=[TextBlock(text="At the local park yesterday.")],+ role="user",+ ),+ Msg(+ name="moderator",+ content=[+ TextBlock(+ text="Please summarize the image content and the "+ "conversation in one paragraph.",+ ),+ ],+ role="user",+ ),+ ]++ print("=== Multi-Agent + Multimodal Call ===")+ await stream_and_collect(await model(msgs))+++if __name__ == "__main__":+ asyncio.run(example_multiagent_image_url())diff --git a/scripts/model_examples/minimax_multimodal.py b/scripts/model_examples/minimax_multimodal.pynew file mode 100644index 000000000..a0e54ea44--- /dev/null+++ b/scripts/model_examples/minimax_multimodal.py@@ -0,0 +1,185 @@+# -*- coding: utf-8 -*-+"""Example of MiniMax chat model image and video calls using+DataBlock.++MiniMax-M3 accepts image and video input on its Anthropic-compatible+endpoint.+"""++import asyncio+import base64+import os+from pathlib import Path++from _utils import stream_and_collect+from agentscope.credential import MiniMaxCredential+from agentscope.message import (+ Msg,+ TextBlock,+ DataBlock,+ URLSource,+ Base64Source,+)+from agentscope.model import MiniMaxChatModel++# A publicly accessible test image (dog and girl photo)+TEST_IMAGE_URL = (+ "https://help-static-aliyun-doc.aliyuncs.com/file-manage"+ "-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"+)++# A publicly accessible test video from the MiniMax API documentation+TEST_VIDEO_URL = (+ "https://filecdn.minimax.chat/public/"+ "ee8c1648-21f1-41b7-8397-65022d22ffe5.mp4"+)+++def _build_model() -> MiniMaxChatModel:+ """Build and return a MiniMaxChatModel instance."""+ return MiniMaxChatModel(+ credential=MiniMaxCredential(+ api_key=os.environ["MINIMAX_API_KEY"],+ ),+ model="MiniMax-M3",+ stream=True,+ parameters=MiniMaxChatModel.Parameters(+ thinking_enable=True,+ ),+ )+++async def example_image_url() -> None:+ """Call MiniMax-M3 with an image URL and ask what is in the image."""+ model = _build_model()++ image_block = DataBlock(+ source=URLSource(+ url=TEST_IMAGE_URL,+ media_type="image/jpeg",+ ),+ )++ msgs = [+ Msg(+ name="user",+ content=[+ TextBlock(+ text="What animal is in this image? Describe it briefly.",+ ),+ image_block,+ ],+ role="user",+ ),+ ]++ print("=== Multimodal Call (Image URL) ===")+ await stream_and_collect(await model(msgs))+++async def example_image_local_path() -> None:+ """Call MiniMax-M3 with a local image using a ``file://`` URL.++ The formatter automatically reads the file and converts it to base64.+ """+ model = _build_model()++ abs_path = str(Path(__file__).parent / "test.jpeg")+ image_block = DataBlock(+ source=URLSource(+ url=f"file://{abs_path}",+ media_type="image/jpeg",+ ),+ )++ msgs = [+ Msg(+ name="user",+ content=[+ TextBlock(+ text=(+ "What is happening in this image? Describe it "+ "briefly."+ ),+ ),+ image_block,+ ],+ role="user",+ ),+ ]++ print("=== Local Path Call (file://) ===")+ await stream_and_collect(await model(msgs))+++async def example_image_base64() -> None:+ """Call MiniMax-M3 with a local image using explicit base64 encoding.++ Use ``Base64Source`` when you already have the binary data in memory or+ want full control over the encoding step.+ """+ model = _build_model()++ with open(Path(__file__).parent / "test.jpeg", "rb") as f:+ data = base64.b64encode(f.read()).decode("utf-8")++ image_block = DataBlock(+ source=Base64Source(+ data=data,+ media_type="image/jpeg",+ ),+ )++ msgs = [+ Msg(+ name="user",+ content=[+ TextBlock(+ text=(+ "What is happening in this image? Describe it "+ "briefly."+ ),+ ),+ image_block,+ ],+ role="user",+ ),+ ]++ print("=== Explicit Base64 Call ===")+ await stream_and_collect(await model(msgs))+++async def example_video_url() -> None:+ """Call MiniMax-M3 with a public video URL."""+ model = _build_model()++ video_block = DataBlock(+ source=URLSource(+ url=TEST_VIDEO_URL,+ media_type="video/mp4",+ ),+ )++ msgs = [+ Msg(+ name="user",+ content=[+ TextBlock(+ text="What is happening in this video?",+ ),+ video_block,+ ],+ role="user",+ ),+ ]++ print("=== Multimodal Call (Video URL) ===")+ await stream_and_collect(await model(msgs))+++if __name__ == "__main__":+ asyncio.run(example_image_url())+ asyncio.run(example_image_local_path())+ asyncio.run(example_image_base64())+ asyncio.run(example_video_url())diff --git a/scripts/model_examples/run_tests.py b/scripts/model_examples/run_tests.pyindex 8ad973e00..ba4023e7e 100644--- a/scripts/model_examples/run_tests.py+++ b/scripts/model_examples/run_tests.py@@ -125,6 +125,18 @@ ALL_PROVIDERS: list[Provider] = [],description="Anthropic Claude models",),+ Provider(+ name="minimax",+ env_var="MINIMAX_API_KEY",+ file_prefix="minimax",+ supported_tests=[+ "call",+ "multiagent",+ "multimodal",+ "multiagent_multimodal",+ ],+ description="MiniMax M-series models",+ ),Provider(name="dashscope",env_var="DASHSCOPE_API_KEY",diff --git a/src/agentscope/credential/__init__.py b/src/agentscope/credential/__init__.pyindex 83386b747..6c9a58412 100644--- a/src/agentscope/credential/__init__.py+++ b/src/agentscope/credential/__init__.py@@ -6,6 +6,7 @@ from ._anthropic import AnthropicCredentialfrom ._dashscope import DashScopeCredentialfrom ._deepseek import DeepSeekCredentialfrom ._gemini import GeminiCredential+from ._minimax import MiniMaxCredentialfrom ._moonshot import MoonshotCredentialfrom ._ollama import OllamaCredentialfrom ._openai import OpenAICredential@@ -21,6 +22,7 @@ __all__ = ["DashScopeCredential","DeepSeekCredential","GeminiCredential",+ "MiniMaxCredential","MoonshotCredential","OllamaCredential","OpenAICredential",diff --git a/src/agentscope/credential/_factory.py b/src/agentscope/credential/_factory.pyindex 3f758650d..1ed40c999 100644--- a/src/agentscope/credential/_factory.py+++ b/src/agentscope/credential/_factory.py@@ -8,6 +8,7 @@ from ._anthropic import AnthropicCredentialfrom ._dashscope import DashScopeCredentialfrom ._deepseek import DeepSeekCredentialfrom ._gemini import GeminiCredential+from ._minimax import MiniMaxCredentialfrom ._moonshot import MoonshotCredentialfrom ._ollama import OllamaCredentialfrom ._openai import OpenAICredential@@ -39,6 +40,7 @@ class CredentialFactory:DashScopeCredential,DeepSeekCredential,GeminiCredential,+ MiniMaxCredential,MoonshotCredential,OllamaCredential,OpenAICredential,diff --git a/src/agentscope/credential/_minimax.py b/src/agentscope/credential/_minimax.pynew file mode 100644index 000000000..7785648ac--- /dev/null+++ b/src/agentscope/credential/_minimax.py@@ -0,0 +1,42 @@+# -*- coding: utf-8 -*-+"""The MiniMax credential."""++from typing import Literal, Type, TYPE_CHECKING++from pydantic import Field, SecretStr++from ._base import CredentialBase++if TYPE_CHECKING:+ from ..model import ChatModelBase++# MiniMax's recommended Anthropic-compatible endpoint (international site)+_MINIMAX_BASE_URL = "https://api.minimax.io/anthropic"+++class MiniMaxCredential(CredentialBase):+ """The MiniMax credential model."""++ type: Literal["minimax_credential"] = "minimax_credential"+ """The credential type."""++ api_key: SecretStr = Field(+ description="The MiniMax API key.",+ )+ """The API key."""++ base_url: str = Field(+ default=_MINIMAX_BASE_URL,+ description=(+ "The base URL for the MiniMax Anthropic-compatible API, use "+ "``https://api.minimax.cn/anthropic`` for China mainland."+ ),+ )+ """The base URL for the MiniMax API."""++ @classmethod+ def get_chat_model_class(cls) -> Type["ChatModelBase"]:+ """Return the MiniMaxChatModel class."""+ from ..model import MiniMaxChatModel++ return MiniMaxChatModeldiff --git a/src/agentscope/formatter/__init__.py b/src/agentscope/formatter/__init__.pyindex 7320a2fa3..de3e36d21 100644--- a/src/agentscope/formatter/__init__.py+++ b/src/agentscope/formatter/__init__.py@@ -30,6 +30,10 @@ from ._openai_response_formatter import (OpenAIResponseFormatter,OpenAIResponseMultiAgentFormatter,)+from ._minimax_formatter import (+ MiniMaxChatFormatter,+ MiniMaxMultiAgentFormatter,+)from ._moonshot_formatter import (MoonshotChatFormatter,MoonshotMultiAgentFormatter,@@ -59,6 +63,8 @@ __all__ = ["DeepSeekMultiAgentFormatter","OpenAIResponseFormatter","OpenAIResponseMultiAgentFormatter",+ "MiniMaxChatFormatter",+ "MiniMaxMultiAgentFormatter","MoonshotChatFormatter","MoonshotMultiAgentFormatter","XAIChatFormatter",diff --git a/src/agentscope/formatter/_minimax_formatter.py b/src/agentscope/formatter/_minimax_formatter.pynew file mode 100644index 000000000..944b3f776--- /dev/null+++ b/src/agentscope/formatter/_minimax_formatter.py@@ -0,0 +1,62 @@+# -*- coding: utf-8 -*-+"""The MiniMax formatters, i.e. the Anthropic formatters plus video input."""+import fnmatch+from typing import Any++from pydantic import Field++from ._anthropic_formatter import (+ AnthropicChatFormatter,+ AnthropicMultiAgentFormatter,+)+from ..message import DataBlock+++class MiniMaxChatFormatter(AnthropicChatFormatter):+ """The MiniMax formatter for chatbot scenario."""++ input_types: list[str] = Field(+ default_factory=lambda: ["text/plain", "image/*", "video/*"],+ description=(+ "The supported input types. "+ 'Defaults to ``["text/plain", "image/*", "video/*"]``.'+ ),+ )++ def _format_anthropic_data_block(+ self,+ block: DataBlock,+ ) -> dict[str, Any] | None:+ """Format video blocks natively and delegate other media."""+ media_type = block.source.media_type+ if media_type.startswith("video/") and any(+ fnmatch.fnmatch(media_type, _)+ for _ in self.supported_input_media_types+ ):+ return self._format_source(block.source, "video")+ return super()._format_anthropic_data_block(block)+++class MiniMaxMultiAgentFormatter(AnthropicMultiAgentFormatter):+ """The MiniMax formatter for multi-agent conversations."""++ input_types: list[str] = Field(+ default_factory=lambda: ["text/plain", "image/*", "video/*"],+ description=(+ "The supported input types. "+ 'Defaults to ``["text/plain", "image/*", "video/*"]``.'+ ),+ )++ def _format_anthropic_data_block(+ self,+ block: DataBlock,+ ) -> dict[str, Any] | None:+ """Format video blocks natively and delegate other media."""+ media_type = block.source.media_type+ if media_type.startswith("video/") and any(+ fnmatch.fnmatch(media_type, _)+ for _ in self.supported_input_media_types+ ):+ return self._format_source(block.source, "video")+ return super()._format_anthropic_data_block(block)diff --git a/src/agentscope/model/__init__.py b/src/agentscope/model/__init__.pyindex c474a7367..f566a9e3f 100644--- a/src/agentscope/model/__init__.py+++ b/src/agentscope/model/__init__.py@@ -9,6 +9,7 @@ from ._anthropic import AnthropicChatModelfrom ._dashscope import DashScopeChatModelfrom ._deepseek import DeepSeekChatModelfrom ._gemini import GeminiChatModel+from ._minimax import MiniMaxChatModelfrom ._ollama import OllamaChatModelfrom ._openai_chat import OpenAIChatModelfrom ._xai import XAIChatModel@@ -27,6 +28,7 @@ __all__ = ["DashScopeChatModel","DeepSeekChatModel","GeminiChatModel",+ "MiniMaxChatModel","OllamaChatModel","OpenAIChatModel","XAIChatModel",diff --git a/src/agentscope/model/_anthropic/_model.py b/src/agentscope/model/_anthropic/_model.pyindex 354c6d686..28093009e 100644--- a/src/agentscope/model/_anthropic/_model.py+++ b/src/agentscope/model/_anthropic/_model.py@@ -184,6 +184,36 @@ class AnthropicChatModel(ChatModelBase):return self.parameters.thinking_modereturn "enabled" if self.parameters.thinking_enable else None+ def _build_thinking_config(+ self,+ max_tokens: int,+ ) -> tuple[dict[str, Any] | None, int]:+ """Build the provider-specific thinking configuration."""+ mode = self._thinking_mode()+ if mode is None:+ return None, max_tokens++ thinking: dict[str, Any] = {"type": mode}+ if mode == "enabled":+ # Anthropic requires max_tokens > budget_tokens strictly.+ budget = self.parameters.thinking_budget or (max_tokens // 2)+ if budget >= max_tokens:+ # Auto-expand max_tokens to satisfy the inequality.+ max_tokens = budget + 1024+ thinking["budget_tokens"] = budget++ # ``display`` is invalid alongside ``type: "disabled"``.+ if mode != "disabled" and self.parameters.thinking_display:+ thinking["display"] = self.parameters.thinking_display++ return thinking, max_tokens++ def _build_output_config(self) -> dict[str, Any] | None:+ """Build the provider-specific output configuration."""+ if self.parameters.reasoning_effort:+ return {"effort": self.parameters.reasoning_effort}+ return None+async def _call_api(self,model_name: str,@@ -226,27 +256,20 @@ class AnthropicChatModel(ChatModelBase):**generate_kwargs,}- mode = self._thinking_mode()- if mode is not None and "thinking" not in kwargs:- thinking: dict[str, Any] = {"type": mode}- if mode == "enabled":- # Anthropic requires max_tokens > budget_tokens strictly.- budget = self.parameters.thinking_budget or (max_tokens // 2)- if budget >= max_tokens:- # Auto-expand max_tokens to satisfy the inequality.- max_tokens = budget + 1024- kwargs["max_tokens"] = max_tokens- thinking["budget_tokens"] = budget- # ``display`` is invalid alongside ``type: "disabled"``.- if mode != "disabled" and self.parameters.thinking_display:- thinking["display"] = self.parameters.thinking_display- kwargs["thinking"] = thinking+ if "thinking" not in kwargs:+ thinking, expanded_max_tokens = self._build_thinking_config(+ max_tokens,+ )+ if thinking is not None:+ kwargs["thinking"] = thinking+ if expanded_max_tokens != max_tokens:+ kwargs["max_tokens"] = expanded_max_tokens# Effort travels inside ``output_config``, not as a top-level field.- if self.parameters.reasoning_effort and "output_config" not in kwargs:- kwargs["output_config"] = {- "effort": self.parameters.reasoning_effort,- }+ if "output_config" not in kwargs:+ output_config = self._build_output_config()+ if output_config is not None:+ kwargs["output_config"] = output_configfmt_tools, fmt_tool_choice = self._format_tools(tools, tool_choice)if fmt_tools:diff --git a/src/agentscope/model/_minimax/__init__.py b/src/agentscope/model/_minimax/__init__.pynew file mode 100644index 000000000..a2972a120--- /dev/null+++ b/src/agentscope/model/_minimax/__init__.py@@ -0,0 +1,8 @@+# -*- coding: utf-8 -*-+"""The MiniMax LLM API modules."""++from ._model import MiniMaxChatModel++__all__ = [+ "MiniMaxChatModel",+]diff --git a/src/agentscope/model/_minimax/_model.py b/src/agentscope/model/_minimax/_model.pynew file mode 100644index 000000000..8d8ff29e7--- /dev/null+++ b/src/agentscope/model/_minimax/_model.py@@ -0,0 +1,96 @@+# -*- coding: utf-8 -*-+"""The MiniMax chat model implementation."""++from typing import Any, Literal++from pydantic import BaseModel, Field++from .._anthropic import AnthropicChatModel+from ...credential import MiniMaxCredential+from ...formatter import FormatterBase, MiniMaxChatFormatter+++class MiniMaxChatModel(AnthropicChatModel):+ """Chat model for MiniMax's Anthropic-compatible API."""++ type: Literal["minimax_chat"] = "minimax_chat"+ """The type of the chat model."""++ class Parameters(BaseModel):+ """The parameters for the MiniMax chat model."""++ max_tokens: int | None = Field(+ default=None,+ title="Max Tokens",+ description=(+ "The maximum number of tokens to generate in the chat "+ "completion."+ ),+ gt=0,+ )++ thinking_enable: bool = Field(+ default=False,+ title="Thinking",+ description="Whether to enable adaptive thinking.",+ )++ def __init__(+ self,+ credential: MiniMaxCredential,+ model: str,+ parameters: "MiniMaxChatModel.Parameters | None" = None,+ stream: bool = True,+ max_retries: int = 3,+ retry_delay: float = 1.0,+ context_size: int = 1_000_000,+ formatter: FormatterBase | None = None,+ client_kwargs: dict[str, Any] | None = None,+ ) -> None:+ """Initialize the MiniMax chat model.++ Args:+ credential (`MiniMaxCredential`):+ The credential used to authenticate MiniMax API calls.+ model (`str`):+ The MiniMax model name, e.g. ``MiniMax-M3``.+ parameters (`MiniMaxChatModel.Parameters | None`, defaults to \+ `None`):+ The MiniMax API parameters.+ stream (`bool`, defaults to `True`):+ Whether to enable streaming output.+ max_retries (`int`, defaults to `3`):+ The maximum number of retries for the MiniMax API.+ retry_delay (`float`, defaults to `1.0`):+ Seconds to sleep between retry attempts.+ context_size (`int`, defaults to `1000000`):+ The model context size used for context compression.+ formatter (`FormatterBase | None`, defaults to `None`):+ The formatter used to serialize messages.+ client_kwargs (`dict[str, Any] | None`, defaults to `None`):+ Extra arguments forwarded to ``anthropic.AsyncAnthropic``.+ """+ super().__init__(+ credential=credential,+ model=model,+ parameters=parameters or self.Parameters(),+ stream=stream,+ max_retries=max_retries,+ retry_delay=retry_delay,+ context_size=context_size,+ formatter=formatter or MiniMaxChatFormatter(),+ client_kwargs=client_kwargs,+ )++ def _build_thinking_config(+ self,+ max_tokens: int,+ ) -> tuple[dict[str, Any] | None, int]:+ """MiniMax only accepts adaptive thinking, without a token budget."""+ if self.parameters.thinking_enable:+ return {"type": "adaptive"}, max_tokens+ return None, max_tokens++ def _build_output_config(self) -> None:+ """MiniMax does not support Anthropic's output configuration."""+ return Nonediff --git a/src/agentscope/model/_minimax/_models/MiniMax-M2.7-highspeed.yaml b/src/agentscope/model/_minimax/_models/MiniMax-M2.7-highspeed.yamlnew file mode 100644index 000000000..5a9947618--- /dev/null+++ b/src/agentscope/model/_minimax/_models/MiniMax-M2.7-highspeed.yaml@@ -0,0 +1,17 @@+name: MiniMax-M2.7-highspeed+label: MiniMax M2.7 Highspeed+status: active++input_types:+ - text/plain+ - application/x-thinking++output_types:+ - text/plain+ - application/x-thinking++context_size: 204800+output_size: 65536++parameter_overrides:+ max_tokens: {"maximum": 204800}diff --git a/src/agentscope/model/_minimax/_models/MiniMax-M2.7.yaml b/src/agentscope/model/_minimax/_models/MiniMax-M2.7.yamlnew file mode 100644index 000000000..49cdb9c69--- /dev/null+++ b/src/agentscope/model/_minimax/_models/MiniMax-M2.7.yaml@@ -0,0 +1,17 @@+name: MiniMax-M2.7+label: MiniMax M2.7+status: active++input_types:+ - text/plain+ - application/x-thinking++output_types:+ - text/plain+ - application/x-thinking++context_size: 204800+output_size: 65536++parameter_overrides:+ max_tokens: {"maximum": 204800}diff --git a/src/agentscope/model/_minimax/_models/MiniMax-M3.yaml b/src/agentscope/model/_minimax/_models/MiniMax-M3.yamlnew file mode 100644index 000000000..2d1d088b5--- /dev/null+++ b/src/agentscope/model/_minimax/_models/MiniMax-M3.yaml@@ -0,0 +1,24 @@+name: MiniMax-M3+label: MiniMax M3+status: active++input_types:+ - text/plain+ - application/x-thinking+ - image/jpeg+ - image/png+ - image/gif+ - image/webp+ - video/mp4+ - video/x-msvideo+ - video/x-matroska++output_types:+ - text/plain+ - application/x-thinking++context_size: 1000000+output_size: 131072++parameter_overrides:+ max_tokens: {"maximum": 524288}diff --git a/tests/model_minimax_test.py b/tests/model_minimax_test.pynew file mode 100644index 000000000..e4389385e--- /dev/null+++ b/tests/model_minimax_test.py@@ -0,0 +1,177 @@+# -*- coding: utf-8 -*-+"""Unit tests for the MiniMax chat model and formatter."""+from unittest import IsolatedAsyncioTestCase+from unittest.mock import AsyncMock, MagicMock++from agentscope.credential import MiniMaxCredential+from agentscope.formatter import MiniMaxChatFormatter+from agentscope.message import (+ Base64Source,+ DataBlock,+ Msg,+ TextBlock,+ URLSource,+)+from agentscope.model import MiniMaxChatModel+++class MiniMaxTest(IsolatedAsyncioTestCase):+ """Tests for the MiniMax-specific behavior."""++ async def test_request_kwargs(self) -> None:+ """Thinking is sent as adaptive without budget or output config."""+ model = MiniMaxChatModel(+ credential=MiniMaxCredential(api_key="test"),+ model="MiniMax-M3",+ stream=False,+ )+ response = MagicMock(id="msg-1", content=[])+ response.usage = MagicMock(input_tokens=1, output_tokens=1)+ model.client = MagicMock()+ model.client.messages.create = AsyncMock(return_value=response)+ msgs = [Msg(name="user", content=[TextBlock(text="Hi")], role="user")]++ await model(msgs)+ model.parameters.thinking_enable = True+ await model(msgs)++ self.assertListEqual(+ [_.kwargs for _ in model.client.messages.create.await_args_list],+ [+ {+ "model": "MiniMax-M3",+ "max_tokens": 8192,+ "stream": False,+ "messages": [+ {+ "role": "user",+ "content": [{"type": "text", "text": "Hi"}],+ },+ ],+ },+ {+ "model": "MiniMax-M3",+ "max_tokens": 8192,+ "stream": False,+ "thinking": {"type": "adaptive"},+ "messages": [+ {+ "role": "user",+ "content": [{"type": "text", "text": "Hi"}],+ },+ ],+ },+ ],+ )++ async def test_format_video(self) -> None:+ """Supported videos become video blocks, unsupported ones skipped."""+ formatter = MiniMaxChatFormatter(+ input_types=["text/plain", "image/*", "video/mp4"],+ )+ msgs = [+ Msg(+ name="user",+ content=[+ DataBlock(+ source=Base64Source(+ data="AAAA",+ media_type="video/mp4",+ ),+ ),+ DataBlock(+ source=URLSource(+ url="https://example.com/a.mkv",+ media_type="video/x-matroska",+ ),+ ),+ DataBlock(+ source=Base64Source(+ data="BBBB",+ media_type="image/png",+ ),+ ),+ ],+ role="user",+ ),+ ]++ self.assertListEqual(+ await formatter.format(msgs),+ [+ {+ "role": "user",+ "content": [+ {+ "type": "video",+ "source": {+ "type": "base64",+ "media_type": "video/mp4",+ "data": "AAAA",+ },+ },+ {+ "type": "image",+ "source": {+ "type": "base64",+ "media_type": "image/png",+ "data": "BBBB",+ },+ },+ ],+ },+ ],+ )++ def test_model_cards(self) -> None:+ """The MiniMax model cards carry the documented limits."""+ cards = sorted(MiniMaxChatModel.list_models(), key=lambda _: _.name)++ self.assertListEqual(+ [+ {+ "name": _.name,+ "context_size": _.context_size,+ "output_size": _.output_size,+ "input_types": _.input_types,+ }+ for _ in cards+ ],+ [+ {+ "name": "MiniMax-M2.7",+ "context_size": 204800,+ "output_size": 65536,+ "input_types": ["text/plain", "application/x-thinking"],+ },+ {+ "name": "MiniMax-M2.7-highspeed",+ "context_size": 204800,+ "output_size": 65536,+ "input_types": ["text/plain", "application/x-thinking"],+ },+ {+ "name": "MiniMax-M3",+ "context_size": 1000000,+ "output_size": 131072,+ "input_types": [+ "text/plain",+ "application/x-thinking",+ "image/jpeg",+ "image/png",+ "image/gif",+ "image/webp",+ "video/mp4",+ "video/x-msvideo",+ "video/x-matroska",+ ],+ },+ ],+ )++ def test_default_base_url(self) -> None:+ """The credential defaults to the Anthropic-compatible endpoint."""+ self.assertEqual(+ MiniMaxCredential(api_key="test").base_url,+ "https://api.minimax.io/anthropic",+ )