0Pricing
Claude Architect · 강의

필수 필드와 선택적/널 허용 필드

없을 수 있는 필드는 절대 필수로 지정하지 않습니다

필수 필드와 선택적/널 허용 필드은(는) CoddyKit의 무료 Claude Architect 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Claude Architect 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Claude Architect 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

The Core Rule

Structured output with tool_use and a JSON Schema eliminates syntax errors and lets you enforce required fields. But that power has a sharp edge.

The exam-critical rule for this lesson: mark a field required only if it is always present. Never require a field that may be absent.

Why? When a field is required, the model must emit a value for it. If the source data doesn't actually contain that value, the model has no choice but to fabricate one to satisfy the schema. A required field is a promise the model will keep even when it shouldn't.

Why Required Forces Fabrication

A JSON Schema's required array is a hard constraint, not a hint. The model cannot return a structurally valid object while omitting a required key.

Consider extracting a customer's phone_number from a support email that never mentions a phone number. If phone_number is required, the model must produce something — and a plausible-looking but invented number is worse than no number at all, because nothing downstream can tell it apart from a real one.

The fix is structural: make optional fields optional, so the model can legitimately leave them out when the information is absent.

A Schema That Invites Fabrication

Here is an extraction tool that marks every field as required. The email below has no phone number — yet the schema forces the model to invent one.

This is the anti-pattern. Read required carefully: it lists fields that may genuinely be missing from real inputs.

tool = {
    "name": "extract_contact",
    "description": "Extract contact details from a support email.",
    "input_schema": {
        "type": "object",
        "properties": {
            "name": {"type": "string"},
            "email": {"type": "string"},
            "phone_number": {"type": "string"},
        },
        # BAD: phone_number is often absent, but it is required here
        "required": ["name", "email", "phone_number"],
    },
}

The Fix: Require Only the Guaranteed

Keep in required only the fields that are always present. Everything that may be absent stays out of required — the model can then omit it honestly.

Notice name and email stay required because every support ticket has them, while phone_number drops out of the list.

tool = {
    "name": "extract_contact",
    "description": "Extract contact details from a support email.",
    "input_schema": {
        "type": "object",
        "properties": {
            "name": {"type": "string"},
            "email": {"type": "string"},
            "phone_number": {"type": "string"},
        },
        # GOOD: only the always-present fields are required
        "required": ["name", "email"],
    },
}

Optional vs. Nullable: Two Different Tools

There are two ways to let a field be "missing", and they mean different things:

  • Optional — the key is simply omitted from required. The model may leave the key out of the object entirely.
  • Nullable — the key is always present but its type allows null, signalling "this slot was checked and found empty."

Optional answers "did the model report on this field at all?" Nullable answers "the model looked, and the value is explicitly absent." Choose nullable when a downstream consumer needs every key present for a stable shape.

Expressing Nullable in JSON Schema

To make a field nullable, allow null as one of its types. With structured outputs you typically express this with anyOf (a supported keyword) combining the real type and null.

Here phone_number is always emitted as a key, but its value is null when the email contains no number — an honest "empty", not a fabricated digit string.

"phone_number": {
    "anyOf": [
        {"type": "string"},
        {"type": "null"}
    ],
    "description": "Customer phone number, or null if none is stated in the email."
}

Nullable Still Needs an Honest Instruction

A nullable type permits null, but the model still decides when to use it. Make the intent explicit in the field description: tell the model to return null rather than guess.

This pairs the structural guarantee (the type allows null) with a behavioural one (the description says when to use it). The schema defines the shape; the description steers the judgment.

"discount_code": {
    "anyOf": [{"type": "string"}, {"type": "null"}],
    "description": "The promo code the customer mentioned. Return null if no code is present — do not invent or infer one."
}

Enums Plus an 'Other' Escape Hatch

The same fabrication risk appears with enums. If a field must be one of a fixed set of values and the real input doesn't match any of them, a strict enum forces the model to pick the closest wrong answer.

The exam-recommended pattern for extensibility: include an "other" value in the enum plus a free-text detail field. This gives the model an honest place to land when reality exceeds your enum — instead of misclassifying.

"category": {
    "type": "string",
    "enum": ["billing", "technical", "account", "other"]
},
"category_detail": {
    "anyOf": [{"type": "string"}, {"type": "null"}],
    "description": "Free-text description used when category is 'other'; otherwise null."
}

Retry Won't Rescue an Absent Value

When validation fails, retry-with-feedback is powerful — you resend the original document, the model's wrong output, and the exact validation error to fix format, structural, or arithmetic mistakes.

But retry does not help when the information is simply absent from the source. If the phone number isn't in the email, no amount of re-prompting will conjure a correct one. The right design lets the field be absent in the first place — required-and-missing is a schema bug, not a transient error to retry.

Self-Correction Detects, Schema Prevents

For values that should be present and verifiable, a complementary technique is self-correction: extract both a calculated_total and a stated_total so a mismatch surfaces a discrepancy you can catch.

But self-correction detects errors in present data; it cannot validate a field that was never in the source. The first line of defense against fabrication is still the schema itself: don't require what may be absent. Use Pydantic-style validation on the result to enforce these invariants in code.

from pydantic import BaseModel
from typing import Optional

class Invoice(BaseModel):
    invoice_id: str            # always present → required
    po_number: Optional[str]   # may be absent → optional / nullable
    calculated_total: float
    stated_total: float        # compare the two to detect discrepancies

Distinguish Empty From Failure

One more architect-grade distinction: a valid empty result ("the email has no phone number") is not the same as an access failure ("the extraction tool errored").

A nullable field cleanly represents the first case. Don't model a genuine absence as an error to retry, and don't silently suppress a real failure as null. Make the schema say which is which: null for legitimately empty, a separate error path for access failures. Clear, structured signals downstream beat ambiguous ones.

Quick Check: Optional Field Design

Apply the rule to a realistic extraction scenario.

Recap: Never Require the Maybe-Absent

Key takeaways:

  • Require only always-present fields. Requiring a possibly-absent field forces the model to fabricate a value.
  • Optional = key may be omitted; nullable = key always present, value may be null. Pick nullable when consumers need a stable key set.
  • Pair nullable types with a description that says "return null if absent — don't guess."
  • For closed value sets, add an "other" enum value plus a free-text detail field for extensibility.
  • Retry-with-feedback fixes format/structural/arithmetic errors, not absent information. Self-correction detects discrepancies in present data, not missing fields.
  • Keep a valid empty result distinct from an access failure — never silently suppress either.

자주 묻는 질문

“필수 필드와 선택적/널 허용 필드” 강의는 무료인가요?

네 — “필수 필드와 선택적/널 허용 필드” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Claude Architect 강의 전체를 잠금 해제할 수 있습니다. Claude Architect 강의에는 총 4개의 강의가 포함되어 있습니다.

“필수 필드와 선택적/널 허용 필드”에서 뭘 배우나요?

없을 수 있는 필드는 절대 필수로 지정하지 않습니다 브라우저에서 직접 실행하는 실습 코드로 Claude Architect을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Claude Architect을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Claude Architect은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“필수 필드와 선택적/널 허용 필드” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Claude Architect 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Claude Architect 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 보장된 구조를 위한 tool_use
  2. JSON 스키마 설계
  3. 필수 필드와 선택적/널 허용 필드
  4. 확장성을 위한 'other' 열거형 값
← Claude Architect(으)로 돌아가기