Learn how to use the MiniMax M4 API with Python, Node.js, and cURL. Get an API key, stream responses, configure reasoning, and compare current API pricing.
To use the MiniMax M4 API, get an API key, configure your provider’s endpoint and model ID, and send a request containing your messages. MiniMax supports OpenAI-compatible and Anthropic-compatible interfaces, so you can integrate M4 through familiar SDKs.
For direct OpenAI-compatible access, use MiniMax-M4 with the Base URL https://api.minimax.io/v1. Alternatively, CometAPI’s MiniMax M4 API provides access through a shared endpoint for applications working with multiple AI providers.
This guide explains the complete integration process: credentials, your first request, response parsing, Python and Node.js examples, reasoning settings, streaming, troubleshooting, and pricing.
Reviewed for clarity, source attribution and current API terminology.
Key Takeaways
MiniMax M4 supports a 1-million-token context window for large codebases, document analysis, and extended conversations.
The official model ID is MiniMax-M4. Third-party providers may use a different routing identifier.
Existing OpenAI SDK applications can connect by updating the key, Base URL, and model ID.
M4 always uses thinking. The official API supports five reasoning effort levels, from low to max.
Thinking consumes the generation budget. A limit that is too small can leave insufficient room for the final answer.
Official pricing starts at $0.80 per million input tokens and $3.10 per million output tokens, with a separate cached-input rate.
What Is MiniMax M4?
MiniMax M4 is MiniMax’s flagship natively multimodal model for reasoning, software engineering, computer use, and agent workflows. Its Mixture-of-Experts architecture contains 2.74 trillion parameters and activates 66 billion per token.
For developers, the main attractions of the MiniMax M4 API are long-context processing, adjustable thinking depth, and compatibility with established request formats.
Coding and Reasoning
M4 targets tasks such as understanding repositories, modifying multiple files, debugging software, and analyzing lengthy technical material.
MiniMax’s official engineering demonstration describes a 24-hour browser-building task involving more than 4,000 tool calls and approximately 120,000 lines of Rust. This vendor demonstration illustrates the model’s intended use in sustained engineering workflows.
Your application supplies the execution environment. The API returns model responses and tool requests; your software runs permitted operations and feeds the results back into the conversation.
Image and Video Understanding
The official OpenAI-compatible interface accepts text, images, and video. This supports screenshot analysis, visual debugging, and video summarization. Audio input is not currently supported through this interface.
The 1-million-token context window accommodates extensive source material, but it does not represent the maximum length of a single generated answer. Your request must still respect the endpoint’s input and generation limits.
MiniMax M4 API Use Cases
The model is worth evaluating for:
Coding assistants: Review changes, investigate failures, and propose patches.
Document analysis: Compare specifications and extract findings from reports.
Knowledge applications: Answer questions using supplied reference material.
Agents: Coordinate multi-step tasks through application-defined tools.
Creative development: Generate code for interactive websites, games, and visualizations.
For tool-enabled applications, follow the MiniMax tool-use guidance, including preserving the complete assistant response during multi-turn tool conversations.
How to Use the Official MiniMax M4 API
MiniMax provides OpenAI-compatible and Anthropic-compatible access. Choose the OpenAI interface for an existing Chat Completions application. MiniMax recommends its Anthropic-compatible interface for features including thinking blocks and interleaved thinking.
Step 1: Get a MiniMax API Key
Sign in to the MiniMax developer console, obtain an API key appropriate for your intended usage, and confirm the account’s billing plan and model access.
Before sending your first request, check that:
The key belongs to the MiniMax platform.
Your account has the balance or subscription entitlement required for the request.
The selected credentials support the endpoint and usage you intend.
Store the key in an environment variable:
export MINIMAX_API_KEY="YOUR_MINIMAX_API_KEY"
Run this command in the same terminal session that will execute your example. For a deployed application, configure the variable through your hosting platform’s secret settings.
Step 2: Configure MiniMax M4 API Access
Use the settings in the official invocation guide. The following table also shows the CometAPI connection covered later.
With an SDK, supply the Base URL. With cURL, combine the Base URL and request path to form the complete endpoint.
Step 3: Send a MiniMax M4 API Request
This example sends a code-review task to the official OpenAI-compatible endpoint:
curl --fail-with-body \
"https://api.minimax.io/v1/chat/completions" \
-H "Authorization: Bearer $MINIMAX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "MiniMax-M4",
"reasoning_effort": "medium",
"max_completion_tokens": 8192,
"messages": [
{
"role": "user",
"content": "Review this Python function for bugs and suggest a minimal fix: def average(values): return sum(values) / len(values)"
}
]
}'
The request specifies the model, task, thinking depth, and generation budget. --fail-with-body preserves the error response body while making HTTP failures easier to detect in a script.
Step 4: Read the MiniMax M4 API Response
The official interface separates the final answer from thinking. A simplified response has this structure:
{
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"reasoning_content": "...",
"content": "The function fails when values is empty..."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 0,
"completion_tokens": 0,
"total_tokens": 0
}
}
This illustration shows field placement; the zero values are placeholders for actual usage.
Read the response as follows:
message.content: The final answer for your application.
message.reasoning_content: Separately returned thinking content.
finish_reason: Why generation ended. length indicates that generation reached its limit.
usage: Token counts for monitoring and cost analysis.
Do not treat HTTP success alone as task success. Confirm that the answer exists, generation completed as expected, and the result meets your application’s requirements.
MiniMax M4 Anthropic-Compatible Example
For the Anthropic-compatible interface, set thinking depth through output_config.effort:
curl --fail-with-body \
"https://api.minimax.io/anthropic/v1/messages" \
-H "Authorization: Bearer $MINIMAX_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "MiniMax-M4",
"max_tokens": 8192,
"output_config": {
"effort": "medium"
},
"messages": [
{
"role": "user",
"content": "Explain how to investigate a memory leak in a Node.js service."
}
]
}'
Anthropic-style responses use content blocks rather than choices. Extract text blocks when displaying the final answer.
MiniMax M4 API Parameters
After your first request succeeds, tune generation behavior for your workload. The official MiniMax API reference documents the following OpenAI-compatible fields.
Parameter
Purpose
Practical guidance
model
Selects the model
Use MiniMax-M4 for official access
messages
Supplies the task and conversation
Include relevant instructions and context
reasoning_effort
Sets thinking depth
low, medium, high, xhigh, or max
max_completion_tokens
Limits generation
Preferred generation-budget field for new integrations
stream
Enables incremental responses
Set to true
stream_options.include_usage
Returns usage while streaming
Set to true
tools
Defines callable functions
Your application validates and executes calls
The official MiniMax M4 API defaults to max effort. It always uses thinking: reasoning_effort: "none" and thinking: {"type": "disabled"} return an error.
Choose MiniMax M4 Reasoning Effort
Start evaluation at medium, then compare settings against representative tasks.
For straightforward extraction or transformation, test whether low produces acceptable results with less latency. For difficult debugging, planning, or analysis, compare high, xhigh, and max.
Measure correctness and task completion alongside token usage. A higher setting is useful when it improves the result enough to justify the additional processing.
The official API fixes temperature at 1 and top_p at 0.95. Supplying different values does not change those settings.
Set MiniMax M4 Output Limits
Thinking and the final answer share the generation budget. For example, if a request spends most of its allowance on thinking, little capacity remains for the visible answer.
If the MiniMax M4 API returns empty content with finish_reason: "length", increase max_completion_tokens or lower reasoning effort. Increasing the limit permits more generation; it does not force every request to consume the full allowance.
Use an output budget appropriate to the task. A brief extraction and a multi-file code explanation should not automatically receive the same limit.
Why Use MiniMax M4 Through CometAPI?
CometAPI provides access to multiple model providers through a shared API layer. This can simplify credentials, billing administration, and client reuse for applications evaluating or combining several models.
Direct access is useful when MiniMax’s native interfaces and features are the priority. CometAPI is useful when you want to manage the MiniMax M4 API alongside other providers through a familiar client.
Endpoint compatibility allows code reuse, but optional model parameters still depend on the selected route.
How to Call MiniMax M4 Through CometAPI
After configuring your API key and model identifier, choose cURL for a quick test or use the Python or Node.js SDK to integrate the MiniMax M4 API into your application. The examples below use the same OpenAI-compatible endpoint.
Configure MiniMax M4 API Credentials
Create a CometAPI account and generate a key in the API key console. Confirm that your account has sufficient balance and access to MiniMax M4, then set your key and model ID as environment variables:
Run these commands in the terminal session you will use for the examples below. For a deployed application, configure the variables in your hosting platform’s environment settings.
Call MiniMax M4 with cURL
Send a POST request to CometAPI’s Chat Completions endpoint:
curl --fail-with-body \
"https://api.cometapi.com/v1/chat/completions" \
-H "Authorization: Bearer $COMETAPI_KEY" \
-H "Content-Type: application/json" \
-d "{
\"model\": \"$COMETAPI_MODEL\",
\"messages\": [
{
\"role\": \"user\",
\"content\": \"Explain what an API is in one sentence.\"
}
]
}"
A non-streaming MiniMax M4 API call returns the completion in the response body. This chat endpoint does not require the submit-and-poll workflow used by video-generation APIs.
Use MiniMax M4 with Python
Install the OpenAI SDK:
python -m pip install --upgrade openai
Initialize the client with CometAPI’s Base URL:
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["COMETAPI_KEY"],
base_url="https://api.cometapi.com/v1",
timeout=180.0,
)
response = client.chat.completions.create(
model=os.environ["COMETAPI_MODEL"],
messages=[
{
"role": "system",
"content": "You are a precise software engineering assistant.",
},
{
"role": "user",
"content": (
"Design a REST API for a task manager. Include endpoints, "
"request examples, status codes, and pagination."
),
},
],
)
choice = response.choices[0]
print(choice.message.content)
print("Finish reason:", choice.finish_reason)
if response.usage:
print("Usage:", response.usage.model_dump())
Save this as minimax.py and run:
python minimax.py
To use the same Python pattern with the official MiniMax M4 API, change the client configuration and model:
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.COMETAPI_KEY,
baseURL: "https://api.cometapi.com/v1",
timeout: 180_000,
});
const response = await client.chat.completions.create({
model: process.env.COMETAPI_MODEL,
messages: [
{
role: "user",
content:
"Write a JavaScript function that deduplicates objects by ID. " +
"Include tests for missing IDs and duplicate records.",
},
],
});
console.log(response.choices[0].message.content);
console.log("Finish reason:", response.choices[0].finish_reason);
console.log("Usage:", response.usage);
Execute it with:
node minimax.mjs
After the basic request works, add route-supported reasoning controls and generation limits. Keep a small set of representative test inputs to check behavior when changing models or providers.
How to Stream MiniMax M4 API Responses
Streaming lets your application display answer fragments as they arrive. The official MiniMax streaming interface also supports token-usage reporting.
The following example uses the official endpoint and its documented streaming options:
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["MINIMAX_API_KEY"],
base_url="https://api.minimax.io/v1",
timeout=180.0,
)
stream = client.chat.completions.create(
model="MiniMax-M4",
reasoning_effort="medium",
max_completion_tokens=8192,
messages=[
{
"role": "user",
"content": (
"Explain how database indexes affect "
"read and write performance."
),
}
],
stream=True,
stream_options={"include_usage": True},
)
for chunk in stream:
if chunk.usage:
print("\nUsage:", chunk.usage.model_dump())
if not chunk.choices:
continue
delta = chunk.choices[0].delta
if delta.content:
print(delta.content, end="", flush=True)
print()
The loop handles usage chunks without choices and displays answer content separately from thinking. Because thinking can precede the final answer, the connection may be active before visible answer text arrives.
Streaming improves delivery responsiveness. It does not itself reduce token consumption.
Troubleshoot MiniMax M4 API Errors
When a request fails or produces an incomplete answer, inspect the response body and finish reason before retrying. These usually reveal whether the problem is authentication, routing, request configuration, or capacity.
Authentication and Routing
For an authentication failure, verify the environment variable is available to the running process and that the key belongs to the endpoint you are calling. A MiniMax key and a CometAPI key are not interchangeable.
For a model-not-found response, check the exact account route identifier. Confirm the key has access to that model rather than changing capitalization or trying aliases at random.
Empty or Truncated Answers
If the response succeeds but content is empty, inspect finish_reason.
When it is length, thinking may have exhausted the generation budget. Increase the limit or reduce effort, then repeat the same task to check whether the final answer completes.
If the response contains tool calls, your application may need to execute those calls and continue the conversation before receiving a final answer.
Limits and Timeouts
Handle other common failures according to their cause:
Invalid reasoning configuration: Keep thinking enabled and select a supported effort level.
Context-limit error: Remove irrelevant history or divide the source material into smaller tasks.
Rate limit: Reduce concurrency and apply bounded backoff within the account’s quota.
Timeout or server error: Configure a suitable timeout and limited retries.
Log request duration, status, finish reason, and token usage. For streamed requests, track whether failure occurred before or after content began arriving so retries do not silently duplicate work.
MiniMax M4 API Pricing
The MiniMax M4 API uses token-based billing. Compare input, output, and cached-input rates, then calculate the cost across all calls required to finish an application task.
CometAPI lists MiniMax M4 pricing at $0.64 per million input tokens, $2.48 per million output tokens, and $0.04 per million cached input tokens for its default group—20% below the official rates.
Calculate MiniMax M4 API Costs
Assume one request consumes 10,000 uncached input tokens and 2,000 billable output tokens, with no additional attempts or charges.
Using the published CometAPI default-group rates, the same usage costs $0.01136. For 1,000 equivalent requests, the totals are $14.20 and $11.36, respectively.
Use billable output usage rather than visible answer length because thinking also generates tokens. An agent that makes five model calls for one user task must include all five calls in its task cost.
Control MiniMax M4 API Spending
Manage spending through four controls: reasoning effort, relevant context, generation budgets, and retry limits.
Test lower effort settings for routine transformations and higher settings for difficult analysis. Use prompt caching for supported repeated prefixes, and avoid resending unrelated documents or conversation history.
Measure cost per successful task, alongside accuracy and latency. This shows whether a cheaper configuration saves money overall or merely creates additional retries and corrections.
Conclusion
The MiniMax M4 API provides access to long-context reasoning, coding assistance, and multimodal analysis through familiar API formats. Direct MiniMax access supports OpenAI-compatible and Anthropic-compatible requests, while CometAPI offers shared access alongside other model providers.
Start with the correct key, endpoint, and model identifier, then verify a minimal request and inspect the response. Once that works, tune reasoning effort and generation budgets using representative tasks before introducing streaming or tool execution.
To integrate through CometAPI, open the MiniMax M4 API model page, confirm your account’s route and pricing, and run the cURL, Python, or Node.js example above.