많은 시나리오에서 사용자는 체계적인 출력을 달성하기 위해 엄격한 JSON 형식으로 출력하려면 모델을 필요로하여 후속 구문 분석을 용이하게합니다.DeepSeek은 JSON 출력을 제공하여 모델 출력이 유효한 JSON 문자열을 보장합니다.알아채다#
JSON 출력을 가능하게하려면 사용자는 다음을해야합니다.1.
response_format 매개 변수를 {'type': 'json_object'} 로 설정하십시오.
2.
시스템 또는 사용자 프롬프트에 "JSON"이라는 단어를 포함시키고 원하는 JSON 형식의 예를 제공하여 유효한 JSON을 출력 할 때 모델을 안내하십시오.
3.
JSON 문자열이 중간에 잘리지 않도록 max_tokens 매개 변수를 합리적으로 설정하십시오.
4.
JSON 출력 기능을 사용하는 경우 API는 때때로 빈 컨텐츠를 반환 할 수 있습니다. 우리는이 문제를 최적화하기 위해 적극적으로 노력하고 있습니다. 그러한 문제를 완화하기 위해 프롬프트를 수정해 볼 수 있습니다.**
샘플 코드#
JSON 출력 사용을 보여주는 완전한 파이썬 코드는 다음과 같습니다.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:54:49