⚡ 중급2026-04-187분
JSON 출력을 100% 보장하는 법 — tool use
"JSON으로만 답해줘"는 가끔 깨진다. tool use(function calling)를 쓰면 파싱 실패가 사라진다.
apitool-usejson
왜 문자열 지시가 깨지는가
모델이 앞뒤에 사족을 붙이거나, 마지막에 마침표를 찍거나, 코드 블록 마커를 섞는다. 프로덕션 파이프라인에선 이 확률만큼 장애가 난다.
해결: tool use
Anthropic API에 tools를 정의하면 모델이 반드시 해당 스키마로 호출한다.
const msg = await client.messages.create({
model: "claude-sonnet-4-6",
max_tokens: 1024,
tools: [{
name: "record_lead",
description: "문의에서 고객 정보를 구조화해 기록한다",
input_schema: {
type: "object",
properties: {
name: { type: "string" },
email: { type: "string" },
intent: { type: "string", enum: ["sales", "support", "spam"] },
urgency: { type: "number", minimum: 1, maximum: 5 },
},
required: ["name", "email", "intent", "urgency"],
},
}],
tool_choice: { type: "tool", name: "record_lead" },
messages: [{ role: "user", content: emailBody }],
})
const call = msg.content.find(c => c.type === "tool_use")
const data = call?.input // ← 항상 위 스키마를 따른 객체
장점
- 스키마 위반 시 Anthropic이 재시도
enum/required/minimum검증 자동- 파싱 try/catch 지옥 제거
체크리스트
- [ ]
tool_choice로 강제 호출했나 - [ ] required 필드 명시
- [ ] enum으로 분류값 제한
- [ ] description에 비즈니스 맥락 추가