Mistral API in Python With the OpenAI SDK
A mistral api python script can run against this OpenAI-compatible endpoint with the standard openai package: set the base URL, pass your key and use model uncensored. This guide has the code for chat, streaming, JSON, tools and batches.
Updated

The short version
To use a mistral api python workflow against this service, you do not need Mistral's own client library. This endpoint speaks the OpenAI chat completions format, so the standard openai package works: install it, set the base URL to https://api.mistralapikey.com/v1, pass your key and use the model ID uncensored.
A necessary note: this is not Mistral's official API, and it is not affiliated with Mistral. It is a separate service with one open-weight model, run by an independent provider and tuned to answer without content refusals for lawful adult use. The page about the Mistral API key explains how keys here relate to other services.
pip install openai
from openai import OpenAI
client = OpenAI(base_url="https://api.mistralapikey.com/v1", api_key="YOUR_KEY")
r = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write a haiku about retries."}],
)
print(r.choices[0].message.content)Translate Mistral-style code line by line
If you have code written for the Mistral Python client, the mapping is short. Check the exact names against the client's own documentation for the version you have installed, as libraries change.
| Mistral-style client | OpenAI SDK against this endpoint |
|---|---|
Mistral(api_key=key) | OpenAI(base_url=URL, api_key=key) |
client.chat.complete(...) | client.chat.completions.create(...) |
client.chat.stream(...) | client.chat.completions.create(..., stream=True) |
model="some-model-name" | model="uncensored" |
res.choices[0].message.content | r.choices[0].message.content (same) |
Messages stay a list of dicts with role and content. The response shape for the common fields, including choices, usage and finish_reason, is also the same, so code that only reads those needs no change.
Side by side, the change looks like this:
# before (Mistral-style)
# from mistralai import Mistral
# client = Mistral(api_key=KEY)
# res = client.chat.complete(model="...", messages=msgs)
# after
from openai import OpenAI
client = OpenAI(base_url="https://api.mistralapikey.com/v1", api_key=KEY)
res = client.chat.completions.create(model="uncensored", messages=msgs)
text = res.choices[0].message.contentKeep the key out of the code
Read the key and the URL from the environment, and keep them out of version control.
import os
from openai import OpenAI
client = OpenAI(
base_url=os.environ.get("LLM_BASE_URL", "https://api.mistralapikey.com/v1"),
api_key=os.environ["LLM_API_KEY"],
)
With a shell: export LLM_API_KEY=.... The OpenAI SDK also reads OPENAI_API_KEY and OPENAI_BASE_URL when you do not pass them explicitly, which is useful for tools that build the client for you, but also a classic source of "wrong key" bugs when an old value sits in the shell. When something fails with 401, print which variables are set before you do anything else.
Get a key on the API key page. New accounts can claim $0.50 of trial credit with one click. It needs no card, is valid for 7 days and is limited to one per person.
Streaming, JSON and tools
Streaming returns tokens as they are generated. Set stream=True and iterate. Usage data arrives at the end.
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Explain list comprehensions in 3 sentences."}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
JSON mode asks for a valid JSON object. Say the word JSON in your prompt as well, and always parse defensively.
import json
r = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Return JSON with keys name and tags for a blog post about retries."}],
response_format={"type": "json_object"},
)
data = json.loads(r.choices[0].message.content)
Tool calling uses the tools and tool_choice parameters. When the model returns tool_calls, run the function and send the result back as a message with role: "tool" and the matching tool_call_id.
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
r = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Weather in Oslo?"}],
tools=tools,
)
print(r.choices[0].message.tool_calls)Async and parallel calls
For batches, use the async client. Keep the number of in-flight requests under the limit: a full key allows 8 concurrent requests and 300 per minute, a trial key 2 and 60.
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI(base_url="https://api.mistralapikey.com/v1", api_key="YOUR_KEY")
sem = asyncio.Semaphore(6)
async def one(prompt):
async with sem:
r = await client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
max_tokens=200,
)
return r.choices[0].message.content
async def main():
prompts = [f"Give a one-line tip number {i} about Python." for i in range(20)]
results = await asyncio.gather(*(one(p) for p in prompts))
print(len(results))
asyncio.run(main())
The semaphore of 6 leaves headroom under 8. Without it, 20 simultaneous calls would hit HTTP 429 with the code concurrency. Remember that streams hold their slot until they finish.
Pitfalls when migrating
Most problems come from assumptions carried over from the old setup rather than from the new endpoint.
- Hard-coded model names. Search your code for the old model string. The only valid model ID here is
uncensored, and you can confirm that withclient.models.list(). - Prompts written for another model. A different model reads instructions a little differently. If a system prompt relied on specific phrasing, test it. Short, direct instructions with an example of the output format usually transfer best.
- Provider-specific parameters. Parameters that exist only in one vendor's client may be ignored or rejected. Stick to the standard ones: temperature, top_p, stop, seed, max_tokens and the penalties are passed through.
- Safe-mode style flags. If your old code turned on a provider's moderation or safety option, there is no equivalent switch here. If your product needs filtering, add it on your side before and after the call.
- Token estimates. Different models count tokens differently, so budget from the
usagefield the API returns, not from a local guess.
Plan on a short test pass, not a rewrite. Take ten prompts from your logs, run them through the new client, read the answers and adjust the system prompt until the tone matches what you want.
Errors and what they mean
- 401. Wrong or missing key, or a key from another service.
- 404. The base URL is missing
/v1. - 429 with
rate_limited. More than the per-minute limit. Wait and slow down. - 429 with
concurrency. Too many requests at once. Lower your parallelism. - 429 with
Retry-After: 5. Temporary overload. Wait five seconds and try again.
import time
from openai import RateLimitError
def safe(prompt):
for _ in range(4):
try:
r = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
)
return r.choices[0].message.content
except RateLimitError:
time.sleep(5)
return None
Save the X-Request-Id header from failing calls. Failed or refused requests are not charged.
Cost, limits and what is not included
Billing is pay as you go: $0.15 per 1M input tokens and $0.50 per 1M output tokens, prepaid, with no subscription and no expiry. A script that sends 1,000 requests of 1,500 input and 400 output tokens costs 1.5M x $0.15 = $0.225 plus 0.4M x $0.50 = $0.20, so $0.425. Top-ups run from $20 to $500, with a bonus from $50, and the pricing page lists the details.
The context window is 100,000 tokens, prompt plus completion, and the body can be up to 8 MB. The service is text only: no images, audio or video, no embeddings and no fine-tuning, and sexual content involving minors is never allowed. If you also want the same API with other clients, the article on the OpenAI-compatible chat API covers apps beyond Python, and the docs list every parameter.
More guides
Questions and answers
Do I need the Mistral Python client?
No. The standard openai package works with the base URL https://api.mistralapikey.com/v1. Mistral-style calls map to chat.completions.create.
Is this Mistral's official API?
No. It is a separate service with one open-weight model run by an independent provider, not affiliated with Mistral.
How do I avoid 429 errors in batches?
Cap parallel calls below 8 with a semaphore, stay under 300 requests per minute and wait after a 429 response.
Is there a free way to test?
Yes. After sign-up you can claim $0.50 of trial credit on the API key page. It needs no card and is valid for 7 days.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.