Mistral AI Python Client
The `mistralai` library is the official Python Client SDK for interacting with the Mistral AI API, providing programmatic access to Mistral's large language models and other AI services. It is currently at version 2.3.0 and actively maintained with regular updates and feature enhancements.
Warnings
- breaking The import path for the `Mistral` client class changed significantly from v1.x to v2.x. Old code importing `from mistralai import Mistral` will fail.
- breaking The structure of response objects, specifically `response.choices[]`, changed in v2.x for methods like `mistral.chat.complete()`, `mistral.fim.complete()`, and `mistral.agents.complete()`.
- gotcha API Key (`MISTRAL_API_KEY`) is crucial for authentication. Not setting it as an environment variable or passing it directly to the client will lead to authentication errors.
- gotcha Incorrect data serialization when sending requests to the API can lead to 'Data Serialization Error'.
- gotcha Common API errors include 401 (Unauthorized), 413 (Payload Too Large/Context Window Overflow), and 429 (Rate Limit Exceeded).
- deprecated Several older models, such as `open-mistral-7b`, `mistral-tiny`, `mistral-medium-2312`, and certain dated model aliases, have been deprecated.
Install
-
pip install mistralai
Imports
- Mistral
from mistralai.client import Mistral
Quickstart
import os
from mistralai.client import Mistral
# Ensure MISTRAL_API_KEY environment variable is set
api_key = os.environ.get('MISTRAL_API_KEY', '')
if not api_key:
print("Error: MISTRAL_API_KEY environment variable not set.")
print("Please set it using: export MISTRAL_API_KEY='your_api_key_here'")
else:
try:
client = Mistral(api_key=api_key)
chat_response = client.chat.complete(
model="mistral-small-latest",
messages=[
{"role": "user", "content": "What is the capital of France?"}
]
)
print(chat_response.choices[0].message.content)
except Exception as e:
print(f"An error occurred: {e}")