How to get Mistral API key
Quick answer
To get a
Mistral API key, sign up at the official Mistral AI website and create an account. After logging in, generate your API key from the dashboard, then set it as an environment variable MISTRAL_API_KEY for use with the mistralai Python SDK or OpenAI-compatible clients.PREREQUISITES
Python 3.8+pip install mistralai or openai>=1.0Mistral account registration
Setup
Install the mistralai Python package to interact with Mistral models. Set your API key as an environment variable for secure access.
pip install mistralai Step by step
After registering at https://mistral.ai, log in and navigate to your dashboard to create and copy your API key. Then, set it in your environment and use it in Python as shown below.
import os
from mistralai import Mistral
# Ensure your MISTRAL_API_KEY is set in your environment
client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
response = client.chat.complete(
model="mistral-large-latest",
messages=[{"role": "user", "content": "Hello from Mistral!"}]
)
print(response.choices[0].message.content) output
Hello from Mistral! How can I assist you today?
Common variations
You can also use the OpenAI-compatible openai Python package with Mistral by setting the base_url to https://api.mistral.ai/v1 and passing your API key. This allows seamless integration if you prefer the OpenAI SDK interface.
from openai import OpenAI
import os
client = OpenAI(api_key=os.environ["MISTRAL_API_KEY"], base_url="https://api.mistral.ai/v1")
response = client.chat.completions.create(
model="mistral-large-latest",
messages=[{"role": "user", "content": "Hello from Mistral via OpenAI SDK!"}]
)
print(response.choices[0].message.content) output
Hello from Mistral via OpenAI SDK! How can I help you?
Troubleshooting
- If you get an authentication error, verify your
MISTRAL_API_KEYis correctly set in your environment variables. - Ensure your API key has not expired or been revoked in your Mistral dashboard.
- Check your internet connection and that you are using the correct
base_urlif using OpenAI-compatible SDK.
Key Takeaways
- Register at mistral.ai to create your API key for Mistral AI access.
- Set your API key securely as an environment variable before using the SDK.
- Use either the official mistralai SDK or OpenAI-compatible SDK with the correct base URL.
- Check your API key validity and environment setup if you encounter authentication issues.