mistralM

Docs

sideBar

Démarrage rapide

Créez un projet d’agent, exécutez son agent dans votre propre processus, discutez avec lui et donnez-lui un deuxième outil.

Commencez par créer un agent qui s’exécute dans votre propre processus Python : il n’appelle Mistral que pour le modèle, ce qui vous permet de l’essayer avant de le déployer. Vous pourrez ensuite le déployer avec Studio (en auto-hébergement ou géré par Mistral) : consultez Modes d’exécution. La commande agents init ci-dessous crée un projet avec un agent fonctionnel, et un outil est une fonction Python que vous y ajoutez. Si vous préférez ajouter le SDK à un projet existant, consultez Installation manuelle.

Avant de commencer

  • uvarrowUpRight : l’étape 1 exécute agents init avec le uvx de uv.
  • L’autorisation de créer une clé API Mistral dans votre espace de travail. agents init ouvre la page API keysarrowUpRight de Mistral Studio et écrit la clé dans le .env du projet sous le nom MISTRAL_API_KEY.

1. Créer le projet

Exécutez agents init pour créer un projet d’agent dans un nouveau dossier portant le nom de l’agent.

uvx --python 3.12 --from mistralai-agents agents init hello-agent
cd hello-agent

Sortie :

✓ Created hello-agent/
  pyproject.toml, .python-version, main.py, .gitignore, README.md, Dockerfile
✓ Locked the dependencies in uv.lock

La commande vous demande ensuite votre clé API : elle ouvre la page des clés API de Mistral Studio pour que vous puissiez en créer une, ou accepte une clé que vous collez, et l’écrit dans .env. .gitignore exclut .env de git. Enfin, elle propose de créer un dépôt git et de commiter le projet. Passez --yes pour ignorer les questions : la commande installe uv s’il est absent, commite immédiatement (sauf si le dossier se trouve dans un autre dépôt git) et laisse .env vide ; ajoutez-y donc votre clé avant l’étape 2.

pyproject.toml épingle mistralai-agents à la version qui a exécuté init, avec ses extras. En Python, vous l’importez sous le nom from mistralai import agents. L’agent se trouve dans main.py. Il dispose d’un outil, get_weather, qui renvoie un texte fixe :

from mistralai import agents

@agents.tool
async def get_weather(city: str) -> dict[str, str]:
    """Weather for a city."""
    return {"weather": f"sunny in {city}"}

agent = agents.Agent(
    model="mistral-large-4",
    name="hello-agent",
    instructions="You are a friendly agent. Tell us the weather in a city.",
    tools=[get_weather],
)

Le modèle lit le nom de l’outil, sa docstring et ses paramètres typés pour décider quand l’appeler. La ligne de commande agents recherche agent dans main.py. Ajoutez les dépendances propres à l’agent avec uv add.

2. Exécuter l’agent depuis Python

Remplacez main.py par cette version. Elle ajoute les lignes mises en évidence : import asyncio et une fonction main() qui envoie un message et affiche la réponse :

import asyncio

from mistralai import agents

@agents.tool
async def get_weather(city: str) -> dict[str, str]:
    """Weather for a city."""
    return {"weather": f"sunny in {city}"}

agent = agents.Agent(
    model="mistral-large-4",
    name="hello-agent",
    instructions="You are a friendly agent. Tell us the weather in a city.",
    tools=[get_weather],
)

async def main() -> None:
    result = await agent.run("What's the weather in Paris?")
    print(result.text)

if __name__ == "__main__":
    asyncio.run(main())

Exécutez-le. --env-file .env lit la clé que agents init a écrite :

uv run --env-file .env python main.py

Sortie :

The weather in **Paris** is currently **sunny** ☀️ — a beautiful day to be out and about!

agent.run démarre une session, envoie le message et renvoie le résultat du tour lorsque l’agent a répondu. Le modèle a appelé get_weather, puis a rédigé la réponse à partir de son résultat. Pour envoyer plusieurs messages dans la même conversation, consultez Sessions.

3. Discuter avec l’agent

agents chat charge le même main.py et ouvre un chat dans votre terminal. Pour lui fournir votre clé, exécutez-le avec uv run --env-file .env, ou exportez MISTRAL_API_KEY dans votre shell.

uv run --env-file .env agents chat

Sortie :

Talking to the agent in this process (session 4236c157-70c1-4211-a914-cc43e49adb1f). Ctrl+D or /exit to quit.
> Tell me about the weather in Paris
→ get_weather {"city": "Paris"}
← get_weather done
Here's the current weather in **Paris**: **Sunny!**

It's a bright, sunny day in the City of Light. Perfect weather for a stroll along the Seine or relaxing at a café terrace! Is there anything else you'd like to know?

La réponse est streamée au fur et à mesure que le modèle l’écrit, et chaque appel d’outil s’affiche pendant son exécution. Le chat conserve tous les messages : l’agent se souvient donc de la conversation. Ctrl+C interrompt un tour ; Ctrl+D ou /exit met fin au chat. Pour envoyer un seul message et quitter, passez -m.

$ uvx --python 3.12 --from mistralai-agents agents init hello-agent
✓ Created hello-agent/
pyproject.toml, .python-version, main.py, .gitignore, README.md, Dockerfile
✓ Locked the dependencies in uv.lock
$ cd hello-agent
$ uv run --env-file .env python main.py
The weather in Paris is currently sunny ☀️ — a beautiful day to be out and about!
$ uv run --env-file .env agents chat
Talking to the agent in this process (session 4236c157-70c1-4211-a914-cc43e49adb1f). Ctrl+D or /exit to quit.
> Tell me about the weather in Paris
■✓ get_weather {"city": "Paris"}
⎣ {"weather": "sunny in Paris"}
Here's the current weather in Paris: Sunny!
It's a bright, sunny day in the City of Light. Perfect weather for a stroll along the Seine or relaxing at a café terrace! Is there anything else you'd like to know?
> /exit
$ uv run --env-file .env agents chat -m "Will it rain in Paris in the next 3 days?"
■✓ get_forecast {"city": "Paris", "days": 3}
⎣ ["day 1: rain in Paris", "day 2: rain in Paris", "day 3: rain in Paris"]
Yes — according to the forecast, it will rain in Paris on all of the next 3 days:
• Day 1: Rain
• Day 2: Rain
• Day 3: Rain
Looks like a wet stretch ahead — pack an umbrella!
Step 1 of 4. agents init creates hello-agent: a project whose main.py holds an agent with one tool, get_weather. It then asks for your API key and writes it to .env.

4. Ajouter un outil

Un outil est une fonction Python, synchrone ou asynchrone, avec le décorateur @agents.tool. Ajoutez un outil de prévisions météo à main.py, au-dessus de l’agent, et ajoutez-le aux tools de l’agent. Conservez get_weather et main() :

@agents.tool
async def get_forecast(city: str, days: int) -> list[str]:
    """Weather forecast for a city, one line per day."""
    return [f"day {day}: rain in {city}" for day in range(1, days + 1)]

agent = agents.Agent(
    model="mistral-large-4",
    name="hello-agent",
    instructions="You are a friendly agent. Tell us the weather in a city.",
    tools=[get_weather, get_forecast],
)

Posez une question qui nécessite le nouvel outil :

uv run --env-file .env agents chat -m "Will it rain in Paris in the next 3 days?"

Sortie :

→ get_forecast {"city": "Paris", "days": 3}
← get_forecast done
Yes — according to the forecast, **it will rain in Paris on all of the next 3 days**:

- **Day 1:** Rain
- **Day 2:** Rain
- **Day 3:** Rain

Looks like a wet stretch ahead — pack an umbrella!

Le modèle a rempli les deux paramètres à partir de la question, days sous forme d’entier. Modifiez main.py et discutez à nouveau : c’est la boucle la plus rapide pendant que vous écrivez l’agent.

Installation manuelle

En plus des éléments de Avant de commencer, vous avez besoin de Python 3.12, 3.13 ou 3.14, dans sa version standard (pas la version free-threaded 3.14t). Le nom du package est mistralai-agents.

Créez un projet, ajoutez le SDK et définissez votre clé :

uv init --python 3.12 my_agent && cd my_agent
uv add "mistralai-agents==1.1.0"
export MISTRAL_API_KEY="<your-key>"

Pour vérifier que tout fonctionne, affichez la version du SDK :

uv run agents --version

Sortie :

mistralai-agents 1.1.0

La ligne de commande du SDK est agents ; exécutez uv run agents --help pour lister ses commandes.

Pour exécuter des commandes shell et modifier des fichiers, un agent a besoin d’un environnement : consultez Environnement. Un projet créé avec agents init installe déjà les extras de sandbox : bashkit, sessions-client et koyeb. Avec uv add, ajoutez l’extra nécessaire à votre sandbox, par exemple uv add "mistralai-agents[koyeb]==1.1.0" pour la sandbox Mistral. La création d’une sandbox Mistral nécessite aussi le rôle d’espace de travail cloud_user, affiché comme Mistral Cloud User dans la console.

Problèmes courants

Vous voyez

Action à effectuer

KeyError: 'Required environment variable is not set: MISTRAL_CLIENT_API_KEY'Définissez MISTRAL_API_KEY dans .env et passez --env-file .env à uv run, ou exportez MISTRAL_API_KEY. Une clé exportée dans votre shell est prioritaire sur .env

Étape suivante : déployer votre agent

Déployer votre agent exécute le même projet sur Mistral avec agents deploy et l’appelle par son nom depuis votre app.

L’agent peut aussi s’exécuter ailleurs, avec le même main.py :

Pour aller plus loin :

  • Parcourir un tour pas à pas : agent.run indique où le tour s’est arrêté : sa réponse, ou l’approbation qu’il attend. Lorsqu’un appel d’outil attend une approbation, Parcourir une session pas à pas y répond et laisse le tour continuer.
  • Suivre et orienter un tour : Créer une app de session affiche les événements du tour au fur et à mesure pendant que vous envoyez des messages à l’agent.
  • Voir ce qui s’est passé : agents chat affiche chaque appel d’outil et son résultat pendant l’exécution du tour. Une fois l’agent déployé, chaque tour est aussi une trace dans Mistral Studio, avec un span par appel de modèle et par appel d’outil.
  • Voir un projet finalisé : le bot météo Telegram ajoute une interface de chat devant le même type d’agent.
  • Donner davantage de moyens à l’agent : Outils, Environnement et Connecteurs et MCP.
  • Comprendre l’agent : Qu’est-ce qu’un agent ?.