自定义结构化输出
自定义结构化输出允许您通过提供清晰的 JSON Schema 来确保模型以非常特定的 JSON 格式提供答案。这种方法使模型能够始终如一地提供具有正确类型和关键字的响应。
- python
- typescript
- curl
这是一个使用 Mistral AI 客户端和 Pydantic 实现此功能的示例
定义数据模型
首先,使用 Pydantic 模型定义输出的结构
from pydantic import BaseModel
class Book(BaseModel):
name: str
authors: list[str]
开始补全
接下来,使用 Mistral AI python 客户端发送请求,并通过将 response_format
设置为相应的 Pydantic 模型来确保响应遵循定义的结构
import os
from mistralai import Mistral
api_key = os.environ["MISTRAL_API_KEY"]
model = "ministral-8b-latest"
client = Mistral(api_key=api_key)
chat_response = client.chat.parse(
model=model,
messages=[
{
"role": "system",
"content": "Extract the books information."
},
{
"role": "user",
"content": "I recently read 'To Kill a Mockingbird' by Harper Lee."
},
],
response_format=Book,
max_tokens=256,
temperature=0
)
在此示例中,Book
类定义了输出的结构,确保模型的响应遵循指定的格式。
可通过我们的 SDK 轻松访问两种可能的输出类型
- 原始 JSON 输出,通过
chat_response.choices[0].message.content
访问
{
"authors": ["Harper Lee"],
"name": "To Kill a Mockingbird"
}
- 解析后的输出,使用
chat_response.choices[0].message.parsed
转换为 Pydantic 对象。在这种情况下,它是一个Book
实例
name='To Kill a Mockingbird' authors=['Harper Lee']
这是一个使用 Mistral AI 客户端和 Zod 实现此功能的示例
定义数据模型
首先,使用 Zod 定义输出的结构
import { z } from "zod";
const Book = z.object({
name: z.string(),
authors: z.array(z.string()),
});
开始补全
接下来,使用 Mistral AI TypeScript 客户端发送请求,并通过将 responseFormat
设置为相应的 Zod Schema 来确保响应遵循定义的结构
import { Mistral } from "@mistralai/mistralai";
const apiKey = process.env.MISTRAL_API_KEY;
const client = new Mistral({apiKey: apiKey});
const chatResponse = await client.chat.parse({
model: "ministral-8b-latest",
messages: [
{
role: "system",
content: "Extract the books information.",
},
{
role: "user",
content: "I recently read 'To Kill a Mockingbird' by Harper Lee.",
},
],
responseFormat: Book,
maxTokens: 256,
temperature: 0,
});
在此示例中,Book
Schema 定义了输出的结构,确保模型的响应遵循指定的格式。
可通过我们的 SDK 轻松访问两种可能的输出类型
- 原始 JSON 输出,通过
chatResponse.choices[0].message.content
访问
{
"authors": ["Harper Lee"],
"name": "To Kill a Mockingbird"
}
- 解析后的输出,使用
chatResponse.choices[0].message.parsed
转换为 TypeScript 对象。在这种情况下,它是一个Book
对象
{ name: 'To Kill a Mockingbird', authors: [ 'Harper Lee' ] }
请求的结构旨在确保响应遵循指定的自定义 JSON Schema。schema
定义了一个包含 name 和 authors 属性的 Book 对象的结构。
curl --location "https://api.mistral.ai/v1/chat/completions" \
--header 'Content-Type: application/json' \
--header 'Accept: application/json' \
--header "Authorization: Bearer $MISTRAL_API_KEY" \
--data '{
"model": "ministral-8b-latest",
"messages": [
{
"role": "system",
"content": "Extract the books information."
},
{
"role": "user",
"content": "I recently read To Kill a Mockingbird by Harper Lee."
}
],
"response_format": {
"type": "json_schema",
"json_schema": {
"schema": {
"properties": {
"name": {
"title": "Name",
"type": "string"
},
"authors": {
"items": {
"type": "string"
},
"title": "Authors",
"type": "array"
}
},
"required": ["name", "authors"],
"title": "Book",
"type": "object",
"additionalProperties": false
},
"name": "book",
"strict": true
}
},
"max_tokens": 256,
"temperature": 0
}'
注意
为了更好地引导模型,使用此方法时,以下内容会默认始终前置添加到系统提示中
Your output should be an instance of a JSON object following this schema: {{ json_schema }}
但是,建议添加更多解释并迭代您的系统提示,以便更好地阐明预期的 Schema 和行为。
常见问题
问:哪些模型支持自定义结构化输出?
答:目前所有可用模型均支持,但 codestral-mamba
除外。