본문 바로가기
C.W.K.
Stream
Lesson 05 of 06 · published

응답 길이보다 stop_reason을 먼저 확인해

~14 min · stop-sequences, stop-reason, json, structured-output

Level 0Observer
0 XP0/64 lessons0/13 achievements
0/150 XP to next level150 XP to go0% complete

멈춘 까닭이 응답의 상태를 말해 줘

모든 응답에는 stop_reason이 있어. end_turn은 자연스러운 완료, max_tokens는 출력 예산 소진, stop_sequence는 지정 문자열 도달, tool_use는 도구 실행 요청을 뜻해. 문장이 그럴듯하게 끝났어도 max_tokens라면 잘린 결과로 다뤄야 해.

중단 문자열은 가벼운 경계에 써

stop_sequences=["</answer>", "END"]를 주면 둘 중 하나가 생성되는 즉시 멈춰. 프롬프트와 함께 쓰면 짧고 단순한 조각을 떼어 내기 편해. 중첩 구조나 엄격한 검증이 필요한 데이터에는 도구 사용이나 스키마를 설명한 JSON 출력을 택해.

도구 없이 JSON을 받을 수도 있어

시스템 프롬프트에 정확한 JSON 스키마를 적고, 도우미 메시지를 {로 미리 채운 뒤, 결과를 방어적으로 해석하는 방식이 있어. 미리 채운 시작 문자가 모델을 원하는 형식으로 유도하지만 유효성을 보장하지는 않으니 파서와 검증은 빼면 안 돼.

원칙: 겉보기 길이가 아니라 stop_reason으로 분기해. 완료와 잘림을 구별하는 계약은 그 값이야.

Code

stop_reason 분기·python
response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=512,
    messages=[{"role": "user", "content": "Write 30 sentences about JSON."}],
)

match response.stop_reason:
    case "end_turn":
        save(response.content[0].text)
    case "max_tokens":
        # truncated — 예산 올리거나 요청을 chunk
        retry_with_higher_budget(response)
    case "stop_sequence":
        partial = response.content[0].text
        log.info("stopped on user-defined sequence")
    case "tool_use":
        dispatch_tool_calls(response)
Prefill로 JSON 강제·python
response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=512,
    system='Respond with a single JSON object matching {"intent": str, "confidence": float}. No prose.',
    messages=[
        {"role": "user", "content": "User said: 'cancel my subscription'"},
        {"role": "assistant", "content": "{"},  # prefill — 모델이 여기서부터 이어서 생성
    ],
    stop_sequences=["}\n"],
)
import json
payload = json.loads("{" + response.content[0].text)  # prefill 다시 더해
print(payload)

External links

Exercise

JSON을 산문으로 요청하던 프롬프트 하나를 (1) prefill과 stop_sequences, (2) JSON Schema 도구 사용 방식으로 각각 바꿔. 50회 호출의 파싱 실패율을 비교해.
Hint
스키마가 두 단계 이상 중첩되면 도구 사용 쪽이 더 안정적일 가능성이 커.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.