Tools

Bắt Claude trả JSON chuẩn schema: dùng tool use thay vì “làm ơn trả JSON”

Tóm tắt

Khai báo một tool với input_schema (JSON Schema), đặt tool_choice bắt buộc gọi tool đó, rồi đọc input của khối tool_use. Kết hợp validate phía server và retry khi sai. Claude API cũng có tính năng structured outputs chính thức — xem docs để chọn cách phù hợp.

Ví dụ: trích xuất ticket

tools = [{
  "name": "save_ticket",
  "description": "Lưu thông tin ticket đã phân loại",
  "input_schema": {
    "type": "object",
    "properties": {
      "category": {"type": "string", "enum": ["bug", "billing", "feature", "other"]},
      "priority": {"type": "string", "enum": ["P1", "P2", "P3"]},
      "summary":  {"type": "string"}
    },
    "required": ["category", "priority", "summary"]
  }
}]

msg = client.messages.create(
  model="claude-sonnet-5-5", max_tokens=500, tools=tools,
  tool_choice={"type": "tool", "name": "save_ticket"},
  messages=[{"role": "user", "content": ticket_text}])

data = next(b.input for b in msg.content if b.type == "tool_use")

Vì sao tốt hơn prompt?

  • enum giới hạn giá trị — không còn “High”, “high”, “cao” lẫn lộn.
  • required buộc đủ trường.
  • Không có lời dẫn kiểu “Đây là JSON của bạn:” làm hỏng parser.

Checklist production

  • Validate lại bằng Pydantic / Zod ở server.
  • Retry 1–2 lần kèm thông báo lỗi validate.
  • Log input/output để debug.
  • Dùng model nhỏ cho trích xuất đơn giản, kết hợp Batch API khi chạy hàng loạt.