Mistral AI is the French lab behind Mistral Large 4, Mistral Small 4 and the Ministral 3 family. Its API is cheap, fast and offers an EU endpoint, which makes it a strong pick for budget apps and EU data rules.
This tutorial takes you from zero to working Python code. You will get a key, make your first call, then add streaming, JSON output and function calling. Every snippet uses the current official SDK.
- Install:
pip install mistralai(we checked version 3.11.0, released 1 Dec 2026, Python 3.10+). Import withfrom mistralai.client import Mistral. - Get a key: Mistral Studio at console.mistral.ai, then API Keys, then New key.
- Free use: the Free mode has no API usage. You need pay-as-you-go credits or a paid plan, or calls fail with HTTP 402.
- Models:
mistral-small-latest($0.15 / $0.60 per 1M tokens) for most apps,mistral-large-4-0($0.70 / $2.10) for hard tasks. - Le Chat: the chatbot is now called Vibe. The API itself did not change.
What the Mistral API Is and When to Use It
The Mistral API is a REST service at https://api.mistral.ai. The main endpoint is POST /v1/chat/completions, which looks very close to the OpenAI Chat Completions format you may already know.
You send a list of messages and get back choices with the model’s reply. The same endpoint handles streaming, JSON output and tools.
Here is when it is a good fit:
- Low budgets: Mistral Small 4 costs $0.15 per million input tokens, one of the lowest prices for a capable model.
- EU data needs: the SDK has built-in EU and US endpoints (
api.eu.mistral.aiandapi.us.mistral.ai). Mistral says regional endpoints cost 10% more. - Open weights: Large 4, Small 4 and Ministral 3 also have open weights, so you can move to self-hosting later.
- Long documents: Mistral Large 4 has a 1M token context window.
If you want to compare it with other providers first, see our AI API pricing comparison.
What Changed Recently (Vibe, Studio, Large 4)
Older Mistral tutorials use names that no longer exist. Here is what is current as of 3 December 2026:
- Le Chat is now Vibe: Mistral renamed its chatbot on 28 May 2026. Vibe has Work, Code and Chat modes. Your plan and history carried over. This is the consumer app, not the API.
- La Plateforme is now Mistral Studio: the developer console became AI Studio in October 2025. The docs now call it Mistral Studio. It still lives at
console.mistral.ai. - Mistral Large 4: public preview on 6 October 2026, then open weights with extra training. It now has Low, Medium and High (default) reasoning modes.
- SDK 3.x: the import path is
mistralai.client. Old code withfrom mistralai import MistralorMistralClientneeds an update. - Codestral retiring:
codestral-latestwas deprecated on 30 November 2026 and retires on 31 December 2026.
Warning: Mistral Medium 3.5 (mistral-medium-latest) and Mistral Large 3 (mistral-large-2512) are deprecated and retire on 30 April 2027. Move that code to Mistral Large 4 now.
Current Mistral Models and API IDs
Use the exact ID in the model field. The -latest aliases move to new versions over time, so pin a dated ID in production if you need stable output.
| Model | API ID (alias) | Context | Best for |
|---|---|---|---|
| Mistral Large 4 | mistral-large-4-0 (mistral-large) |
1M | Hard reasoning, agents, coding, vision |
| Mistral Small 4 | mistral-small-2603 (mistral-small-latest) |
256K | Most apps: chat, tools, JSON, images |
| Ministral 3 14B | ministral-14b-2512 (ministral-14b-latest) |
256K | Cheap mid-size tasks |
| Ministral 3 8B | ministral-8b-2512 (ministral-8b-latest) |
256K | Classification, routing, short replies |
| Ministral 3 3B | ministral-3-3b-25-12 |
Not stated | Tiny, very cheap jobs |
| Mistral Embed | mistral-embed |
n/a | Text embeddings for search |
Mistral also hosts some third-party models, such as GLM 5.3 and DeepSeek V4.1 Flash, plus OCR and Voxtral audio models. To see every ID your key can use, call client.models.list() or GET /v1/models.
Tip: Start with mistral-small-latest. It supports function calling, structured output and image input, and it is the model Mistral uses in its own quickstart.
Get an API Key and Set Up Python
You need Python 3.10 or newer, a terminal, and a Mistral account with API access. The steps below follow the official Studio quickstart.
- Create or sign in to your account. Go to console.mistral.ai. The same login works for Vibe and Studio.
- Turn on API usage. Free mode does not include API calls. Add prepaid credits and enable pay-as-you-go in the Admin Panel under Billing, or move to a plan that includes API usage (Pro, Education or Team).
- Open API Keys. In Studio, open API Keys and click New key.
- Configure the key. Give it a name, set an expiration date, and pick a connector access scope.
- Copy it once. The full key is shown only one time. Save it in a password manager.
- Set an environment variable. On macOS or Linux run
export MISTRAL_API_KEY="your-key". On Windows PowerShell run$env:MISTRAL_API_KEY="your-key". - Install the SDK. Run
pip install -U mistralaiinside a virtual environment. Addpydanticif you plan to use structured output (it is already a dependency).

Note: Never paste a key into your code or commit it to Git. Every example below reads it from MISTRAL_API_KEY.
Your First Chat Call (Python and curl)
This script sends a system message and a user message, then prints the reply and the token count. Save it as chat.py and run python chat.py.
import os
from mistralai.client import Mistral
client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
response = client.chat.complete(
model="mistral-small-latest",
messages=[
{"role": "system", "content": "You are a friendly Python tutor. Keep answers short."},
{"role": "user", "content": "Explain a Python list comprehension in two sentences."},
],
temperature=0.3,
max_tokens=300,
)
print(response.choices[0].message.content)
print("Tokens used:", response.usage.prompt_tokens, "in /", response.usage.completion_tokens, "out")
The reply is in response.choices[0].message.content. The usage object tells you how many tokens you paid for.
Useful parameters
- temperature: lower values (0 to 0.3) give steadier answers. Higher values give more variety.
- max_tokens: caps the length of the reply, which also caps the cost.
- random_seed: makes sampling repeatable for tests.
- reasoning_effort: SDK 3.11 accepts this for reasoning models. Large 4 offers Low, Medium and High modes.
The same call with curl
curl https://api.mistral.ai/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $MISTRAL_API_KEY" \
-d '{
"model": "mistral-small-latest",
"messages": [{"role": "user", "content": "Say hello in French."}]
}'
If this returns JSON with a choices array, your key and billing are set up correctly.
Streaming Responses
Streaming prints the reply word by word, so users are not left staring at a blank screen. Use client.chat.stream() instead of complete(). Each event holds a small delta of text.
import os
from mistralai.client import Mistral
client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
stream = client.chat.stream(
model="mistral-small-latest",
messages=[{"role": "user", "content": "Write a 4-line poem about Paris in winter."}],
)
with stream as events:
for event in events:
delta = event.data.choices[0].delta.content
if delta:
print(delta, end="", flush=True)
print()
The stream works as a context manager, so the with block closes the connection for you. For async apps, use await client.chat.stream_async(...) with async for.
JSON Mode and Structured Output
Mistral gives you two ways to get JSON back. Mistral’s docs say custom structured outputs are more reliable, so use them when you can.
| Mode | How to turn it on | What you get |
|---|---|---|
| Structured output | client.chat.parse(response_format=MyModel) or {"type": "json_schema", ...} |
JSON that follows your exact schema |
| JSON mode | response_format={"type": "json_object"} |
Valid JSON, shape set by your prompt |
Structured output with Pydantic
The SDK turns a Pydantic class into a strict JSON schema, sends it, and parses the reply back into your class.
import os
from pydantic import BaseModel
from mistralai.client import Mistral
class Book(BaseModel):
title: str
author: str
year: int
genres: list[str]
client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
response = client.chat.parse(
model="mistral-small-latest",
messages=[
{"role": "system", "content": "Extract the book details."},
{"role": "user", "content": "Les Miserables was written by Victor Hugo in 1862. It is a historical novel and a tragedy."},
],
response_format=Book,
temperature=0,
)
book = response.choices[0].message.parsed
print(book.title, "|", book.author, "|", book.year, "|", book.genres)
Plain JSON mode
With JSON mode you must also ask for JSON in your prompt. The SDK docstring says you “MUST also instruct the model to produce JSON yourself”.
import os, json
from mistralai.client import Mistral
client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
response = client.chat.complete(
model="mistral-small-latest",
messages=[{
"role": "user",
"content": "List three French cheeses. Reply in JSON with a key 'cheeses' that holds an array of objects with 'name' and 'region'.",
}],
response_format={"type": "json_object"},
)
data = json.loads(response.choices[0].message.content)
for cheese in data["cheeses"]:
print(cheese["name"], "-", cheese["region"])
For a side-by-side look at how other providers do this, read structured outputs for Claude, OpenAI and Gemini.
Function Calling
Function calling lets the model ask your code to run a function, such as a database lookup or a weather API. The model never runs anything itself. It returns a request, you run it, and you send back the result.
The flow has four parts:
- Describe your tools as JSON schema in a
toolslist. - Call the model with
toolsand atool_choice. - Run each tool call from
message.tool_callsand add a"tool"message with the matchingtool_call_id. - Call the model again so it can write the final answer.
import os, json
from mistralai.client import Mistral
client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
MODEL = "mistral-small-latest"
# 1. Your real Python function
def get_weather(city: str) -> dict:
fake_db = {"paris": 7, "london": 9, "berlin": 3}
return {"city": city, "temp_c": fake_db.get(city.lower(), 15)}
# 2. Describe it to the model as a tool
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current temperature in Celsius for a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string", "description": "City name, e.g. Paris"}},
"required": ["city"],
},
},
}]
messages = [{"role": "user", "content": "Is it colder in Paris or Berlin right now?"}]
# 3. First call: the model decides which tools to call
response = client.chat.complete(model=MODEL, messages=messages, tools=tools, tool_choice="auto")
assistant_msg = response.choices[0].message
messages.append(assistant_msg)
# 4. Run each requested tool and send the result back
for call in assistant_msg.tool_calls or []:
args = json.loads(call.function.arguments)
result = get_weather(**args)
messages.append({
"role": "tool",
"name": call.function.name,
"content": json.dumps(result),
"tool_call_id": call.id,
})
# 5. Second call: the model writes the final answer
final = client.chat.complete(model=MODEL, messages=messages, tools=tools)
print(final.choices[0].message.content)
tool_choice and parallel calls
- auto (default): the model decides whether to call a tool.
- any: the model must call a tool. SDK 3.11 also accepts
required. - none: the model must not call tools.
- parallel_tool_calls:
Trueby default, so the model can ask for Paris and Berlin in one turn. Set it toFalseto get one call at a time.
Tip: function.arguments arrives as a JSON string, not a dict. Always run it through json.loads() and check the values before you use them.
Free Tier and Rate Limits
This is the part that has changed most. The old “Experiment” plan let you call the API for free with a verified phone number. Some help pages still describe it, but the current Studio docs say otherwise.
The docs now state that Free mode includes Vibe and Studio usage but no API usage. API keys made in Free mode fail with HTTP 402 (code 2314) until you enable pay-as-you-go with prepaid credits or move to Pro, Education or Team.
Plans and API access
| Plan | Price | API usage |
|---|---|---|
| Free | $0 | None (402 error). Pay-as-you-go credits can be added. |
| Pro | $14.99/month | Separate monthly API allowance, per the docs |
| Education | $5.99/month (students) | Separate monthly API allowance, per the docs |
| Team | $24.99/user/month | Separate monthly API allowance, per the docs |
| Enterprise | Custom | Set by contract |
Mistral changed plan bundles more than once in late 2026, so check your Subscriptions page for the current allowance. Usage past the allowance is drawn from prepaid credits at API rates.
How rate limits work
- Limit types: requests per second, tokens per minute and tokens per month, per model.
- Scope: limits apply to the whole Organization, across all Workspaces. Input and output tokens both count.
- Where to see yours: Admin Panel, then API, then Rate limits. Usage and cost are under API, then Usage.
- Headers: 429 replies include
Retry-Afterandx-ratelimit-*headers.
Your usage tier goes up automatically as your total billed amount grows:
| Total billed so far | Usage tier |
|---|---|
| Over $20 / €20 | Tier 1 to Tier 2 |
| Over $100 / €100 | Tier 2 to Tier 3 |
| Over $500 / €500 | Tier 3 to Tier 4 |
| Over $2,000 / €2,000 | Tier 4 (contact support for more) |
Mistral does not publish the exact numbers for each tier, so read them in your Admin Panel. For a wider view of how tiers work across providers, see LLM API rate limits and tiers.
Prices and a Worked Cost Example
Prices below are the standard USD rates per 1 million tokens from Mistral’s pricing docs, checked on 3 December 2026.
| Model | Input | Cached input | Output |
|---|---|---|---|
| Mistral Large 4 | $0.70 | $0.07 | $2.10 |
| Mistral Small 4 | $0.15 | n/a | $0.60 |
| Ministral 3 14B | $0.20 | n/a | $0.20 |
| Ministral 3 8B | $0.15 | n/a | $0.15 |
| Ministral 3 3B | $0.10 | n/a | $0.10 |
| Mistral Embed | $0.10 | n/a | n/a |
| Mistral Moderation 2 | Free | ||
Batch processing cuts the price by 50%, and regional EU or US endpoints add 10%. OCR 4.1 is billed at $4 per 1,000 pages.
Worked example: a support chatbot
Say your bot handles 1,000 chats a day. Each chat sends 1,500 input tokens and gets 500 output tokens back.
- Daily tokens: 1.5M input and 0.5M output.
- On Mistral Small 4: 1.5 x $0.15 = $0.225, plus 0.5 x $0.60 = $0.30. That is $0.525 a day, or about $15.75 for 30 days.
- On Mistral Large 4: 1.5 x $0.70 = $1.05, plus 0.5 x $2.10 = $1.05. That is $2.10 a day, or about $63 for 30 days.
- With the Batch API: if the work can wait, both numbers drop by half, to about $7.88 and $31.50.
Cached input on Large 4 costs 90% less than fresh input. A long shared system prompt can therefore cut the bill further. Our guide on prompt caching explains the idea.
Troubleshooting: Common Errors and Fixes
These are the real messages from Mistral’s error glossary. In Python, catch them with from mistralai.client import errors and except errors.MistralError as e:, then read e.status_code and e.body.
| Status (code) | Message | Fix |
|---|---|---|
| 401 | Invalid API Key | Check that MISTRAL_API_KEY holds the full key in the same terminal, and that the key has not expired. |
| 402 (2314) | You need a subscription to access this API. | You are in Free mode. Enable pay-as-you-go with credits, or move to a plan with API usage. |
| 402 (2300) | Customer monthly spending limit reached. | An admin must raise the monthly cap, or wait for next month. |
| 400 (1500) | Invalid model: <name> | Fix the model ID. Retired IDs such as open-mistral-nemo fail here. List valid IDs with GET /v1/models. |
| 422 | Field required / Extra inputs are not permitted | Read loc and msg in the detail list and fix that field. |
| 429 (1300) | Rate limit exceeded | Wait for Retry-After and retry with backoff. A limit of 0 requests means Free mode. |
| 429 / 503 (3505, 3801) | Not enough capacity available for this request | Retry with exponential backoff, or switch models for a while. |
| 500 (1000) | Service unavailable. | Retry after a short delay and check status.mistral.ai. |
Code problems that are not HTTP errors
- ImportError on Mistral: SDK 3.x moved the class. Use
from mistralai.client import Mistral. parsedis None: the reply was cut off. Raisemax_tokensand checkfinish_reason.- Model ignores your tool: improve the tool description, or set
tool_choice="any"to force a call. - JSON mode returns odd keys: describe the exact keys in your prompt, or switch to
chat.parse().
Frequently Asked Questions
Is the Mistral API free?
Not anymore for most new users. The current docs say Free mode has no API usage, and calls fail with a 402 error until you add pay-as-you-go credits or join Pro, Education or Team.
Where do I get a Mistral API key?
Sign in at console.mistral.ai (Mistral Studio), open API Keys and click New key. Copy the key right away, because it is shown only once.
Is Le Chat still a thing?
Le Chat was renamed Vibe on 28 May 2026. Your account and history moved over, and the API is separate from the chatbot.
Which Mistral model should I use?
Use mistral-small-latest for most apps because it is cheap and supports tools, JSON and images. Switch to mistral-large-4-0 for hard reasoning, long documents or agent work.
Is the Mistral API compatible with the OpenAI SDK?
The request and response shapes are very similar, but Mistral’s official route is its own mistralai SDK. This guide uses that SDK so every parameter matches the docs.
Does Mistral train on my API data?
The old free Experiment plan said its API requests may be used for training. For paid use, check Mistral’s data training policy and your Admin Panel settings before sending private data.
How do I lower my Mistral API bill?
Use Small 4 or Ministral for simple jobs, cap max_tokens, and send non-urgent work through the Batch API for 50% off. Large 4 also bills cached input at $0.07 instead of $0.70.
Want to try other providers with the same pattern? See our DeepSeek API Python tutorial, or route many models through one key with OpenRouter.
Sources
- Mistral docs: Activate and generate an API key
- Mistral docs: API pricing
- Mistral docs: Models overview and deprecations
- Mistral docs: Mistral Large 4 model card
- Mistral docs: Function calling
- Mistral docs: Structured output
- Mistral docs: Usage and limits
- Mistral docs: Subscriptions
- Mistral docs: Error glossary
- Mistral Help: How API rate limits work
- Mistral AI: Le Chat is now Vibe (28 May 2026)
- Mistral AI: Plans and pricing
- PyPI: mistralai 3.11.0



