Text Generation
Transformers
Safetensors
minimax_m2
conversational
custom_code
fp8
MiniMax-AI commited on
Commit
a917c26
·
verified ·
1 Parent(s): 79891b6

Delete docs/function_call_guide_en.md

Browse files
Files changed (1) hide show
  1. docs/function_call_guide_en.md +0 -482
docs/function_call_guide_en.md DELETED
@@ -1,482 +0,0 @@
1
- # MiniMax-M2 Function Call Guide
2
-
3
- ## Introduction
4
-
5
- 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.
6
-
7
- ## Basic Example
8
-
9
- The following Python script implements a weather query function call example based on the OpenAI SDK:
10
-
11
- ```python
12
- from openai import OpenAI
13
- import json
14
-
15
- client = OpenAI(base_url="http://localhost:8000/v1", api_key="dummy")
16
-
17
- def get_weather(location: str, unit: str):
18
- return f"Getting the weather for {location} in {unit}..."
19
-
20
- tool_functions = {"get_weather": get_weather}
21
-
22
- tools = [{
23
- "type": "function",
24
- "function": {
25
- "name": "get_weather",
26
- "description": "Get the current weather in a given location",
27
- "parameters": {
28
- "type": "object",
29
- "properties": {
30
- "location": {"type": "string", "description": "City and state, e.g., 'San Francisco, CA'"},
31
- "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
32
- },
33
- "required": ["location", "unit"]
34
- }
35
- }
36
- }]
37
-
38
- response = client.chat.completions.create(
39
- model=client.models.list().data[0].id,
40
- messages=[{"role": "user", "content": "What's the weather like in San Francisco? use celsius."}],
41
- tools=tools,
42
- tool_choice="auto"
43
- )
44
-
45
- print(response)
46
-
47
- tool_call = response.choices[0].message.tool_calls[0].function
48
- print(f"Function called: {tool_call.name}")
49
- print(f"Arguments: {tool_call.arguments}")
50
- print(f"Result: {get_weather(**json.loads(tool_call.arguments))}")
51
- ```
52
-
53
- **Output Example:**
54
- ```
55
- Function called: get_weather
56
- Arguments: {"location": "San Francisco, CA", "unit": "celsius"}
57
- Result: Getting the weather for San Francisco, CA in celsius...
58
- ```
59
-
60
- ## Manually Parsing Model Output
61
-
62
- 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.
63
-
64
- ### Example Using Transformers
65
-
66
- Here is a complete example using the transformers library:
67
-
68
- ```python
69
- from transformers import AutoTokenizer
70
-
71
- def get_default_tools():
72
- return [
73
- {
74
- "name": "get_current_weather",
75
- "description": "Get the latest weather for a location",
76
- "parameters": {
77
- "type": "object",
78
- "properties": {
79
- "location": {
80
- "type": "string",
81
- "description": "A certain city, such as Beijing, Shanghai"
82
- }
83
- },
84
- }
85
- "required": ["location"],
86
- "type": "object"
87
- }
88
- ]
89
-
90
- # Load model and tokenizer
91
- tokenizer = AutoTokenizer.from_pretrained(model_id)
92
- prompt = "What's the weather like in Shanghai today?"
93
- messages = [
94
- {"role": "system", "content": "You are a helpful assistant."},
95
- {"role": "user", "content": prompt},
96
- ]
97
-
98
- # Enable function calling tools
99
- tools = get_default_tools()
100
-
101
- # Apply chat template and include tool definitions
102
- text = tokenizer.apply_chat_template(
103
- messages,
104
- tokenize=False,
105
- add_generation_prompt=True,
106
- tools=tools
107
- )
108
-
109
- # Send request (using any inference service)
110
- import requests
111
- payload = {
112
- "model": "MiniMaxAI/MiniMax-M2",
113
- "prompt": text,
114
- "max_tokens": 4096
115
- }
116
- response = requests.post(
117
- "http://localhost:8000/v1/completions",
118
- headers={"Content-Type": "application/json"},
119
- json=payload,
120
- stream=False,
121
- )
122
-
123
- # Model output needs manual parsing
124
- raw_output = response.json()["choices"][0]["text"]
125
- print("Raw output:", raw_output)
126
-
127
- # Use the parsing function below to process the output
128
- function_calls = parse_tool_calls(raw_output, tools)
129
- ```
130
-
131
- ## 🛠️ Function Call Definition
132
-
133
- ### Function Structure
134
-
135
- Function calls need to define the `tools` field in the request body. Each function consists of the following parts:
136
-
137
- ```json
138
- {
139
- "tools": [
140
- {
141
- "name": "search_web",
142
- "description": "Search function.",
143
- "parameters": {
144
- "properties": {
145
- "query_list": {
146
- "description": "Keywords for search, list should contain 1 element.",
147
- "items": { "type": "string" },
148
- "type": "array"
149
- },
150
- "query_tag": {
151
- "description": "Category of query",
152
- "items": { "type": "string" },
153
- "type": "array"
154
- }
155
- },
156
- "required": [ "query_list", "query_tag" ],
157
- "type": "object"
158
- }
159
- }
160
- ]
161
- }
162
- ```
163
-
164
- **Field Descriptions:**
165
- - `name`: Function name
166
- - `description`: Function description
167
- - `parameters`: Function parameter definition
168
- - `properties`: Parameter property definition, where key is the parameter name and value contains detailed parameter description
169
- - `required`: List of required parameters
170
- - `type`: Parameter type (usually "object")
171
-
172
- ### Internal Processing Format
173
-
174
- 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:
175
-
176
- ```
177
- ]~!b[]~b]system
178
- You are a helpful assistant.
179
-
180
- # Tools
181
- You may call one or more tools to assist with the user query.
182
- Here are the tools available in JSONSchema format:
183
-
184
- <tools>
185
- <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>
186
- </tools>
187
-
188
- When making tool calls, use XML format to invoke tools and pass parameters:
189
-
190
- <minimax:tool_call>
191
- <invoke name="tool-name-1">
192
- <parameter name="param-key-1">param-value-1</parameter>
193
- <parameter name="param-key-2">param-value-2</parameter>
194
- ...
195
- </invoke>
196
- [e~[
197
- ]~b]user
198
- When were the latest announcements from OpenAI and Gemini?[e~[
199
- ]~b]ai
200
- <think>
201
- ```
202
-
203
- **Format Description:**
204
-
205
- - `]~!b[]~b]system`: System message start marker
206
- - `[e~[`: Message end marker
207
- - `]~b]user`: User message start marker
208
- - `]~b]ai`: Assistant message start marker
209
- - `]~b]tool`: Tool result message start marker
210
- - `<tools>...</tools>`: Tool definition area, each tool is wrapped with `<tool>` tag, content is JSON Schema
211
- - `<minimax:tool_call>...</minimax:tool_call>`: Tool call area
212
- - `<think>`: Thinking process marker during generation (optional)
213
-
214
- ### Model Output Format
215
-
216
- MiniMax-M2 uses structured XML tag format:
217
-
218
- ```xml
219
- <minimax:tool_call>
220
- <invoke name="search_web">
221
- <parameter name="query_tag">["technology", "events"]</parameter>
222
- <parameter name="query_list">["\"OpenAI\" \"latest\" \"release\""]</parameter>
223
- </invoke>
224
- <invoke name="search_web">
225
- <parameter name="query_tag">["technology", "events"]</parameter>
226
- <parameter name="query_list">["\"Gemini\" \"latest\" \"release\""]</parameter>
227
- </invoke>
228
- </minimax:tool_call>
229
- ```
230
-
231
- Each function call uses the `<invoke name="function_name">` tag, and parameters use the `<parameter name="parameter_name">` tag wrapper.
232
-
233
- ## Manually Parsing Function Call Results
234
-
235
- ### Parsing Function Calls
236
-
237
- MiniMax-M2 uses structured XML tags, which require a different parsing approach. The core function is as follows:
238
-
239
- ```python
240
- import re
241
- import json
242
- from typing import Any, Optional, List, Dict
243
-
244
-
245
- def extract_name(name_str: str) -> str:
246
- """Extract name from quoted string"""
247
- name_str = name_str.strip()
248
- if name_str.startswith('"') and name_str.endswith('"'):
249
- return name_str[1:-1]
250
- elif name_str.startswith("'") and name_str.endswith("'"):
251
- return name_str[1:-1]
252
- return name_str
253
-
254
-
255
- def convert_param_value(value: str, param_type: str) -> Any:
256
- """Convert parameter value based on parameter type"""
257
- if value.lower() == "null":
258
- return None
259
-
260
- param_type = param_type.lower()
261
-
262
- if param_type in ["string", "str", "text"]:
263
- return value
264
- elif param_type in ["integer", "int"]:
265
- try:
266
- return int(value)
267
- except (ValueError, TypeError):
268
- return value
269
- elif param_type in ["number", "float"]:
270
- try:
271
- val = float(value)
272
- return val if val != int(val) else int(val)
273
- except (ValueError, TypeError):
274
- return value
275
- elif param_type in ["boolean", "bool"]:
276
- return value.lower() in ["true", "1"]
277
- elif param_type in ["object", "array"]:
278
- try:
279
- return json.loads(value)
280
- except json.JSONDecodeError:
281
- return value
282
- else:
283
- # Try JSON parsing, return string if failed
284
- try:
285
- return json.loads(value)
286
- except json.JSONDecodeError:
287
- return value
288
-
289
-
290
- def parse_tool_calls(model_output: str, tools: Optional[List[Dict]] = None) -> List[Dict]:
291
- """
292
- Extract all tool calls from model output
293
-
294
- Args:
295
- model_output: Complete output text from the model
296
- tools: Tool definition list for getting parameter type information, format can be:
297
- - [{"name": "...", "parameters": {...}}]
298
- - [{"type": "function", "function": {"name": "...", "parameters": {...}}}]
299
-
300
- Returns:
301
- Parsed tool call list, each element contains name and arguments fields
302
-
303
- Example:
304
- >>> tools = [{
305
- ... "name": "get_weather",
306
- ... "parameters": {
307
- ... "type": "object",
308
- ... "properties": {
309
- ... "location": {"type": "string"},
310
- ... "unit": {"type": "string"}
311
- ... }
312
- ... }
313
- ... }]
314
- >>> output = '''<minimax:tool_call>
315
- ... <invoke name="get_weather">
316
- ... <parameter name="location">San Francisco</parameter>
317
- ... <parameter name="unit">celsius</parameter>
318
- ... </invoke>
319
- ... </minimax:tool_call>'''
320
- >>> result = parse_tool_calls(output, tools)
321
- >>> print(result)
322
- [{'name': 'get_weather', 'arguments': {'location': 'San Francisco', 'unit': 'celsius'}}]
323
- """
324
- # Quick check if tool call marker is present
325
- if "<minimax:tool_call>" not in model_output:
326
- return []
327
-
328
- tool_calls = []
329
-
330
- try:
331
- # Match all <minimax:tool_call> blocks
332
- tool_call_regex = re.compile(r"<minimax:tool_call>(.*?)</minimax:tool_call>", re.DOTALL)
333
- invoke_regex = re.compile(r"<invoke name=(.*?)</invoke>", re.DOTALL)
334
- parameter_regex = re.compile(r"<parameter name=(.*?)</parameter>", re.DOTALL)
335
-
336
- # Iterate through all tool_call blocks
337
- for tool_call_match in tool_call_regex.findall(model_output):
338
- # Iterate through all invokes in this block
339
- for invoke_match in invoke_regex.findall(tool_call_match):
340
- # Extract function name
341
- name_match = re.search(r'^([^>]+)', invoke_match)
342
- if not name_match:
343
- continue
344
-
345
- function_name = extract_name(name_match.group(1))
346
-
347
- # Get parameter configuration
348
- param_config = {}
349
- if tools:
350
- for tool in tools:
351
- tool_name = tool.get("name") or tool.get("function", {}).get("name")
352
- if tool_name == function_name:
353
- params = tool.get("parameters") or tool.get("function", {}).get("parameters")
354
- if isinstance(params, dict) and "properties" in params:
355
- param_config = params["properties"]
356
- break
357
-
358
- # Extract parameters
359
- param_dict = {}
360
- for match in parameter_regex.findall(invoke_match):
361
- param_match = re.search(r'^([^>]+)>(.*)', match, re.DOTALL)
362
- if param_match:
363
- param_name = extract_name(param_match.group(1))
364
- param_value = param_match.group(2).strip()
365
-
366
- # Remove leading and trailing newlines
367
- if param_value.startswith('\n'):
368
- param_value = param_value[1:]
369
- if param_value.endswith('\n'):
370
- param_value = param_value[:-1]
371
-
372
- # Get parameter type and convert
373
- param_type = "string"
374
- if param_name in param_config:
375
- if isinstance(param_config[param_name], dict) and "type" in param_config[param_name]:
376
- param_type = param_config[param_name]["type"]
377
-
378
- param_dict[param_name] = convert_param_value(param_value, param_type)
379
-
380
- tool_calls.append({
381
- "name": function_name,
382
- "arguments": param_dict
383
- })
384
-
385
- except Exception as e:
386
- print(f"Failed to parse tool calls: {e}")
387
- return []
388
-
389
- return tool_calls
390
- ```
391
-
392
- **Usage Example:**
393
-
394
- ```python
395
- # Define tools
396
- tools = [
397
- {
398
- "name": "get_weather",
399
- "parameters": {
400
- "type": "object",
401
- "properties": {
402
- "location": {"type": "string"},
403
- "unit": {"type": "string"}
404
- },
405
- "required": ["location", "unit"]
406
- }
407
- }
408
- ]
409
-
410
- # Model output
411
- model_output = """Let me help you query the weather.
412
- <minimax:tool_call>
413
- <invoke name="get_weather">
414
- <parameter name="location">San Francisco</parameter>
415
- <parameter name="unit">celsius</parameter>
416
- </invoke>
417
- </minimax:tool_call>"""
418
-
419
- # Parse tool calls
420
- tool_calls = parse_tool_calls(model_output, tools)
421
-
422
- # Output results
423
- for call in tool_calls:
424
- print(f"Function called: {call['name']}")
425
- print(f"Arguments: {call['arguments']}")
426
- # Output: Function called: get_weather
427
- # Arguments: {'location': 'San Francisco', 'unit': 'celsius'}
428
- ```
429
-
430
- ### Executing Function Calls
431
-
432
- After parsing is complete, you can execute the corresponding function and construct the return result:
433
-
434
- ```python
435
- def execute_function_call(function_name: str, arguments: dict):
436
- """Execute function call and return result"""
437
- if function_name == "get_weather":
438
- location = arguments.get("location", "Unknown location")
439
- unit = arguments.get("unit", "celsius")
440
- # Build function execution result
441
- return {
442
- "role": "tool",
443
- "content": [
444
- {
445
- "name": function_name,
446
- "type": "text",
447
- "text": json.dumps({
448
- "location": location,
449
- "temperature": "25",
450
- "unit": unit,
451
- "weather": "Sunny"
452
- }, ensure_ascii=False)
453
- }
454
- ]
455
- }
456
- elif function_name == "search_web":
457
- query_list = arguments.get("query_list", [])
458
- query_tag = arguments.get("query_tag", [])
459
- # Simulate search results
460
- return {
461
- "role": "tool",
462
- "content": [
463
- {
464
- "name": function_name,
465
- "type": "text",
466
- "text": f"Search keywords: {query_list}, Category: {query_tag}\nSearch results: Relevant information found"
467
- }
468
- ]
469
- }
470
-
471
- return None
472
- ```
473
-
474
- ### Returning Function Execution Results to the Model
475
-
476
- 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.
477
-
478
- ## References
479
-
480
- - [MiniMax-M2 Model Repository](https://github.com/MiniMaxAI/MiniMax-M2)
481
- - [vLLM Project Homepage](https://github.com/vllm-project/vllm)
482
- - [OpenAI Python SDK](https://github.com/openai/openai-python)