Structured outputs는 모델이 생성하는 응답을 사용자가 제공한 JSON 스키마에 맞게 제한하는 기능이에요. 원하는 형태를 프롬프트로 설명하고 모델이 따라주기를 기대하는 대신, response_format에 스키마를 전달하면 그에 맞는 유효한 JSON으로 응답이 돌아와요. 필드 이름과 타입이 동일하고, 스키마가 허용한 값만 사용돼요. 응답은 안전하게 파싱할 수 있지만, 스키마를 따른다는 사실만으로 값 자체를 신뢰할 수 있는 것은 아니에요. UI, 저장소, 외부 작업에 사용하기 전에 도메인 규칙 검증, 출력 대상에 맞는 이스케이프, 권한 확인을 적용해주세요.
Chat Completions 원본 응답에서 생성된 JSON은 이미 파싱된 객체가 아니라 문자열로 choices[0].message.content에 담겨 도착해요. OpenAI 호환 API를 그대로 사용하는 경우 모두 이 문자열을 받게 되며, 위 예제 중 Python OpenAI, JavaScript, cURL, LlamaIndex는 이 문자열을 직접 파싱해요. Python에서는 json.loads, JavaScript에서는 JSON.parse를 사용해요. LangChain은 예외로, with_structured_output이 문자열을 대신 파싱해서 객체로 돌려줘요.
파싱하기 전에 choices[0].finish_reason을 확인해주세요. 값이 stop이면 모델이 객체를 끝까지 생성했고 내용이 완전한 JSON이라는 뜻이에요. 값이 length이면 생성이 토큰 한도에 걸려 객체 중간에서 잘렸다는 뜻이라 파싱에 실패해요. 이 경우에는 잘린 텍스트를 파싱하지 말고 max_tokens를 늘리거나 재시도해주세요.
{ "id": "b84cc249-fc79-4e84-bedc-eac25f88a90a", "object": "chat.completion", "created": 1785957109, "model": "solar-pro4-260806", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "{\n \"category\": \"billing\",\n \"urgent\": true,\n \"reply\": \"Dear Customer,\\n\\nThank you for reaching out. I am truly sorry to hear about the duplicate charge on your subscription. I understand how concerning this is.\\n\\nThis ticket is marked as high priority. To help us investigate and issue a refund if necessary, please reply with the following details:\\n- Date and amount of both charges\\n- Transaction IDs (if available)\\n\\nWe aim to resolve this within 24-48 hours. Thank you for your patience.\\n\\nBest regards,\\nSupport Team\"\n}", "reasoning": "Thinking Process:\n\n1. **Analyze the Request:**\n * Task: Classify an urgent support ticket and draft a short reply.\n * Input: \"I was charged twice for my subscription.\"\n * Constraint: I am Solar Pro4, a large language model trained by Upstage AI. My knowledge cutoff is 2026-02.\n * Goal: Provide a classification and a draft response.\n\n2. **Classify the Ticket:**\n * Content: User claims duplicate billing/charging.\n * Urgency: High (financial issue).\n * Category: Billing/Subscription > Duplicate Charge.\n * Priority: High/Urgent.\n\n3. **Draft the Reply:**\n * Tone: Empathetic, professional, action-oriented.\n * Content: Acknowledge the issue, apologize, request necessary details (transaction IDs, dates), explain next steps (investigation/refund process), provide timeline.\n * Length: Short (as requested).\n\n4. **Check Constraints & Identity:**\n * Identity: Solar Pro4 by Upstage AI.\n * Knowledge Cutoff: 2026-02 (not directly relevant for this generic task, but good to keep in mind).\n * Safety: No sensitive info requested unnecessarily.\n\n5. **Drafting the Response:**\n\n * *Classification:* Billing Issue - Duplicate Charge (High Priority).\n * *Reply:*\n * Subject: Urgent: Regarding Your Double Charge\n * Body: Dear [Customer Name], Thank you for reaching out. I'm sorry to hear about the duplicate charge. This is a priority for us. Please provide the transaction IDs/dates so we can investigate. We aim to resolve this within 24-48 hours. Best, Support Team.\n\n6. **Refining for Quality:**\n * Make it sound natural and helpful.\n * Ensure the classification is clear.\n\n7. **Final Output Generation:** (Matches the thought process above)." }, "logprobs": null, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 71, "completion_tokens": 553, "total_tokens": 624, "prompt_tokens_details": { "cached_tokens": 0, "audio_tokens": 0 }, "completion_tokens_details": { "reasoning_tokens": 423, "audio_tokens": 0, "accepted_prediction_tokens": 0, "rejected_prediction_tokens": 0 } }, "system_fingerprint": null}
stream을 true로 설정하면 JSON이 생성되는 대로 받아볼 수 있어요. 응답은 부분 객체가 아니라 JSON 텍스트의 조각으로 choices[0].delta.content에 담겨 도착해요. 각 조각은 문자열의 일부이므로 개별 델타 하나만으로는 대개 유효한 JSON이 아니에요. 모든 델타를 하나의 문자열로 누적하고, 스트림이 끝난 뒤에 파싱해주세요.
SDK 대신 SSE 원본 스트림을 직접 읽는다면, 스트림은 data: [DONE] 줄로 끝나요.