Skip to content

[Feature] Support MiniMax-M1 function calls features #20297

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jul 3, 2025

Conversation

qscqesze
Copy link
Contributor

@qscqesze qscqesze commented Jul 1, 2025

Support MiniMax-M1 function calls features

How to use:

export SAFETENSORS_FAST_GPU=1
export VLLM_USE_V1=0

python3 -m vllm.entrypoints.openai.api_server \
--model MiniMax-M1-80k \
--tensor-parallel-size 8 \
--trust-remote-code \
--quantization experts_int8  \
--enable-auto-tool-choice \
--tool-call-parser minimax \
--chat-template vllm/examples/tool_chat_template_minimax_m1.jinja \
--max_model_len 4096 \
--dtype bfloat16 \
--gpu-memory-utilization 0.85

test_scripts:

from openai import OpenAI
import 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].function
print(f"Function called: {tool_call.name}")
print(f"Arguments: {tool_call.arguments}")
print(f"Result: {get_weather(**json.loads(tool_call.arguments))}")

Outpt:

Function called: get_weather
Arguments: {"location": "San Francisco, CA", "unit": "celsius"}
Result: Getting the weather for San Francisco, CA in celsius...

Streaming Test:

from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="dummy")

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'


tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_temperature",
            "description": "Get current temperature at a location.",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": 'The location to get the temperature for, in the format "City, State, Country".',
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": 'The unit to return the temperature in. Defaults to "celsius".',
                    },
                },
                "required": ["location"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "get_temperature_date",
            "description": "Get temperature at a location and date.",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": 'The location to get the temperature for, in the format "City, State, Country".',
                    },
                    "date": {
                        "type": "string",
                        "description": 'The date to get the temperature for, in the format "Year-Month-Day".',
                    },
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": 'The unit to return the temperature in. Defaults to "celsius".',
                    },
                },
                "required": ["location", "date"],
            },
        },
    },
]


tool_calls_stream = client.chat.completions.create(
    model=client.models.list().data[0].id,
    messages=[
        {
            "role": "system",
            "content": "You are a helpful assistant.\n\nCurrent Date: 2024-09-30",
        },
        {
            "role": "user",
            "content": "What's the temperature in San Francisco now? How about tomorrow? use celsius.",
        },
    ],
    tools=tools,
    tool_choice="auto",
    stream=True
)

print("reasoning content(Blue) and content(Green):")
chunks = []
arguments = []
tool_call_idx = -1

response = ""

for chunk in tool_calls_stream:
    chunks.append(chunk)
    delta = chunk.choices[0].delta
    
    
    if hasattr(delta, "reasoning_content") and delta.reasoning_content:
        print(bcolors.OKBLUE + delta.reasoning_content, end="", flush=True)
    
    if hasattr(delta, "content") and delta.content:
        print(bcolors.OKGREEN + delta.content, end="", flush=True)
        response += delta.content
    
    if delta.tool_calls:
        tool_call = delta.tool_calls[0]
        
        if tool_call.index != tool_call_idx:
            tool_call_idx = tool_call.index
            arguments.append({"id": "", "name": "", "arguments": ""})
        
        if tool_call.id:
            if not arguments[tool_call_idx]["id"]:
                arguments[tool_call_idx]["id"] = tool_call.id
        
        if tool_call.function:
            if tool_call.function.name:
                if not arguments[tool_call_idx]["name"]: 
                    arguments[tool_call_idx]["name"] = tool_call.function.name
            
            if tool_call.function.arguments:
                current_args = arguments[tool_call_idx]["arguments"]
                new_args = tool_call.function.arguments
                
                if new_args.startswith(current_args):
                    delta_args = new_args[len(current_args):]
                
                arguments[tool_call_idx]["arguments"] = new_args

print(bcolors.ENDC + "\n\n### Streaming Output End ###\n")

if response.strip():
    print(f"{bcolors.OKGREEN}Complete Response:{bcolors.ENDC}")
    print(response)

if arguments:
    print(f"\n{bcolors.HEADER}Tool Calls Summary:{bcolors.ENDC}")
    for i, tool_call_info in enumerate(arguments):
        print(f"Tool {i+1}: {tool_call_info.get('name', 'Unknown')}")
        if tool_call_info.get('arguments'):
            print(f"  Full Arguments: {tool_call_info['arguments']}")
        print()

Output:

Tool Calls Summary:
Tool 1: get_current_temperature
  Full Arguments: {"location": "San Francisco, California, USA", "unit": "celsius"}

Tool 2: get_temperature_date
  Full Arguments: {"location": "San Francisco, California, USA", "date": "2024-10-01", "unit": "celsius"}

@qscqesze qscqesze requested a review from aarnphm as a code owner July 1, 2025 04:01
@mergify mergify bot added documentation Improvements or additions to documentation frontend tool-calling labels Jul 1, 2025
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary of Changes

Hello @qscqesze, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances vLLM's capabilities by adding native support for Minimax-M1 model's function calling features. It involves creating a specialized chat template to format prompts according to Minimax-M1's requirements and developing a dedicated tool parser to interpret the model's tool call responses, including robust handling for streaming scenarios. This integration allows users to leverage Minimax-M1 models for advanced tool-use applications within the vLLM framework.

Highlights

  • Minimax-M1 Function Call Support: Introduces comprehensive support for Minimax-M1's function calling features, enabling vLLM to correctly format prompts for tool use and parse the model's tool call responses.
  • New Chat Template: Adds a new Jinja chat template (examples/tool_chat_template_minimax_m1.jinja) specifically designed for Minimax-M1, defining its unique prompt format for system messages, user inputs, assistant responses, and the structure for tool definitions and tool calls using XML tags.
  • Dedicated Tool Parser: Implements a new MinimaxToolParser to accurately extract and stream tool calls from Minimax-M1 model outputs. This parser handles the model's specific XML-like tag structure (<tool_calls>) and uses partial JSON parsing for incremental argument extraction during streaming.
  • Integration with OpenAI API: Integrates the new MinimaxToolParser into vLLM's OpenAI API entrypoint, allowing users to enable Minimax-M1 function calling via the --tool-call-parser minimax command-line argument.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces support for Minimax-M1 function calls, including a new Jinja chat template and a dedicated tool parser. The non-streaming tool extraction logic appears sound. However, the streaming tool call parsing in minimax_tool_parser.py has significant design flaws related to handling multiple concurrent tool calls and extracting argument deltas, which will lead to incorrect behavior. Additionally, there are opportunities to improve error handling and code clarity for better maintainability.

Copy link

github-actions bot commented Jul 1, 2025

👋 Hi! Thank you for contributing to the vLLM project.

💬 Join our developer Slack at https://slack.vllm.ai to discuss your PR in #pr-reviews, coordinate on features in #feat- channels, or join special interest groups in #sig- channels.

Just a reminder: PRs would not trigger full CI run by default. Instead, it would only run fastcheck CI which starts running only a small and essential subset of CI tests to quickly catch errors. You can run other CI tests on top of those by going to your fastcheck build on Buildkite UI (linked in the PR checks section) and unblock them. If you do not have permission to unblock, ping simon-mo or khluu to add you in our Buildkite org.

Once the PR is approved and ready to go, your PR reviewer(s) can run CI to test the changes comprehensively before merging.

To run CI, PR reviewers can either: Add ready label to the PR or enable auto-merge.

🚀

Signed-off-by: QscQ <[email protected]>
@qscqesze qscqesze requested a review from hmellor as a code owner July 1, 2025 08:07
qscqesze and others added 2 commits July 1, 2025 16:14
Signed-off-by: qingjun <[email protected]>
Signed-off-by: QscQ <[email protected]>
Copy link
Member

@mgoin mgoin left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great work, thanks for sharing examples! It would be nice to add a unit test, especially to test complex features like streaming - see xlam for an example https://github.com/vllm-project/vllm/blob/02cabff207ca68094a73ba21296c82cdbcb1d1a5/tests/tool_use/test_xlam_tool_parser.py

@qscqesze
Copy link
Contributor Author

qscqesze commented Jul 2, 2025

@heeju-kim2 @aarnphm Hi. Would you have some time to help review this RP when convenient? It looks like we’ll need someone with write access to approve it in order to move forward with the CI/CD process.

@aarnphm
Copy link
Collaborator

aarnphm commented Jul 2, 2025

Can you add tests similar to Michael's suggestion here?

@aarnphm
Copy link
Collaborator

aarnphm commented Jul 2, 2025

note for self: one more tools to keep in mind of 😃

qscqesze and others added 2 commits July 2, 2025 20:10
Signed-off-by: QscQ <[email protected]>
Signed-off-by: qingjun <[email protected]>
@qscqesze
Copy link
Contributor Author

qscqesze commented Jul 2, 2025

@aarnphm @mgoin Thanks for your suggestions. I added the tests.

It can run with:python3 -m pytest tests/tool_use/test_minimax_tool_parser.py -v

@qscqesze qscqesze changed the title [Feature] Support Minimax-M1 function calls features [Feature] Support MiniMax-M1 function calls features Jul 2, 2025
@mgoin mgoin added the ready ONLY add when PR is ready to merge/full CI is needed label Jul 2, 2025
Copy link
Collaborator

@aarnphm aarnphm left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this

@aarnphm aarnphm enabled auto-merge (squash) July 2, 2025 15:46
@qscqesze
Copy link
Contributor Author

qscqesze commented Jul 3, 2025

@aandyw I noticed that the CI/CD pipeline for this auto-merge has been running for over 17 hours. It seems to be stuck at the "Intel HPU Test" stage — is this expected, or could something be wrong?
Just wanted to check in case it needs a manual retry or intervention?

@aarnphm aarnphm merged commit 363528d into vllm-project:main Jul 3, 2025
82 checks passed
sfeng33 pushed a commit to sfeng33/vllm that referenced this pull request Jul 6, 2025
huydhn pushed a commit to huydhn/vllm that referenced this pull request Jul 8, 2025
LyrisZhong pushed a commit to LyrisZhong/vllm that referenced this pull request Jul 23, 2025
avigny pushed a commit to avigny/vllm that referenced this pull request Jul 31, 2025
Pradyun92 pushed a commit to Pradyun92/vllm that referenced this pull request Aug 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation frontend ready ONLY add when PR is ready to merge/full CI is needed tool-calling
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

3 participants