输出JSON格式的DeepSeek在线调用示例

输出JSON格式的DeepSeek在线调用示例

 

在许多应用场景中,用户需要模型严格按照JSON 格式输出数据,以确保输出的结构化和标准化,便于后续逻辑处理和解析。为了满足这一需求,DeepSeek 提供了强大的JSON Output  功能,确保模型输出的字符串始终是合法的JSON 格式。

我们给出一个DeepSeek 官方提供的JSON 结构化数据处理代码,如图2-26 所示。

2-26  JSON 结构化数据处理代码

import json
from openai import OpenAI
 
client = OpenAI(
    api_key="",
    base_url="https://api.deepseek.com",
)
 
system_prompt = """
The user will provide some exam text. Please parse the "question" and "answer" and output them in JSON format. 
EXAMPLE INPUT: 
Which is the highest mountain in the world? Mount Everest.
EXAMPLE JSON OUTPUT:
{
    "question": "Which is the highest mountain in the world?",
    "answer": "Mount Everest"
}
"""
 
user_prompt = "Which is the longest river in the world? The Nile River."
 
messages = [{"role": "system", "content": system_prompt},
            {"role": "user", "content": user_prompt}]
 
response = client.chat.completions.create(
    model="deepseek-chat",
    messages=messages,
    response_format={
        'type': 'json_object'
    }
)
 
print(json.loads(response.choices[0].message.content))

这个样例代码运行结果如下:

{
    "question": "Which is the longest river in the world?",
    "answer": "The Nile River"
}

以下是一个完整的、根据图2-26 所示的样例代码改写的Python 示例代码,展示了如何使用DeepSeek JSON Output 功能完成一个自定义的JSON 格式信息:

import json
from openai import OpenAI
 
client = OpenAI(
    api_key="sk-c646e1c201d74777b54f45c60973f4f3",
    base_url="https://api.deepseek.com",
)
 
system_prompt = """
用户将提供一些考试文本。请解析“问题”和“答案”,并将它们以 JSON 格式输出。
示例输入:
世界上最高的山是哪座?珠穆朗玛峰。
 
示例 JSON 输出:
{
    "question": "世界上最高的山是哪座?",
    "answer": "珠穆朗玛峰"
}
"""
 
user_prompt = "世界上最长的河流是哪条?尼罗河。"
 
messages = [{"role": "system", "content": system_prompt},
            {"role": "user", "content": user_prompt}]
 
response = client.chat.completions.create(
    model="deepseek-chat",
    messages=messages,
    response_format={
        'type': 'json_object'
    }
)
 
print(json.loads(response.choices[0].message.content))

注意:代码中的api_key要改成你自己的授权码。运行代码,输出结果如下所示:

{'question': '世界上最长的河流是哪条?', 'answer': '尼罗河'}





请使用浏览器的分享功能分享到微信等