结构化输出
更新时间:2025-08-23
介绍
JSON 是世界上应用程序交换数据最广泛使用的格式之一。结构化输出是一项功能,可确保模型始终生成符合您提供的JSON模式的响应,因此用户不必担心模型省略必需的键或产生无效的枚举值。
结构化输出的一些好处包括:
- 可靠的类型安全:无需验证或重试格式错误的响应
- 明确拒绝:基于安全的模型拒绝现在可以通过编程检测
- 更简单的提示:不需要用强烈的措辞来提示,就能实现一致的格式
如何支持
通过response_format字段来控制响应内容的生成。
字段 | 数据类型 | 描述 |
---|---|---|
type | string | 指定响应内容的格式,可选值: - text:以文本格式返回,默认为text; - json_object:以json格式返回,可能出现不满足效果情况; - json_schema:以json_scheam规定的格式返回 |
json_schema | object | - 当type为json_schema时,该参数必填;只有部分模型支持。 - 指定返回的JSON Schema描述; |
支持模型范围
- ERNIE-4.5
- DeepSeek-V3.1
- DeepSeek-V3.1-Think
- DeepSeek-V3
- Deepseek-R1
- Qwen3等开源模型
json_obejct
HTTP请求
请求
Bash
1curl --location 'https://qianfan.bj.baidubce.com/v2/chat/completions' \
2--header 'Content-Type: application/json' \
3--header 'Authorization: Bearer your-api-key' \
4--data '{
5 "messages": [
6 {
7 "role": "system",
8 "content": "\nThe user will provide some exam text. Please parse the \"question\" and \"answer\" and output them in JSON format. \n\nEXAMPLE INPUT: \nWhich is the highest mountain in the world? Mount Everest.\n\nEXAMPLE JSON OUTPUT:\n{\n \"question\": \"Which is the highest mountain in the world?\",\n \"answer\": \"Mount Everest\"\n}\n"
9 },
10 {
11 "role": "user",
12 "content": "Which is the longest river in the world? The Nile River."
13 }
14 ],
15 "model": "deepseek-v3",
16 "response_format": {
17 "type": "json_object"
18 },
19 "stream": false
20}'
返回
JSON
1{
2 "id": "as-edpps57f2v",
3 "object": "chat.completion",
4 "created": 1751006944,
5 "model": "deepseek-v3",
6 "choices": [
7 {
8 "index": 0,
9 "message": {
10 "role": "assistant",
11 "content": "{\n \"question\": \"Which is the longest river in the world?\",\n \"answer\": \"The Nile River\"\n}"
12 },
13 "finish_reason": "stop",
14 "flag": 0
15 }
16 ],
17 "usage": {
18 "prompt_tokens": 111,
19 "completion_tokens": 27,
20 "total_tokens": 138,
21 "prompt_tokens_details": {
22 "cached_tokens": 2
23 }
24 }
25}
OpenAI SDK兼容
请求
Python
1from openai import OpenAI
2
3client = OpenAI(
4 api_key="your-api-key",
5 base_url="https://qianfan.baidubce.com/v2"
6)
7
8system_prompt = """
9The user will provide some exam text. Please parse the "question" and "answer" and output them in JSON format.
10
11EXAMPLE INPUT:
12Which is the highest mountain in the world? Mount Everest.
13
14EXAMPLE JSON OUTPUT:
15{
16 "question": "Which is the highest mountain in the world?",
17 "answer": "Mount Everest"
18}
19"""
20
21user_prompt = "Which is the longest river in the world? The Nile River."
22
23messages = [{"role": "system", "content": system_prompt},
24 {"role": "user", "content": user_prompt}]
25
26response = client.chat.completions.create(
27 stream=True,
28 model="deepseek-v3",
29 messages=messages,
30 response_format={
31 'type': 'json_object'
32 }
33)
34
35for chunk in response:
36 print(chunk.choices[0].delta.content, end='')
返回
JSON
1{
2 "question": "Which is the longest river in the world?",
3 "answer": "The Nile River"
4}
json_schema
HTTP请求
请求
Bash
1curl --location 'https://qianfan.baidubce.com/v2/chat/completions' \
2--header 'Content-Type: application/json' \
3--header 'Authorization: Bearer your-api-key' \
4--data '{
5 "messages": [
6 {
7 "role": "system",
8 "content": "You are a helpful math tutor. Guide the user through the solution step by step."
9 },
10 {
11 "role": "user",
12 "content": "how can I solve 8x + 7 = -23"
13 }
14 ],
15 "model": "deepseek-v3",
16 "response_format": {
17 "type": "json_schema",
18 "json_schema": {
19 "schema": {
20 "$defs": {
21 "Step": {
22 "properties": {
23 "explanation": {
24 "title": "Explanation",
25 "type": "string"
26 },
27 "output": {
28 "title": "Output",
29 "type": "string"
30 }
31 },
32 "required": [
33 "explanation",
34 "output"
35 ],
36 "title": "Step",
37 "type": "object",
38 "additionalProperties": false
39 }
40 },
41 "properties": {
42 "steps": {
43 "items": {
44 "$ref": "#/$defs/Step"
45 },
46 "title": "Steps",
47 "type": "array"
48 },
49 "final_answer": {
50 "title": "Final Answer",
51 "type": "string"
52 }
53 },
54 "required": [
55 "steps",
56 "final_answer"
57 ],
58 "title": "MathReasoning",
59 "type": "object",
60 "additionalProperties": false
61 },
62 "name": "MathReasoning",
63 "strict": true
64 }
65 },
66 "stream": false
67}'
返回
JSON
1{
2 "id": "as-xa6w2285g9",
3 "object": "chat.completion",
4 "created": 1751005990,
5 "model": "deepseek-v3",
6 "choices": [
7 {
8 "index": 0,
9 "message": {
10 "role": "assistant",
11 "content": "{\n \"final_answer\": \"x = -15/4\",\n \"steps\": [\n {\n \"explanation\": \"To solve the equation 8x + 7 = -23, we first need to isolate the term with the variable x. We can do this by subtracting 7 from both sides of the equation.\",\n \"output\": \"8x + 7 - 7 = -23 - 7\"\n },\n {\n \"explanation\": \"After subtracting 7 from both sides, the equation simplifies to 8x = -30.\",\n \"output\": \"8x = -30\"\n },\n {\n \"explanation\": \"Next, we solve for x by dividing both sides of the equation by 8 to isolate x.\",\n \"output\": \"x = -30 / 8\"\n },\n {\n \"explanation\": \"The fraction -30/8 can be simplified by dividing both the numerator and the denominator by 2.\",\n \"output\": \"x = -15/4\"\n }\n ]\n}"
12 },
13 "finish_reason": "stop",
14 "flag": 0
15 }
16 ],
17 "usage": {
18 "prompt_tokens": 302,
19 "completion_tokens": 220,
20 "total_tokens": 522,
21 "prompt_tokens_details": {
22 "cached_tokens": 5
23 }
24 }
25}
OpenAI SDK兼容
请求
Python
1from openai import OpenAI
2from pydantic import BaseModel
3
4client = OpenAI(
5 api_key="your-api-key",
6 base_url="https://qianfan.baidubce.com/v2"
7)
8
9class Step(BaseModel):
10 explanation: str
11 output: str
12
13class MathReasoning(BaseModel):
14 steps: list[Step]
15 final_answer: str
16
17completion = client.chat.completions.parse(
18 model="deepseek-v3",
19 messages=[
20 {"role": "system", "content": "You are a helpful math tutor. Guide the user through the solution step by step."},
21 {"role": "user", "content": "how can I solve 8x + 7 = -23"}
22 ],
23 response_format=MathReasoning,
24)
25
26resp = completion.choices[0].message.parsed
27# 打印 JSON 格式结果
28print(resp.model_dump_json(indent=2))
输出
JSON
1{
2 "steps": [
3 {
4 "explanation": "To solve the equation 8x + 7 = -23, we first need to isolate the term with the variable x. We can do this by subtracting 7 from both sides of the equation.",
5 "output": "8x + 7 - 7 = -23 - 7"
6 },
7 {
8 "explanation": "After subtracting 7 from both sides, the equation simplifies to 8x = -30.",
9 "output": "8x = -30"
10 },
11 {
12 "explanation": "Now, to solve for x, we divide both sides of the equation by 8.",
13 "output": "8x / 8 = -30 / 8"
14 },
15 {
16 "explanation": "After dividing both sides by 8, we find that x = -3.75.",
17 "output": "x = -3.75"
18 }
19 ],
20 "final_answer": "x = -3.75"
21}