JSON 출력 (JSON Output)
JSON 출력 (JSON Output)
모델의 답을 바로 코드에서 파싱해서 쓰고 싶다면, JSON 형식으로 구조화된 출력이 필요해요. DeepSeek는 모델이 유효한 JSON 문자열을 내보내도록 보장하는 JSON Output 기능을 제공해요. 응답을 정형 데이터로 받아야 하는 작업에서 아주 유용해요.
JSON 출력을 켜려면 네 가지를 지켜야 해요.
response_format파라미터를{'type': 'json_object'}로 설정해요.- 시스템 또는 사용자 프롬프트에 "json"이라는 단어를 포함하고, 원하는 JSON 형식의 예시를 함께 제시해서 모델이 유효한 JSON을 출력하도록 유도해요.
- JSON 문자열이 중간에 잘리지 않도록
max_tokens를 적절히 설정해요. - JSON 출력을 쓸 때 API가 가끔 빈 내용을 반환할 수 있어요. 이 문제는 개선 중이고, 프롬프트를 수정해 완화해 볼 수 있어요.
전체 Python 코드 예시를 볼게요. 예시에서는 시험 문항 텍스트에서 "질문"과 "답"을 추출해 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-flash",
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"
}
코드 마지막에서 json.loads(...)로 파싱하니, 받은 내용이 진짜 유효한 JSON인 게 보장되어야 안전하게 파싱돼요.
더 알아보기
response_format파라미터의 전체 설명은 «채팅 완성 API» 문서를 봐요.- 모델이 함수 호출 형태로 구조화 출력을 하게 하려면 «도구 호출 (Tool Calls)» 문서를 봐요.