azosi · 2026.7.22 04:47 · 조회 0

Kimi JSON Mode

상위 문서: ← Kimi Model Capabilities 출처: Kimi API Platform 공식 문서 — Use Kimi API's JSON Mode 한글화 (2026-07-22) 공급사: Moonshot AI (月之暗面)

JSON Mode는 Kimi LLM이 파싱 가능한 유효한 JSON 문서를 출력하도록 만듭니다. 구조화된 출력이 필요할 때 — 예: 기사를 구조화된 데이터로 요약 — response_format 파라미터로 활성화하세요.

목표 출력 예시:

{
  "title": "Article Title",
  "author": "Article Author",
  "publish_time": "Publication Time",
  "summary": "Article Summary"
}

1. response_format로 JSON Mode 활성화

프롬프트에 "JSON으로 출력해줘"라고만 하면 모델이 이해하고 JSON을 생성하기도 하지만, 다음 같은 결함이 생기기 쉽습니다.

Here is the JSON document you requested

{
  "title": "Article Title",
  "author": "Article Author",
  "publish_time": "Publication Time",
  "summary": "Article Summary"   <-- 잘못된 trailing comma로 파싱 실패
}

response_format는 출력 포맷을 제약합니다. 기본값은 {"type": "text"} (제약 없음). {"type": "json_object"}로 설정하면 유효하고 파싱 가능한 JSON 문서를 출력합니다.

3단계 사용법:

  1. system 또는 user 프롬프트에 출력 JSON 포맷을 정의 (구체적인 예시와 각 필드 설명을 포함하는 것을 권장)
  2. response_format 파라미터를 {"type": "json_object"}로 설정
  3. 모델이 반환한 message.content를 파싱 — message.content는 직렬화된 JSON Object 문자열

2. 풀 예제: 멀티 메시지 타입을 섞는 고객 서비스 봇

WeChat 인텔리전트 고객 서비스를 예로 들면, Kimi LLM으로 고객 질문에 답하면서 텍스트뿐 아니라 이미지, 링크 카드, 음성 메시지 등 여러 메시지 타입을 한 응답에 섞어 답변할 수 있습니다. JSON Mode로 고정 구조의 응답을 받고, 각 타입을 파싱하는 예시입니다.

import os
import json
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["MOONSHOT_API_KEY"],
    base_url="https://api.moonshot.ai/v1",
)

system_prompt = """
You are the intelligent customer service of Moonshot AI (Kimi), responsible for answering various user questions. Please refer to the document content to reply to user questions. Your reply can be text, images, links, and you can include text, images, and links in a single response.

Please output your reply in the following JSON format:

{
    "text": "Text information",
    "image": "Image URL",
    "url": "Link URL"
}

Note: Please place the text information in the `text` field, put the image in the `image` field in the form of a link starting with `oss://`, and place the regular link in the `url` field.
"""

completion = client.chat.completions.create(
    model="kimi-k3",
    messages=[
        {"role": "system", "content": "You are Kimi, an artificial intelligence assistant provided by Moonshot AI, excelling in Chinese and English conversations. You provide users with safe, helpful, and accurate answers. You will reject any questions involving terrorism, racism, pornography, and violence. Moonshot AI is a proper noun and should not be translated into other languages."},
        {"role": "system", "content": system_prompt},  # <-- 출력 포맷 정의 system prompt
        {"role": "user", "content": "Hello, my name is Li Lei, what is 1+1?"}
    ],
    response_format={"type": "json_object"},  # <-- JSON Mode 활성화
)

# JSON Mode이므로 message.content는 JSON Object 문자열
content = json.loads(completion.choices[0].message.content)

if "text" in content:
    print("text:", content["text"])
if "image" in content:
    print("image:", content["image"])
if "url" in content:
    print("url:", content["url"])

3. 잘린 JSON 출력 문제 해결

response_format을 올바르게 설정하고 프롬프트에 JSON 포맷을 명시했는데도 반환된 JSON이 잘렸거나 불완전하다면, 반환값의 finish_reason 필드가 length인지 확인하세요.

max_tokens 값이 너무 작으면 출력이 잘립니다 (JSON Mode에서도 동일). 예상 출력 JSON 크기를 가늠해 합리적인 max_tokens을 설정하세요.

잘린 출력에 대한 자세한 설명은 Troubleshooting 참고.


4. 주의사항

  • Kimi LLM은 JSON Object 타입의 JSON 문서만 생성 — JSON Array 등 다른 타입을 생성하도록 프롬프트하지 마세요
  • 필요한 JSON Object 포맷을 모델에 정확히 알려주지 않으면 예기치 않은 결과가 나옴

변경 이력

날짜변경
2026-07-22초판 작성 (공식 JSON Mode 가이드 한글화)
2026-07-22제목에 "Kimi" 접두사 추가, 본문 H1 중복 제거

댓글

아직 댓글이 없습니다.

댓글을 작성하려면 로그인이 필요합니다.