Define a Pydantic, Zod, or JSON schema and make the model return responses that follow that exact JSON structure.
Custom Structured Outputs allow you to ensure the model provides an answer in a very specific JSON format by supplying a clear JSON schema. This approach allows the model to consistently deliver responses with the correct typing and keywords.
Usage
Generate and Use custom Structured Outputs
Here is an example of how to achieve this using the Mistral AI client and Pydantic/Zod/JSON Schemas:
Define the Data Model
First, define the structure of the output using a Pydantic, Zod or a JSON Schema:
from pydantic import BaseModelclass Book(BaseModel): name: str authors: list[str]
import { z } from 'zod';const Book = z.object({ name: z.string(), authors: z.array(z.string()),});
In this example, the Book class defines the structure of the output, ensuring that the model's response adheres to the specified format.
There are two types of possible outputs that are easily accessible via our SDK.
Corresponds to the raw structured JSON output of the model.
# Accessed with `chat_response.choices[0].message.content`:print(chat_response.choices[0].message.content)# {# "authors": ["Harper Lee"],# "name": "To Kill a Mockingbird"# }
// Accessed with `chatResponse.choices[0].message.content`:console.log(chatResponse.choices[0].message.content);// {// "authors": ["Harper Lee"],// "name": "To Kill a Mockingbird"// }
Corresponds to the parsed json object initialized from the response_format parameter and the content field of the response.<br />
It corresponds to the same object as the defined pydantic/zod model.
# converted into a Pydantic object with `chat_response.choices[0].message.parsed`. In this case, it is a `Book` instance:print(chat_response.choices[0].message.parsed)# name='To Kill a Mockingbird' authors=['Harper Lee']
// converted into a TypeScript object with `chatResponse.choices[0].message.parsed`. In this case, it is a `Book` object:console.log(chatResponse.choices[0].message.parsed);// { name: 'To Kill a Mockingbird', authors: [ 'Harper Lee' ] }
To better guide the model, the following is being always prepended to the System Prompt when using this method:
Your output should be an instance of a JSON object following this schema: {{ json_schema }}
However, it is recommended to add more explanations and iterate on your system prompt to better clarify the expected schema and behavior.
FAQ
All currently available models except for codestral-mamba are supported.