Run this model with HF Jobs
Run MiniMaxAI/MiniMax-M2 on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/MiniMaxAI/MiniMax-M2. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/MiniMaxAI/MiniMax-M2 on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/MiniMaxAI/MiniMax-M2. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/MiniMaxAI/MiniMax-M2. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use MiniMaxAI/MiniMax-M2 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use MiniMaxAI/MiniMax-M2 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="MiniMaxAI/MiniMax-M2", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("MiniMaxAI/MiniMax-M2", trust_remote_code=True) model = AutoModelForCausalLM.from_pretrained("MiniMaxAI/MiniMax-M2", trust_remote_code=True, device_map="auto") messages = [ {"role": "user", "content": "Who are you?"}, ] inputs = tokenizer.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=256) print(tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use MiniMaxAI/MiniMax-M2 with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "MiniMaxAI/MiniMax-M2" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "MiniMaxAI/MiniMax-M2", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/MiniMaxAI/MiniMax-M2
- SGLang
How to use MiniMaxAI/MiniMax-M2 with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "MiniMaxAI/MiniMax-M2" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "MiniMaxAI/MiniMax-M2", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "MiniMaxAI/MiniMax-M2" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "MiniMaxAI/MiniMax-M2", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use MiniMaxAI/MiniMax-M2 with Docker Model Runner:
docker model run hf.co/MiniMaxAI/MiniMax-M2
Delete docs/function_call_guide_en.md
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482# MiniMax-M2 Function Call Guide
## Introduction
The MiniMax-M2 model supports function calling capabilities, enabling the model to identify when external functions need to be called and output function call parameters in a structured format. This document provides detailed instructions on how to use the function calling features of MiniMax-M2.
## Basic Example
The following Python script implements a weather query function call example based on the OpenAI SDK:
```pythonfrom openai import OpenAIimport json
client = OpenAI(base_url="http://localhost:8000/v1", api_key="dummy")
def get_weather(location: str, unit: str): return f"Getting the weather for {location} in {unit}..."
tool_functions = {"get_weather": get_weather}
tools = [{ "type": "function", "function": { "name": "get_weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": {"type": "string", "description": "City and state, e.g., 'San Francisco, CA'"}, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]} }, "required": ["location", "unit"] } }}]
response = client.chat.completions.create( model=client.models.list().data[0].id, messages=[{"role": "user", "content": "What's the weather like in San Francisco? use celsius."}], tools=tools, tool_choice="auto")
print(response)
tool_call = response.choices[0].message.tool_calls[0].functionprint(f"Function called: {tool_call.name}")print(f"Arguments: {tool_call.arguments}")print(f"Result: {get_weather(**json.loads(tool_call.arguments))}")```
**Output Example:**```Function called: get_weatherArguments: {"location": "San Francisco, CA", "unit": "celsius"}Result: Getting the weather for San Francisco, CA in celsius...```
## Manually Parsing Model Output
If you cannot use the built-in parser of inference engines that support MiniMax-M2, or need to use other inference frameworks (such as transformers, TGI, etc.), you can manually parse the model's raw output using the following method. This approach requires you to parse the XML tag format of the model output yourself.
### Example Using Transformers
Here is a complete example using the transformers library:
```pythonfrom transformers import AutoTokenizer
def get_default_tools(): return [ { "name": "get_current_weather", "description": "Get the latest weather for a location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "A certain city, such as Beijing, Shanghai" } }, } "required": ["location"], "type": "object" } ]
# Load model and tokenizertokenizer = AutoTokenizer.from_pretrained(model_id)prompt = "What's the weather like in Shanghai today?"messages = [ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": prompt},]
# Enable function calling toolstools = get_default_tools()
# Apply chat template and include tool definitionstext = tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True, tools=tools)
# Send request (using any inference service)import requestspayload = { "model": "MiniMaxAI/MiniMax-M2", "prompt": text, "max_tokens": 4096}response = requests.post( "http://localhost:8000/v1/completions", headers={"Content-Type": "application/json"}, json=payload, stream=False,)
# Model output needs manual parsingraw_output = response.json()["choices"][0]["text"]print("Raw output:", raw_output)
# Use the parsing function below to process the outputfunction_calls = parse_tool_calls(raw_output, tools)```
## 🛠️ Function Call Definition
### Function Structure
Function calls need to define the `tools` field in the request body. Each function consists of the following parts:
```json{ "tools": [ { "name": "search_web", "description": "Search function.", "parameters": { "properties": { "query_list": { "description": "Keywords for search, list should contain 1 element.", "items": { "type": "string" }, "type": "array" }, "query_tag": { "description": "Category of query", "items": { "type": "string" }, "type": "array" } }, "required": [ "query_list", "query_tag" ], "type": "object" } } ]}```
**Field Descriptions:**- `name`: Function name- `description`: Function description- `parameters`: Function parameter definition - `properties`: Parameter property definition, where key is the parameter name and value contains detailed parameter description - `required`: List of required parameters - `type`: Parameter type (usually "object")
### Internal Processing Format
When processing within the MiniMax-M2 model, function definitions are converted to a special format and concatenated to the input text. Here is a complete example:
```]~!b[]~b]systemYou are a helpful assistant.
# ToolsYou may call one or more tools to assist with the user query.Here are the tools available in JSONSchema format:
<tools><tool>{"name": "search_web", "description": "Search function.", "parameters": {"type": "object", "properties": {"query_list": {"type": "array", "items": {"type": "string"}, "description": "Keywords for search, list should contain 1 element."}, "query_tag": {"type": "array", "items": {"type": "string"}, "description": "Category of query"}}, "required": ["query_list", "query_tag"]}}</tool></tools>
When making tool calls, use XML format to invoke tools and pass parameters:
<minimax:tool_call><invoke name="tool-name-1"><parameter name="param-key-1">param-value-1</parameter><parameter name="param-key-2">param-value-2</parameter>...</invoke>[e~[]~b]userWhen were the latest announcements from OpenAI and Gemini?[e~[]~b]ai<think>```
**Format Description:**
- `]~!b[]~b]system`: System message start marker- `[e~[`: Message end marker- `]~b]user`: User message start marker- `]~b]ai`: Assistant message start marker- `]~b]tool`: Tool result message start marker- `<tools>...</tools>`: Tool definition area, each tool is wrapped with `<tool>` tag, content is JSON Schema- `<minimax:tool_call>...</minimax:tool_call>`: Tool call area- `<think>`: Thinking process marker during generation (optional)
### Model Output Format
MiniMax-M2 uses structured XML tag format:
```xml<minimax:tool_call><invoke name="search_web"><parameter name="query_tag">["technology", "events"]</parameter><parameter name="query_list">["\"OpenAI\" \"latest\" \"release\""]</parameter></invoke><invoke name="search_web"><parameter name="query_tag">["technology", "events"]</parameter><parameter name="query_list">["\"Gemini\" \"latest\" \"release\""]</parameter></invoke></minimax:tool_call>```
Each function call uses the `<invoke name="function_name">` tag, and parameters use the `<parameter name="parameter_name">` tag wrapper.
## Manually Parsing Function Call Results
### Parsing Function Calls
MiniMax-M2 uses structured XML tags, which require a different parsing approach. The core function is as follows:
```pythonimport reimport jsonfrom typing import Any, Optional, List, Dict
def extract_name(name_str: str) -> str: """Extract name from quoted string""" name_str = name_str.strip() if name_str.startswith('"') and name_str.endswith('"'): return name_str[1:-1] elif name_str.startswith("'") and name_str.endswith("'"): return name_str[1:-1] return name_str
def convert_param_value(value: str, param_type: str) -> Any: """Convert parameter value based on parameter type""" if value.lower() == "null": return None param_type = param_type.lower() if param_type in ["string", "str", "text"]: return value elif param_type in ["integer", "int"]: try: return int(value) except (ValueError, TypeError): return value elif param_type in ["number", "float"]: try: val = float(value) return val if val != int(val) else int(val) except (ValueError, TypeError): return value elif param_type in ["boolean", "bool"]: return value.lower() in ["true", "1"] elif param_type in ["object", "array"]: try: return json.loads(value) except json.JSONDecodeError: return value else: # Try JSON parsing, return string if failed try: return json.loads(value) except json.JSONDecodeError: return value
def parse_tool_calls(model_output: str, tools: Optional[List[Dict]] = None) -> List[Dict]: """ Extract all tool calls from model output Args: model_output: Complete output text from the model tools: Tool definition list for getting parameter type information, format can be: - [{"name": "...", "parameters": {...}}] - [{"type": "function", "function": {"name": "...", "parameters": {...}}}] Returns: Parsed tool call list, each element contains name and arguments fields Example: >>> tools = [{ ... "name": "get_weather", ... "parameters": { ... "type": "object", ... "properties": { ... "location": {"type": "string"}, ... "unit": {"type": "string"} ... } ... } ... }] >>> output = '''<minimax:tool_call> ... <invoke name="get_weather"> ... <parameter name="location">San Francisco</parameter> ... <parameter name="unit">celsius</parameter> ... </invoke> ... </minimax:tool_call>''' >>> result = parse_tool_calls(output, tools) >>> print(result) [{'name': 'get_weather', 'arguments': {'location': 'San Francisco', 'unit': 'celsius'}}] """ # Quick check if tool call marker is present if "<minimax:tool_call>" not in model_output: return [] tool_calls = [] try: # Match all <minimax:tool_call> blocks tool_call_regex = re.compile(r"<minimax:tool_call>(.*?)</minimax:tool_call>", re.DOTALL) invoke_regex = re.compile(r"<invoke name=(.*?)</invoke>", re.DOTALL) parameter_regex = re.compile(r"<parameter name=(.*?)</parameter>", re.DOTALL) # Iterate through all tool_call blocks for tool_call_match in tool_call_regex.findall(model_output): # Iterate through all invokes in this block for invoke_match in invoke_regex.findall(tool_call_match): # Extract function name name_match = re.search(r'^([^>]+)', invoke_match) if not name_match: continue function_name = extract_name(name_match.group(1)) # Get parameter configuration param_config = {} if tools: for tool in tools: tool_name = tool.get("name") or tool.get("function", {}).get("name") if tool_name == function_name: params = tool.get("parameters") or tool.get("function", {}).get("parameters") if isinstance(params, dict) and "properties" in params: param_config = params["properties"] break # Extract parameters param_dict = {} for match in parameter_regex.findall(invoke_match): param_match = re.search(r'^([^>]+)>(.*)', match, re.DOTALL) if param_match: param_name = extract_name(param_match.group(1)) param_value = param_match.group(2).strip() # Remove leading and trailing newlines if param_value.startswith('\n'): param_value = param_value[1:] if param_value.endswith('\n'): param_value = param_value[:-1] # Get parameter type and convert param_type = "string" if param_name in param_config: if isinstance(param_config[param_name], dict) and "type" in param_config[param_name]: param_type = param_config[param_name]["type"] param_dict[param_name] = convert_param_value(param_value, param_type) tool_calls.append({ "name": function_name, "arguments": param_dict }) except Exception as e: print(f"Failed to parse tool calls: {e}") return [] return tool_calls```
**Usage Example:**
```python# Define toolstools = [ { "name": "get_weather", "parameters": { "type": "object", "properties": { "location": {"type": "string"}, "unit": {"type": "string"} }, "required": ["location", "unit"] } }]
# Model outputmodel_output = """Let me help you query the weather.<minimax:tool_call><invoke name="get_weather"><parameter name="location">San Francisco</parameter><parameter name="unit">celsius</parameter></invoke></minimax:tool_call>"""
# Parse tool callstool_calls = parse_tool_calls(model_output, tools)
# Output resultsfor call in tool_calls: print(f"Function called: {call['name']}") print(f"Arguments: {call['arguments']}") # Output: Function called: get_weather # Arguments: {'location': 'San Francisco', 'unit': 'celsius'}```
### Executing Function Calls
After parsing is complete, you can execute the corresponding function and construct the return result:
```pythondef execute_function_call(function_name: str, arguments: dict): """Execute function call and return result""" if function_name == "get_weather": location = arguments.get("location", "Unknown location") unit = arguments.get("unit", "celsius") # Build function execution result return { "role": "tool", "content": [ { "name": function_name, "type": "text", "text": json.dumps({ "location": location, "temperature": "25", "unit": unit, "weather": "Sunny" }, ensure_ascii=False) } ] } elif function_name == "search_web": query_list = arguments.get("query_list", []) query_tag = arguments.get("query_tag", []) # Simulate search results return { "role": "tool", "content": [ { "name": function_name, "type": "text", "text": f"Search keywords: {query_list}, Category: {query_tag}\nSearch results: Relevant information found" } ] } return None```
### Returning Function Execution Results to the Model
After successfully parsing function calls, you should add the function execution results to the conversation history so that the model can access and utilize this information in subsequent interactions. Refer to chat_template.jinja for concatenation format.
## References
- [MiniMax-M2 Model Repository](https://github.com/MiniMaxAI/MiniMax-M2)- [vLLM Project Homepage](https://github.com/vllm-project/vllm)- [OpenAI Python SDK](https://github.com/openai/openai-python)docs/function_call_guide_en.mdDeleted-482