Quickstart: get structured output
In this quickstart, you describe the fields you want with a Pydantic class, and the model fills them from a customer message. You get a validated Python object instead of free text. It takes about 5 minutes. For JSON mode and JSON schemas, see Structured outputs.
Before you begin
Before you begin
- A Mistral API key. To create one, see Create your first API key.
- Python 3.10 or later and uv.
Set up your environment
Set up your environment
Create a project, install the Mistral SDK, and export your API key:
uv init structured-output --python 3.12 && cd structured-output
uv add mistralai
export MISTRAL_API_KEY="your-api-key"1. Write the script
1. Write the script
Create structured.py. chat.parse sends the schema of Ticket with the request, then parses and validates the answer:
import os
from mistralai.client import Mistral
from pydantic import BaseModel
class Ticket(BaseModel):
title: str
priority: int
customer: str
client = Mistral(api_key=os.environ["MISTRAL_API_KEY"])
response = client.chat.parse(
model="mistral-small-latest",
messages=[
{
"role": "user",
"content": "Ada from Acme writes: our checkout page is down, please fix it urgently. "
"Extract a support ticket with a priority from 1 (urgent) to 3 (low).",
}
],
response_format=Ticket,
)
ticket = response.choices[0].message.parsed
print(ticket)
print(f"Priority: {ticket.priority}")2. Run it
2. Run it
uv run structured.pyYou should see
You should see
A Ticket object with the three fields filled in, then one field read as a Python integer:
title='Checkout page is down' priority=1 customer='Acme'
Priority: 1The values can vary slightly between runs, but they always match the types of Ticket. If the answer doesn't validate, parse raises a validation error instead of returning a wrong object.
Going further