JSON 模式是大模型 API 实现结构化输出的关键功能。当用户在调用大模型 API 时,返回的结果以 JSON 格式呈现,有利于阅读和理解。智算平台目前支持 JSON 模式输出功能。

支持的模型

目前平台上的 DeepSeek-V3 模型支持。

注意事项

用户需提前在 API 密钥管理中创建和获取 API KEY 用于替换示例代码中的 api_key 参数。

使用方法

  • response_format 参数设置为 {'type': 'json_object'}

  • 用户传入的 systemuser prompt 中必须含有 json 字样,并给出希望模型输出的 JSON 格式的样例。

  • 合理设置 max_tokens 参数,防止 JSON 字符串被中断。

代码示例

示例一

import json
from openai import OpenAI

client = OpenAI(
    api_key="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    base_url="https://openapi.coreshub.cn/v1"
)


user_prompt = """Which is the longest river in the world? The Nile River.
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"
}
Don't output begin "```json" and end "```"
"""

messages = [{"role": "user", "content": user_prompt}]

response = client.chat.completions.create(
    model="DeepSeek-V3",
    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'}

示例二

import json
from openai import OpenAI

client = OpenAI(
    api_key="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    base_url="https://openapi.coreshub.cn/v1"
)


response = client.chat.completions.create(
    model="DeepSeek-V3",
    messages=[
            {"role": "system", "content": "You are a helpful assistant designed to output JSON."},
            {"role": "user", "content": """? 2020 年世界奥运会乒乓球男子和女子单打冠军分别是谁?
             Please respond in the format {\"男子冠军\": ..., \"女子冠军\": ...}
             Don't output begin "```json" and end "```" """}
        ],
    response_format={
        'type': 'json_object'
    }
)

print(json.loads(response.choices[0].message.content))

代码运行回显示例:

{'男子冠军': '马龙', '女子冠军': '陈梦'}