Mistral API Python Example With the OpenAI SDK
Updated
Copy-paste Python for a hosted, OpenAI-compatible endpoint. Each snippet runs with the official openai package and a changed base URL.
Key points
- Install the openai package, set the base URL and your key, and use the model ID uncensored.
- Streaming, JSON mode and tool calling work through the normal SDK arguments.
- Handle HTTP 429 with a short retry, and keep async concurrency at 8 or below on a full key.
- A typical short chat call costs a fraction of a cent at $0.15 and $0.50 per 1M tokens.

The short version
If you searched for a mistral api python example, here is the honest framing first. This site does not run the official Mistral API. It hosts one open-weight model, tuned to answer without content refusals for lawful adult use, behind an OpenAI-compatible endpoint. Because the protocol is the OpenAI one, the Python you already know applies: install the openai package, point it at a new base URL, and send chat requests.
The smallest working program is below. Replace the key with your own from the API key page. The model ID is always uncensored.
from openai import OpenAI
client = OpenAI(
base_url="https://api.mistraluncensored.top/v1",
api_key="YOUR_KEY",
)
resp = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write a two-line poem about a lighthouse."}],
)
print(resp.choices[0].message.content)That is the whole integration. Everything else in this article is a variation on those few lines: streaming the output, forcing JSON, calling tools, retrying politely, and running many requests at once.
Install and configure the client
You need Python 3.8 or newer and one package: pip install openai. Any recent version of the SDK works, because the endpoint only uses the standard chat completions route. Two methods exist on the server: POST /v1/chat/completions and GET /v1/models. There is no embeddings route and no image route, so do not try to call those through the same client.
Keep the key out of your source files. Read it from an environment variable and pass it in. The example below also lists the available models, which doubles as a connectivity test.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.mistraluncensored.top/v1",
api_key=os.environ["API_KEY"],
)
# GET /v1/models: should list the model ID "uncensored"
for m in client.models.list():
print(m.id)
# The model ID you send in chat requests
MODEL = "uncensored"Run it once from a shell where API_KEY is exported. If the model list prints, your base URL and key are correct. If the call fails right away, the usual causes are a stray space in the key, a base URL that is missing the /v1 suffix, or an empty balance. The response headers include X-Balance-USD, so you can read the remaining credit without opening a dashboard. The SDK exposes headers through client.chat.completions.with_raw_response.create(...) if you want to log them.
A conversation with a system prompt
Chat models are stateless. The server does not remember earlier turns, so your code keeps the message list and sends it back each time. A small class makes that tidy.
from openai import OpenAI
client = OpenAI(base_url="https://api.mistraluncensored.top/v1", api_key="YOUR_KEY")
class Chat:
def __init__(self, system):
self.messages = [{"role": "system", "content": system}]
def say(self, text, **kw):
self.messages.append({"role": "user", "content": text})
r = client.chat.completions.create(
model="uncensored",
messages=self.messages,
temperature=0.8,
**kw,
)
reply = r.choices[0].message.content
self.messages.append({"role": "assistant", "content": reply})
return reply
bot = Chat("You are a blunt editor for adult fiction writers. Keep answers short.")
print(bot.say("Give me three ways to open a scene in a night train."))
print(bot.say("Expand the second one."))Sampling parameters such as temperature, top_p, stop, seed and the frequency and presence penalties are passed through to the model. Setting seed together with a low temperature gives repeatable output for tests, though you should not treat it as a hard guarantee across model updates.
The context window is 100,000 tokens, counting the prompt and the completion together. A long chat history will eventually hit that ceiling, so trim old turns or summarize them once your list grows. max_tokens is optional, because the completion may use whatever room is left in the window. Set it anyway when you want a hard cap on cost per call.
Streaming tokens as they arrive
For interactive tools you want words on screen as they are generated. Pass stream=True and iterate. The server sends Server-Sent Events, the SDK parses them for you, and a usage block arrives at the end of the stream.
from openai import OpenAI
client = OpenAI(base_url="https://api.mistraluncensored.top/v1", api_key="YOUR_KEY")
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Describe a storm over a harbor in 120 words."}],
stream=True,
stream_options={"include_usage": 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("\n\ntokens:", chunk.usage.prompt_tokens, chunk.usage.completion_tokens)One detail matters for production code: a streamed request occupies its concurrency slot until the stream ends. If you open a stream and stop reading it, the slot stays busy. Always consume the iterator to the end or close it explicitly with stream.close() when the user cancels.
JSON mode and tool calling
Structured output
When your program needs to parse the reply, turn on JSON mode with response_format. Also tell the model in the prompt that you want JSON, and name the keys you expect. The setting guarantees a JSON object, not your particular schema, so validate the fields in code.
import json
from openai import OpenAI
client = OpenAI(base_url="https://api.mistraluncensored.top/v1", api_key="YOUR_KEY")
r = client.chat.completions.create(
model="uncensored",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "Reply with JSON: {\"title\": str, \"tags\": [str]}"},
{"role": "user", "content": "Suggest a title and tags for a noir story set in a flooded city."},
],
)
data = json.loads(r.choices[0].message.content)
print(data["title"], data["tags"])Tools
Tool calling follows the OpenAI shape: declare tools, optionally set tool_choice, run the function yourself when the model asks, then send the output back as a message with role: "tool".
import json
from openai import OpenAI
client = OpenAI(base_url="https://api.mistraluncensored.top/v1", api_key="YOUR_KEY")
tools = [{
"type": "function",
"function": {
"name": "roll_dice",
"description": "Roll a die with the given number of sides",
"parameters": {
"type": "object",
"properties": {"sides": {"type": "integer"}},
"required": ["sides"],
},
},
}]
messages = [{"role": "user", "content": "Roll a 20-sided die for my character."}]
first = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
call = first.choices[0].message.tool_calls[0]
sides = json.loads(call.function.arguments)["sides"]
messages.append(first.choices[0].message)
messages.append({"role": "tool", "tool_call_id": call.id, "content": "17"})
final = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
print(final.choices[0].message.content)In a real program, replace the hard-coded "17" with the result of your function. Check that tool_calls is not empty before indexing it, because the model may answer in plain text instead.
Rate limits, retries and async batches
A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent and 60 per minute. Past either limit you get HTTP 429. The error code tells you which one: rate_limited means too many requests per minute, concurrency means too many at once. On temporary overload the server also returns 429 with a Retry-After: 5 header.
The openai SDK retries a couple of times by default, but explicit control is better when you batch work. The pattern below uses a semaphore sized to your key and a small retry wrapper.
import asyncio
from openai import AsyncOpenAI, RateLimitError
client = AsyncOpenAI(base_url="https://api.mistraluncensored.top/v1", api_key="YOUR_KEY", max_retries=0)
sem = asyncio.Semaphore(8) # use 2 on a trial key
async def ask(prompt, tries=4):
async with sem:
for attempt in range(tries):
try:
r = await client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
max_tokens=300,
)
return r.choices[0].message.content
except RateLimitError:
await asyncio.sleep(5 * (attempt + 1))
return None
async def main():
prompts = [f"Give one story idea about harbor number {i}." for i in range(40)]
results = await asyncio.gather(*(ask(p) for p in prompts))
print(sum(r is not None for r in results), "done")
asyncio.run(main())Failed or refused requests are not charged, so a retry loop does not double-bill you. The body limit is 8 MB, which matters only if you paste very large documents into the prompt.
What a call costs
Pricing is pay as you go from prepaid credit: $0.15 per 1M input tokens and $0.50 per 1M output tokens. The usage object on every response gives you the counts, so you can compute the bill in the same script.
# endpoint https://api.mistraluncensored.top/v1, model "uncensored"
def cost(prompt_tokens, completion_tokens):
return prompt_tokens * 0.15 / 1_000_000 + completion_tokens * 0.50 / 1_000_000
print(cost(2_000, 500)) # 0.00055
print(cost(50_000, 2_000)) # 0.0085Check the arithmetic by hand. A chat with 2,000 input tokens and 500 output tokens costs 2,000 × $0.15 / 1M = $0.0003 for input plus 500 × $0.50 / 1M = $0.00025 for output, so $0.00055 in total. A heavy call that fills half the window, 50,000 input and 2,000 output, costs $0.0075 + $0.001 = $0.0085. Ten thousand of the small calls come to $5.50.
New accounts can claim $0.50 of trial credit with one click on the key page, valid for 7 days with no card. That covers roughly 900 of the small calls above. Full top-ups start at $20, with a bonus of 5% from $50, 10% from $100 and 15% from $200, payable by crypto. The pricing page has the full table, and the docs list every parameter. Prompts are not used for training.
For a quick overview of what this service is and is not, read the Mistral API explainer. One last point: sexual content involving minors is blocked outright, regardless of framing.
More guides
Questions and answers
Is this the official Mistral Python SDK?
No. You use the standard openai package with a different base URL. The service is an independent host of one open-weight model, not the official API of Mistral or any other vendor.
Which model name do I pass?
Always uncensored. You can confirm it by calling GET /v1/models with your key.
Can I use LangChain or LlamaIndex instead of the raw SDK?
Yes, any client that lets you set an OpenAI-compatible base URL and key will work. Use the same base URL and the model ID uncensored.
Why do I get a 429 error?
You hit the per-minute limit (code rate_limited), the concurrency limit (code concurrency), or a temporary overload with a Retry-After of 5 seconds. Wait and retry, and keep async concurrency within 8 on a full key or 2 on a trial key.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.