Use the Mistral AI Python SDK to build chat completions, embeddings, file uploads, agents, batch jobs, and fine-tuning workflows with Mistral AI models.
Master the Mistral AI Python Client SDK to build powerful AI applications with chat completions, embeddings, file management, agents, batch processing, and fine-tuning capabilities.
You'll learn to integrate Mistral AI's API into Python applications using their official SDK (v1.11.1+), including setup, authentication, synchronous and asynchronous patterns, streaming responses, error handling, and advanced features like agents and batch jobs.
Install the `mistralai` package using your preferred Python package manager:
**Using uv (recommended for speed):**
```bash
uv add mistralai
```
**Using pip:**
```bash
pip install mistralai
```
**Using poetry:**
```bash
poetry add mistralai
```
**For agents functionality, install with extras:**
```bash
pip install "mistralai[agents]"
```
Note: Agents require Python 3.10+
Before using the SDK, obtain and configure your Mistral API key:
1. Get your API key from https://console.mistral.ai
2. Set it as an environment variable:
```bash
echo 'export MISTRAL_API_KEY=[your_key_here]' >> ~/.zshenv
source ~/.zshenv
echo 'export MISTRAL_API_KEY=[your_key_here]' >> ~/.bashrc
source ~/.bashrc
```
Use the SDK to generate chat completions:
```python
from mistralai import Mistral
import os
with Mistral(api_key=os.getenv("MISTRAL_API_KEY", "")) as mistral:
res = mistral.chat.complete(
model="mistral-large-latest",
messages=[
{
"content": "Who is the best French painter? Answer in one short sentence.",
"role": "user",
},
],
stream=False,
response_format={"type": "text"}
)
print(res)
```
**Key parameters:**
For async applications, use the async methods:
```python
import asyncio
from mistralai import Mistral
import os
async def main():
async with Mistral(api_key=os.getenv("MISTRAL_API_KEY", "")) as mistral:
res = await mistral.chat.complete_async(
model="mistral-large-latest",
messages=[
{
"content": "Who is the best French painter? Answer in one short sentence.",
"role": "user",
},
],
stream=False,
response_format={"type": "text"}
)
print(res)
asyncio.run(main())
```
For real-time streaming responses:
```python
with Mistral(api_key=os.getenv("MISTRAL_API_KEY", "")) as mistral:
stream = mistral.chat.stream(
model="mistral-large-latest",
messages=[{"role": "user", "content": "Tell me a story"}]
)
for chunk in stream:
if chunk.data.choices[0].delta.content:
print(chunk.data.choices[0].delta.content, end="")
```
Generate text embeddings for semantic search and similarity:
```python
from mistralai import Mistral
import os
with Mistral(api_key=os.getenv("MISTRAL_API_KEY", "")) as mistral:
res = mistral.embeddings.create(
model="mistral-embed",
inputs=[
"Embed this sentence.",
"As well as this one.",
]
)
print(res)
```
Upload files to Mistral AI (useful for fine-tuning or agents):
```python
from mistralai import Mistral
import os
with Mistral(api_key=os.getenv("MISTRAL_API_KEY", "")) as mistral:
res = mistral.files.upload(file={
"file_name": "example.file",
"content": open("example.file", "rb"),
})
print(res)
```
**File operations available:**
Create and use agents for conversational AI (requires Python 3.10+ and `mistralai[agents]`):
```python
from mistralai import Mistral
import os
with Mistral(api_key=os.getenv("MISTRAL_API_KEY", "")) as mistral:
# Create agent completion
res = mistral.agents.complete(
messages=[
{
"content": "Who is the best French painter? Answer in one short sentence.",
"role": "user",
},
],
agent_id="<your_agent_id>",
stream=False,
response_format={"type": "text"}
)
print(res)
```
**Agent management:**
Process multiple requests efficiently with batch jobs:
```python
from mistralai import Mistral
import os
with Mistral(api_key=os.getenv("MISTRAL_API_KEY", "")) as mistral:
# Create batch job
job = mistral.batch.jobs.create(
input_files=["file-abc123"],
model="mistral-large-latest",
endpoint="/v1/chat/completions"
)
# Check job status
status = mistral.batch.jobs.get(job_id=job.id)
print(status)
# List all jobs
jobs = mistral.batch.jobs.list()
# Cancel a job
mistral.batch.jobs.cancel(job_id=job.id)
```
Implement proper error handling for production applications:
```python
from mistralai import Mistral, SDKError
import os
try:
with Mistral(api_key=os.getenv("MISTRAL_API_KEY", "")) as mistral:
res = mistral.chat.complete(
model="mistral-large-latest",
messages=[{"role": "user", "content": "Hello"}]
)
except SDKError as e:
print(f"SDK Error: {e}")
except Exception as e:
print(f"Unexpected error: {e}")
```
Customize retry behavior for failed requests:
```python
from mistralai import Mistral
from mistralai.utils import BackoffStrategy, RetryConfig
mistral = Mistral(
api_key=os.getenv("MISTRAL_API_KEY", ""),
retry_config=RetryConfig(
strategy="backoff",
backoff=BackoffStrategy(
initial_interval=500,
max_interval=60000,
exponent=1.5,
max_elapsed_time=3600000
),
retry_connection_errors=True
)
)
```
**For Azure AI:**
```python
from mistralai_azure import MistralAzure
client = MistralAzure(
azure_api_key=os.getenv("AZURE_API_KEY", ""),
azure_endpoint=os.getenv("AZURE_ENDPOINT", "")
)
res = await client.chat.complete_async(
max_tokens=100,
temperature=0.5,
messages=[{"content": "Hello!", "role": "user"}]
)
```
**For Google Cloud (requires `mistralai[gcp]`):**
```python
from mistralai_gcp import MistralGoogleCloud
client = MistralGoogleCloud()
res = await client.chat.complete_async(
model="mistral-small-2402",
messages=[{"content": "Hello!", "role": "user"}]
)
```
**Streaming with async:**
```python
async with Mistral(api_key=os.getenv("MISTRAL_API_KEY")) as mistral:
async for chunk in mistral.chat.stream_async(
model="mistral-large-latest",
messages=[{"role": "user", "content": "Write a poem"}]
):
print(chunk.data.choices[0].delta.content, end="")
```
**Function calling (tool use):**
```python
res = mistral.chat.complete(
model="mistral-large-latest",
messages=[{"role": "user", "content": "What's the weather in Paris?"}],
tools=[{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string"}
}
}
}
}]
)
```
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/mistral-ai-python-sdk/raw