EN ▾

MiniMax API in Python: Use the OpenAI SDK

You do not need a special client to call this API from Python. The standard openai package works once you set the base URL and key, and this guide covers chat, streaming, JSON, tools, retries and cost math.

Updated

A ribbon of glowing code brackets weaving through stacked API layers, representing Python calling an API

Key points

  • Install openai, then pass base_url https://api.minimaxapikey.com/v1 and your key to the client.
  • Use the model ID uncensored for chat, streaming, JSON mode and tool calling.
  • Handle HTTP 429 with backoff, and cap threads at 8 for a full key, 2 for a trial key.
  • Read usage from each response and multiply by $0.15 and $0.50 per 1M tokens to track spend.

Install and make the first call

For minimax api python work, the quickest route is the official openai package from PyPI. The service behind this site is a hosted, OpenAI-compatible API run by an independent provider, so there is no separate SDK to learn. It is not the vendor's own platform, and the only changes from a stock OpenAI script are the base URL, the key and the model name.

pip install --upgrade openai
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.minimaxapikey.com/v1",
    api_key=os.environ["UNCENSORED_KEY"],
)

resp = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "Answer in plain English, briefly."},
        {"role": "user", "content": "What does a context window limit?"},
    ],
)
print(resp.choices[0].message.content)
print(resp.usage)

Get the key from the API key page. New accounts can claim $0.50 of trial credit there with one click, no card needed, and it stays valid for 7 days. Keep the key in an environment variable as shown rather than pasting it into source files.

Sampling parameters and max_tokens

The usual knobs are passed through: temperature, top_p, stop, seed, and the frequency and presence penalties. A fixed seed with a low temperature gives you more repeatable outputs for tests, though you should not treat it as a guarantee of identical text.

resp = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "List five verbs for a changelog."}],
    temperature=0.3,
    top_p=0.9,
    stop=["\n\n"],
    seed=42,
    max_tokens=120,
)

max_tokens is optional. Without it, the completion can use whatever is left of the 100,000-token window after your prompt. That is useful for long documents, but set a cap in production code. A runaway generation costs real output tokens at $0.50 per 1M, and a cap puts a ceiling on the damage from a bad prompt.

Streaming responses

Pass stream=True and iterate. The response is delivered as server-sent events, and the SDK turns them into chunk objects. Print the delta text as it arrives for a chat interface that feels responsive.

stream = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Write a short product description for a notebook."}],
    stream=True,
)

parts = []
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        piece = chunk.choices[0].delta.content
        parts.append(piece)
        print(piece, end="", flush=True)
print()
text = "".join(parts)

Usage numbers are sent at the end of the stream. If your SDK version exposes a usage attribute on the last chunk, read it there; otherwise count tokens on your side for budgeting. One practical point: a streamed request holds its concurrency slot until the stream finishes. If you open eight long streams on a full key, a ninth request will get a 429 with the code concurrency until one completes. Always close or fully consume a stream so the slot is released.

JSON mode for structured output

When you need machine-readable output, set response_format to a JSON object. Mention JSON in the prompt as well, and describe the keys you want, because the format flag guarantees valid JSON syntax but not your schema.

import json

resp = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "Reply only with JSON using keys: title, tags (list of strings)."},
        {"role": "user", "content": "Summarise: a tutorial on caching HTTP responses in Python."},
    ],
    response_format={"type": "json_object"},
)

data = json.loads(resp.choices[0].message.content)
print(data["title"], data["tags"])

Still validate the result. Check that required keys exist and have the right types before you use them, and decide what your code does when they do not, such as retrying once with a clearer instruction. A thin validation layer, even a few isinstance checks, saves a lot of production debugging.

Tool calling

Tool calling follows the OpenAI shape. You describe functions in tools, optionally force a choice with tool_choice, and the model returns tool_calls with JSON arguments. You run the function and send the result back as a message with role: "tool".

import json

def get_rate(currency):
    rates = {"EUR": 0.92, "GBP": 0.79}
    return json.dumps({"currency": currency, "per_usd": rates.get(currency)})

tools = [{
    "type": "function",
    "function": {
        "name": "get_rate",
        "description": "Exchange rate per 1 USD for a currency code.",
        "parameters": {
            "type": "object",
            "properties": {"currency": {"type": "string"}},
            "required": ["currency"],
        },
    },
}]

messages = [{"role": "user", "content": "How many EUR is 50 USD?"}]
first = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
msg = first.choices[0].message
messages.append(msg)

for call in msg.tool_calls or []:
    args = json.loads(call.function.arguments)
    messages.append({"role": "tool", "tool_call_id": call.id, "content": get_rate(args["currency"])})

final = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
print(final.choices[0].message.content)

The rates in this example are made up for the demo. In real code the function would call your own service. Parse arguments defensively with json.loads inside a try block, since a model can occasionally emit malformed arguments.

Rate limits, retries and parallel work

A full key allows 8 concurrent requests and 300 per minute; a trial key allows 2 concurrent and 60 per minute. Going over returns HTTP 429. The error code is rate_limited for the per-minute cap and concurrency for too many simultaneous calls. Temporary overload also gives a 429, with a Retry-After: 5 header. The OpenAI SDK retries some failures on its own, and you can raise that with max_retries. For batch jobs, add your own limit on threads so you stay under the cap by design instead of by retrying.

from concurrent.futures import ThreadPoolExecutor
from openai import OpenAI, RateLimitError
import os, time

client = OpenAI(
    base_url="https://api.minimaxapikey.com/v1",
    api_key=os.environ["UNCENSORED_KEY"],
    max_retries=2,
)

def ask(prompt):
    for attempt in range(4):
        try:
            r = client.chat.completions.create(
                model="uncensored",
                messages=[{"role": "user", "content": prompt}],
                max_tokens=200,
            )
            return r.choices[0].message.content
        except RateLimitError:
            time.sleep(5 * (attempt + 1))
    return None

prompts = [f"Write one tagline for product {i}." for i in range(20)]
with ThreadPoolExecutor(max_workers=8) as pool:
    results = list(pool.map(ask, prompts))

Use max_workers=2 on a trial key. The async client, AsyncOpenAI, takes the same arguments; pair it with an asyncio.Semaphore(8) to enforce the same ceiling. The docs list the response headers you can inspect for limits.

Keeping conversation history

The API is stateless. It does not remember the previous call, so a multi-turn chat works by sending the whole conversation each time. Keep a list of messages, append the user turn, call the API, then append the assistant reply before the next round.

history = [{"role": "system", "content": "You are a patient Python tutor."}]

def chat(user_text):
    history.append({"role": "user", "content": user_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(chat("What is a list comprehension?"))
print(chat("Show me one with a filter."))

This pattern has a cost that grows with every turn: each request pays for all earlier turns again as input tokens. With a 100,000-token window you have a lot of room, but long sessions get expensive and slow. A simple policy is to keep the system message and the last N turns, or to ask the model for a short summary of older turns and replace them with it. Decide on a policy early, because retrofitting trimming into a chat app is more awkward than building it in.

Handling errors beyond 429

The SDK raises typed exceptions, and sorting them is worth a few lines. Authentication problems and bad requests will not fix themselves on retry, while network errors and overload usually will. Treat them differently.

import openai

try:
    r = client.chat.completions.create(
        model="uncensored",
        messages=[{"role": "user", "content": "Hello"}],
        timeout=60,
    )
except openai.AuthenticationError:
    print("Check the API key and the Bearer header.")
except openai.RateLimitError as e:
    print("Slow down:", e.response.headers.get("Retry-After"))
except openai.APIConnectionError:
    print("Network problem, retry with backoff.")
except openai.APIStatusError as e:
    print("Server said", e.status_code, e.response.headers.get("X-Request-Id"))

When you contact support, include the value of X-Request-Id from the failing call. It identifies that exact request. Set an explicit timeout as shown, since the default is long, and a stuck call that holds a concurrency slot quietly cuts your throughput. Failed or refused requests are not charged, so retrying a failed call does not double the bill.

A small project layout that scales

Scripts grow into services. A little structure at the start keeps the API details in one place, so a later change to the model name, the timeout or the limits touches one file instead of twenty.

# llm.py
import os
from openai import OpenAI

BASE_URL = "https://api.minimaxapikey.com/v1"
MODEL = "uncensored"

_client = OpenAI(base_url=BASE_URL, api_key=os.environ["UNCENSORED_KEY"], timeout=60, max_retries=2)

def complete(messages, **kwargs):
    r = _client.chat.completions.create(model=MODEL, messages=messages, **kwargs)
    return r.choices[0].message.content, r.usage

Every other module imports complete and never builds a client. That single seam is where you add logging, a spend counter or a semaphore later. If you want more reference material, the docs page shows the same endpoints in curl form, which is handy for comparing a failing Python call against a known-good request.

Version pinning helps too. Pin the openai package in your requirements file and upgrade on purpose, reading the release notes first, because SDK changes can alter exception names or default retry behaviour. Pair that with a short README note stating which base URL and model ID the project expects, so a new teammate can run it on day one without asking.

One last point on testing. Write at least one test that runs against a fake client, so your suite does not spend credit or depend on the network. Keep a single live smoke test, run by hand or in a nightly job, to catch changes in the real API early.

Tracking balance and cost in code

Every response carries X-Balance-USD, and the SDK lets you read headers through with_raw_response. Logging it after each call is a cheap way to catch a drained balance before your users do.

raw = client.chat.completions.with_raw_response.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Say hello in French."}],
)
print("balance:", raw.headers.get("X-Balance-USD"))
print("request id:", raw.headers.get("X-Request-Id"))
resp = raw.parse()

def cost_usd(usage):
    return usage.prompt_tokens * 0.15 / 1_000_000 + usage.completion_tokens * 0.50 / 1_000_000

print(cost_usd(resp.usage))

A worked check of the formula: a call with 2,000 input tokens and 500 output tokens costs 2,000 x 0.15 / 1,000,000 = $0.0003 for input, plus 500 x 0.50 / 1,000,000 = $0.00025 for output, so $0.00055. A thousand such calls come to $0.55. Failed or refused requests are not charged, so a log built from successful usage objects will match the bill closely.

Billing is pay as you go from prepaid credit with no subscription. Top-ups run from $20 to $500 in any whole amount, with bonuses from $50, and the credit never expires; the details are on the pricing page. Prompts are not used for training.

Questions and answers

Is there a separate MiniMax Python package?

You do not need one here. This service is OpenAI-compatible, so the regular openai package works with a custom base_url. It is an independent service, not the vendor's official SDK.

Does the async client work?

Yes. AsyncOpenAI takes the same base_url and api_key arguments. Keep the number of in-flight requests at or below your concurrency limit.

How do I get token counts?

Each non-streamed response has a usage object with prompt_tokens and completion_tokens. For streams, usage is sent at the end, so read it from the final chunk if your client exposes it.

What context length can I use?

The window is 100,000 tokens, shared between prompt and completion. max_tokens is optional.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.

Get API key