多くのシナリオでは、ユーザーは構造化された出力を達成するために厳密なJSON形式で出力するモデルを必要とし、その後の解析を促進します。DeepSeekはJSON出力を提供して、モデルが有効なJSON文字列を出力するようにします。知らせ#
JSON出力を有効にするには、ユーザーは次のようにする必要があります。1.
response_format
パラメーターを{'type': 'json_object'}
に設定します。
2.
システムまたはユーザープロンプトに「JSON」という言葉を含め、有効なJSON出力にモデルをガイドするために、目的のJSON形式の例を提供します。
3.
JSON文字列が途中で切り捨てられないように、 max_tokens
パラメーターを合理的に設定します。
4.
JSON出力機能を使用する場合、APIは空のコンテンツを返すことがあります。私たちはこの問題の最適化に積極的に取り組んでいます。このような問題を軽減するためにプロンプトを変更することを試みることができます。**
サンプルコード#
JSON出力の使用を示す完全な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))
"question": "Which is the longest river in the world?",
"answer": "The Nile River
Modified at 2025-02-06 09:09:52