Deepseek JSON Output

2025-02-05 11:08 更新

在很多場景下,用戶需要讓模型嚴(yán)格按照 JSON 格式來輸出,以實(shí)現(xiàn)輸出的結(jié)構(gòu)化,便于后續(xù)邏輯進(jìn)行解析。

DeepSeek 提供了 JSON Output 功能,來確保模型輸出合法的 JSON 字符串。

注意事項(xiàng)?

  1. 設(shè)置 response_format 參數(shù)為 {'type': 'json_object'}。
  2. 用戶傳入的 system 或 user prompt 中必須含有 json 字樣,并給出希望模型輸出的 JSON 格式的樣例,以指導(dǎo)模型來輸出合法 JSON。
  3. 需要合理設(shè)置 max_tokens 參數(shù),防止 JSON 字符串被中途截?cái)唷?/li>
  4. 在使用 JSON Output 功能時(shí),API 有概率會(huì)返回空的 content。我們正在積極優(yōu)化該問題,您可以嘗試修改 prompt 以緩解此類問題。

樣例代碼?

這里展示了使用 JSON Output 功能的完整 Python 代碼:

import json
from openai import OpenAI

client = OpenAI(
api_key="<your 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))

模型將會(huì)輸出:

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


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號