Mistral API Python: Use an OpenAI-Compatible Endpoint
Updated
If you are looking for a Mistral API Python example, the shortest working path is the openai package pointed at a different base URL. This page covers that path, plus streaming, tools, JSON mode and 429 handling.
Key points
- Install the openai package, set base_url to https://api.mistralapi.cc/v1 and use the model ID uncensored.
- Streaming, tool calling and JSON mode work through the normal SDK parameters.
- Catch RateLimitError and cap your thread pool at 8 so you stay inside the concurrency limit.
- This is an independent host, not the official API of Mistral or any vendor.

On this page
A working call in under a minute
A Mistral API Python script usually means one of two things: the vendor's own client library, or a generic OpenAI-style client. This service speaks the OpenAI protocol, so the second route applies. You do not need a special package. Install the standard SDK:
pip install openai
Then create a client with the base URL of this API and your key, and call the chat completions endpoint:
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.mistralapi.cc/v1",
api_key=os.environ["API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain Python generators in three sentences."},
],
temperature=0.7,
)
print(resp.choices[0].message.content)
print(resp.usage)
That is the whole integration. Two lines differ from a stock OpenAI script: base_url and the model name uncensored. A note on what this is: the service runs one open-weight model, hosted by an independent provider, tuned to answer without content refusals for lawful adult use. It is not the official API of Mistral or any other vendor. You can create a key on the API key page, and new users can claim $0.50 of trial credit there with one click.
Keep the key out of your code
Hard-coded keys end up in git history. Put the key in an environment variable and read it at start-up, as the example above does. On macOS or Linux:
export API_KEY="paste-your-key-here"
python app.py
On Windows PowerShell, use $env:API_KEY = "paste-your-key-here" for the current session. For a project, a .env file loaded with python-dotenv works well, as long as .env is in your .gitignore. Authentication is the usual header, Authorization: Bearer <key>, which the SDK adds for you.
Two methods exist: POST /v1/chat/completions and GET /v1/models. The models call is handy as a health check, because it confirms your key and base URL in one request:
from openai import OpenAI
import os
client = OpenAI(base_url="https://api.mistralapi.cc/v1", api_key=os.environ["API_KEY"])
for m in client.models.list():
print(m.id)
ping = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Reply with the word ok."}],
max_tokens=5,
)
print(ping.choices[0].message.content)
If this prints uncensored, your setup is correct and any later problem lies in the request itself.
Streaming tokens as they arrive
For chat interfaces, stream the answer so the user sees text immediately. Pass stream=True and iterate over the chunks. Server-sent events carry the usage at the end if you ask for it:
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write a short story opening about a lighthouse."}],
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 chunk.usage:
print("\ntokens:", chunk.usage.total_tokens)
One detail matters for capacity planning: a streamed request holds its concurrency slot until the stream ends. A full key allows 8 requests at once, so eight slow streams fill the pool and the ninth gets a 429 with the error code concurrency, even if your requests-per-minute count is low.
JSON mode and tool calling
Structured output is supported through JSON mode. Tell the model in the prompt that you want JSON, and set the response format so the reply is a valid object:
import json
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "Reply with a JSON object with keys city and country."},
{"role": "user", "content": "Where is the Eiffel Tower?"},
],
response_format={"type": "json_object"},
)
data = json.loads(resp.choices[0].message.content)
print(data["city"], data["country"])
Tool calling follows the standard shape: you describe functions in tools, the model answers with tool_calls, you run the function, and you return the result as a message with role: "tool".
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current temperature for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
messages = [{"role": "user", "content": "What is the weather in Lisbon?"}]
first = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools, tool_choice="auto"
)
msg = first.choices[0].message
if msg.tool_calls:
call = msg.tool_calls[0]
messages.append(msg)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps({"city": "Lisbon", "temp_c": 21}),
})
final = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools
)
print(final.choices[0].message.content)
Always validate tool arguments before you act on them. The model returns them as a JSON string, and a model can produce a malformed one.
Handle 429 errors and stay inside the limits
The limits are specific. A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent and 60 per minute. Past a limit you get HTTP 429 with the code rate_limited (too many per minute) or concurrency (too many at once). Under temporary overload the API also answers 429 with a Retry-After: 5 header.
The openai SDK retries some errors on its own, two times by default. Raise that number, and bound your own parallelism so you rarely hit the wall in the first place:
from concurrent.futures import ThreadPoolExecutor
import openai
client = openai.OpenAI(
base_url="https://api.mistralapi.cc/v1",
api_key=os.environ["API_KEY"],
max_retries=4,
timeout=120,
)
def ask(prompt):
try:
r = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
)
return r.choices[0].message.content
except openai.RateLimitError as e:
return "rate limited: " + str(e)
prompts = ["Define idempotent.", "Define monad.", "Define closure."]
with ThreadPoolExecutor(max_workers=8) as pool:
for answer in pool.map(ask, prompts):
print(answer)
Use max_workers=2 on a trial key. Each response also carries X-Request-Id for support questions, X-Balance-USD for your remaining credit, and the two X-RateLimit-Limit-* headers. Read them with the raw-response wrapper:
raw = client.chat.completions.with_raw_response.create(
model="uncensored",
messages=[{"role": "user", "content": "Say hello."}],
)
print(raw.headers.get("X-Balance-USD"), raw.headers.get("X-Request-Id"))
resp = raw.parse()
print(resp.choices[0].message.content)Async code and long inputs
For web backends and bulk jobs, the async client is a better fit than threads. It has the same arguments:
import asyncio, os
from openai import AsyncOpenAI
client = AsyncOpenAI(base_url="https://api.mistralapi.cc/v1", api_key=os.environ["API_KEY"])
sem = asyncio.Semaphore(8)
async def ask(prompt):
async with sem:
r = await client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
)
return r.choices[0].message.content
async def main():
results = await asyncio.gather(*(ask(f"Give fact number {i} about Python.") for i in range(20)))
for r in results:
print(r)
asyncio.run(main())
The semaphore does the same job as max_workers: it caps in-flight requests at 8. The context window is 100,000 tokens for prompt and completion combined, and the maximum request body is 8 MB. max_tokens is optional, because the completion may use whatever the window has left, but setting it protects you from a long reply you did not want to pay for. Parameters such as temperature, top_p, stop, seed and the penalties are passed through to the model.
Multi-turn chat and tracking cost
The API is stateless. It does not remember earlier requests, so a conversation works by resending the history each time. A small loop shows the pattern, and it also tallies spend from the usage numbers in every response:
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.mistralapi.cc/v1", api_key=os.environ["API_KEY"])
history = [{"role": "system", "content": "You are a helpful writing partner."}]
tokens_in = tokens_out = 0
while True:
user = input("you> ")
if user in ("quit", "exit"):
break
history.append({"role": "user", "content": user})
r = client.chat.completions.create(model="uncensored", messages=history)
reply = r.choices[0].message.content
history.append({"role": "assistant", "content": reply})
tokens_in += r.usage.prompt_tokens
tokens_out += r.usage.completion_tokens
cost = tokens_in * 0.15 / 1_000_000 + tokens_out * 0.50 / 1_000_000
print(reply)
print(f"[session cost so far: ${cost:.5f}]")
Notice that prompt_tokens grows with every turn, because the whole history is sent again. A chat that reaches 20,000 tokens of history pays for those 20,000 input tokens on the next request, at $0.15 per 1M, which is $0.003. That is cheap, but a long roleplay session adds up over thousands of turns. When the history gets long, drop the oldest turns or replace them with a short summary that you generate with the same model.
The window is 100,000 tokens in total, so plan a cut-off well before you reach it. A simple rule is to keep the system prompt, the last 20 messages and a running summary of everything older.
Common errors and how to fix them
Most first-run problems come down to four causes. Work through them in this order:
- 401 or an authentication error. The key is missing, truncated or wrongly exported. Print
os.environ.get("API_KEY")length, not the key itself, to confirm the variable is set in the shell that runs Python. - 404 on the request. The base URL is wrong. It must end in
/v1, and the SDK appends/chat/completionsby itself. Do not add that path tobase_url. - Model not found. The model ID is
uncensored, all lowercase. Names from other vendors do not exist here. - 429 on the very first call. Another process is using the same key, or an earlier streaming request is still open and holding a concurrency slot.
If a request fails for a reason you cannot explain, note the X-Request-Id header and send it with your question through the support page. It lets the operator find the exact request.
Timeouts deserve a word too. A long completion from a large prompt can take a while to finish, and the SDK default timeout may be shorter than you expect for a reply of several thousand tokens. Set an explicit timeout on the client, as in the retry example above, and prefer streaming for long outputs so your program receives text steadily instead of waiting for one large response. Also keep your own logs of usage per request. They make it easy to spot a prompt that suddenly grew ten times larger because a bug appended the same document twice.
Moving over from a vendor SDK
If your code currently uses the vendor's own Python package, the migration is usually small, because the message list of role and content pairs is the same idea across chat APIs. Replace the client construction, change the method to client.chat.completions.create, and read the reply from choices[0].message.content. Check each vendor-specific argument against the vendor's documentation, since names and defaults differ between libraries.
Test three things before you switch traffic: that your prompts still produce the output format you need, that tool calling behaves as you expect with your function schemas, and that your rate of requests fits the limits above. Remember what is not offered: no embeddings, no image, audio or video, no fine-tuning. If your project needs any of those, keep that part on the vendor.
The documentation lists the endpoints and parameters in one place, and the pricing page shows the costs: $0.15 per 1M input tokens and $0.50 per 1M output tokens, billed from prepaid credit. A request with 2,000 input and 500 output tokens costs $0.00055.
More guides
Questions and answers
Do I need a special Python package?
No. The standard openai package works. Set base_url to https://api.mistralapi.cc/v1, pass your key, and use the model ID uncensored.
Is this the official Mistral API?
No. It is an independent host running one open-weight model, and it is not the official API of Mistral or any other vendor.
Why do I get a 429 error?
You passed a limit. The code rate_limited means too many requests per minute, and concurrency means too many at once. A full key allows 8 concurrent and 300 per minute.
Does streaming work with the Python SDK?
Yes. Pass stream=True and iterate over the chunks. Add stream_options with include_usage to receive token counts at the end.
Can I test without paying?
Yes. After sign-up you can claim $0.50 of trial credit with one click on the API key page. It is valid for 7 days and needs no card.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.