The smallest working request
A minimax api example that works on the first try needs only a key, a URL and a model ID. This site is not the official MiniMax API; it is an independent, OpenAI-compatible endpoint serving one open-weight model that answers without content refusals for lawful adult use. The request format is the OpenAI chat format, so everything you know about it carries over.
Set your key in an environment variable called API_KEY (you can get one on the API key page). Then send a chat completion. The path is POST /v1/chat/completions, the auth header is Authorization: Bearer followed by the key, and the model is uncensored.
curl https://api.minimaxapi.top/v1/chat/completions \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "uncensored",
"messages": [
{"role": "system", "content": "You answer in plain English."},
{"role": "user", "content": "Explain what a context window is in two sentences."}
],
"temperature": 0.7
}'The reply is a JSON object with a choices array, the text in choices[0].message.content, and a usage block with prompt and completion token counts. That usage block is what you are billed on: $0.15 per 1M input tokens and $0.50 per 1M output tokens. This request, with about 40 tokens in and 60 tokens out, costs a fraction of a thousandth of a cent.
Which client to pick
Three styles cover nearly every use. The SDK route, with the official OpenAI library in Python or Node, is the best default because it handles retries, streaming parsing and typed responses for you. Plain HTTP with curl or fetch is better for shell scripts, serverless functions and debugging, since you see exactly what goes over the wire. Frameworks such as LangChain sit on top of the same endpoint and add chains and agents, at the cost of more moving parts when something breaks.
Whichever you pick, the contract does not change. Only POST /v1/chat/completions and GET /v1/models exist, the model is always uncensored, and the reply format follows OpenAI's. If you have code written for another OpenAI-style provider, expect to change the base URL, the key and the model name, and nothing else.
Multi-turn chat in Python
The API keeps no conversation state. Each request must contain the whole history you want the model to see, which is how the OpenAI format has always worked. The helper below appends each user message and each reply to a list and resends it.
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.minimaxapi.top/v1", api_key=os.environ["API_KEY"])
history = [{"role": "system", "content": "You are a dungeon master for a short fantasy story."}]
def say(text: str) -> str:
history.append({"role": "user", "content": text})
r = client.chat.completions.create(model="uncensored", messages=history)
reply = r.choices[0].message.content
history.append({"role": "assistant", "content": reply})
return reply
print(say("I push open the cellar door."))
print(say("I light a torch and step inside."))Two consequences follow. First, input cost grows with the conversation, because turn ten pays again for turns one to nine. A history of 6,000 tokens plus a 400-token reply costs 6,000 x $0.15 / 1M + 400 x $0.50 / 1M = $0.0009 + $0.0002 = $0.0011. Second, the context window is 100,000 tokens for prompt and completion together, so very long sessions need trimming or summarising at some point. A simple rule is to keep the system prompt, a short summary and the last handful of turns.
Streaming responses
For chat interfaces you want text to appear as it is generated. Set stream: true and the server sends Server-Sent Events, one chunk per piece of text, and finishes with a chunk carrying usage. In the loop below, the guard on chunk.choices matters, because the closing chunk can arrive with no choices at all.
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.minimaxapi.top/v1", api_key=os.environ["API_KEY"])
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Tell a four-sentence story about a lighthouse keeper."}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
if getattr(chunk, "usage", None):
print("\nTokens:", chunk.usage.prompt_tokens, chunk.usage.completion_tokens)Keep one operational fact in mind: a streamed request holds its concurrency slot until the stream ends. A full key allows 8 concurrent requests, a trial key 2. If a user closes the tab, make sure your server cancels the upstream stream, otherwise the slot stays busy and later calls get a 429 with the code concurrency.
JSON mode for structured output
When another program reads the model's answer, free text is a liability. Setting response_format to {"type": "json_object"} constrains the reply to a JSON object. You should still describe the shape you want in the system prompt and mention the word JSON there, as in the example, because the mode guarantees valid JSON syntax but cannot know which keys you expect.
import json, os
from openai import OpenAI
client = OpenAI(base_url="https://api.minimaxapi.top/v1", api_key=os.environ["API_KEY"])
r = client.chat.completions.create(
model="uncensored",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "Reply only with a JSON object with keys name, role and traits (a list of strings)."},
{"role": "user", "content": "Invent a tavern keeper for a fantasy story."},
],
temperature=0.8,
)
data = json.loads(r.choices[0].message.content)
print(data["name"], "-", ", ".join(data["traits"]))Always wrap json.loads in a try block in real code, and check that the keys exist before you use them. If a field is sometimes missing, ask for a default in the prompt, for example an empty list. Setting a lower temperature, around 0.2 to 0.5, makes the structure more stable across calls.
Tool calling end to end
Tool calling lets the model ask your code to run a function. You describe functions in the tools list, the model replies with tool_calls carrying a name and JSON arguments, you run the function, and you send the result back as a message with role: "tool". Then you call the API again for the final answer. tool_choice controls whether the model may pick a tool or must.
import json, os
from openai import OpenAI
client = OpenAI(base_url="https://api.minimaxapi.top/v1", api_key=os.environ["API_KEY"])
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current temperature for a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
def get_weather(city: str) -> str:
return json.dumps({"city": city, "temp_c": 14}) # stand-in for a real lookup
messages = [{"role": "user", "content": "Is it warm in Lisbon right now?"}]
first = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools, tool_choice="auto"
)
msg = first.choices[0].message
if msg.tool_calls:
messages.append(msg.model_dump(exclude_none=True))
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": get_weather(**args),
})
final = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
print(final.choices[0].message.content)
else:
print(msg.content)Streaming also works with tools, and tool_calls arrive in pieces that you assemble by index before parsing the arguments. Models of this class sometimes produce arguments that are almost-valid JSON, so validate before executing anything with side effects, and never pass model output straight into a shell or a database query.
Sampling parameters, headers and plain fetch
The parameters temperature, top_p, stop, seed and the frequency and presence penalties are passed through to the model. The next example uses plain fetch in Node with no SDK at all, which is useful for edge functions and quick scripts. It also reads the response headers: X-Balance-USD for the remaining credit and X-Request-Id for support questions.
const res = await fetch("https://api.minimaxapi.top/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "uncensored",
messages: [{ role: "user", content: "Name three uses for a rubber duck." }],
seed: 42,
temperature: 0.2,
stop: ["\n\n"],
}),
});
console.log("balance:", res.headers.get("X-Balance-USD"));
console.log("request id:", res.headers.get("X-Request-Id"));
const data = await res.json();
console.log(data.choices[0].message.content);
console.log(data.usage);A fixed seed with a low temperature makes outputs far more repeatable, which helps when you compare two prompt versions. Do not rely on identical output byte for byte across days, since the service runs on an independent provider's infrastructure and may change. For creative work, a temperature near 0.9 and a mild presence penalty reduce repetition in long scenes.
Prompting habits that make examples behave
The code is only half of a good result. The model follows the system message closely, so put standing rules there and keep the user message for the task. For fiction and roleplay, name the setting, the tone and the point of view in the system prompt once, and let the conversation carry on from there. For extraction and classification, show one or two sample inputs with the exact output you want. Few-shot examples cost input tokens, but a 300-token example set at $0.15 per 1M adds $0.000045 per call, which is almost nothing next to the benefit of consistent output.
Keep the use inside what the service allows: lawful adult content such as fiction, companion apps and unfiltered brainstorming. One rule has no exceptions, and it is the ban on sexual content involving minors. Build that check into any app where users write the prompts.
When a result looks wrong, look at the request first. Print the final messages list before you send it. Most surprises come from a stale system prompt, an assistant turn that was never appended, or history that grew past what you meant to send. Then check the finish reason in the response and the token counts in usage. If the output stopped mid-sentence, you either hit your own max_tokens or a stop sequence you forgot about.
Handling 429 errors in code
Two kinds of 429 exist. The error code rate_limited means you exceeded 300 requests per minute on a full key, or 60 on a trial key. The code concurrency means too many requests are in flight at once. A temporary overload also returns 429, with a Retry-After: 5 header. Nothing is charged for a failed request.
import os, time
from openai import OpenAI, RateLimitError
client = OpenAI(base_url="https://api.minimaxapi.top/v1", api_key=os.environ["API_KEY"], max_retries=0)
def ask(prompt: str, tries: int = 4) -> str:
for attempt in range(tries):
try:
r = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
)
return r.choices[0].message.content
except RateLimitError as err:
wait = 5 * (attempt + 1)
print("429, waiting", wait, "s:", err.response.headers.get("Retry-After"))
time.sleep(wait)
raise RuntimeError("still rate limited")
print(ask("Say hello in five languages."))The pattern is wait, then retry, with a longer wait each time. For batch jobs, add a semaphore sized below your concurrency limit so you rarely see the error at all. More detail on limits and the full parameter list is in the API docs, and the pricing page shows how top-ups and bonuses work if you need more credit than the trial gives. The cost analysis is a good next read before you size a larger workload.
