0Pricing
Claude Architect · Lekcja

Wartości enum z „other” na potrzeby rozszerzalności

Dodaj wartość „other” oraz pole ze szczegółami

Wartości enum z „other” na potrzeby rozszerzalności to bezpłatna lekcja Claude Architect na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Claude Architect, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Claude Architect zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

The Problem with a Closed Enum

Enums are the backbone of clean structured output. When you constrain a field to a fixed set of values — like category being one of billing, technical, or account — the model can't drift into free-form strings, and downstream code can branch with confidence.

But a closed enum has a hidden failure mode: the real world produces inputs your list never anticipated. When a ticket doesn't fit any allowed value, the model is forced to pick the least wrong option. That's a silent misclassification, and it corrupts everything built on top of it.

The Extensibility Pattern: 'other' + detail

The architect-grade fix is the extensibility pattern: add an "other" value to the enum, plus a free-text detail field the model fills in when it selects other.

This gives you two wins at once:

  • The model has an honest escape hatch instead of a forced bad fit.
  • You capture what the unexpected case actually was — raw signal you can mine to grow the enum later.

It turns the gap in your taxonomy into a logged, inspectable data point instead of a corrupted record.

A Schema with 'other'

Here is a classification tool for a support agent. Notice the enum includes "other", and there's a companion category_detail string for the open case.

Because structured output via tool_use + JSON Schema enforces the enum, the model literally cannot return a value outside the list — including the deliberate other safety valve.

classify_ticket = {
    "name": "classify_ticket",
    "description": "Classify a support ticket into one category.",
    "input_schema": {
        "type": "object",
        "properties": {
            "category": {
                "type": "string",
                "enum": ["billing", "technical", "account", "other"],
                "description": "Use 'other' ONLY when none of the named categories fit."
            },
            "category_detail": {
                "type": "string",
                "description": "Required when category is 'other': a short phrase naming the real category."
            }
        },
        "required": ["category"]
    }
}

Why detail Must NOT Be Required

The most important schema decision here: mark category_detail as optional, never required.

A core structured-output rule is to require a field only if it is always present. The detail field is present only when category is other — it is absent for billing, technical, and account tickets.

If you force it into required, the model will fabricate a detail string for cases that don't need one, just to satisfy the schema. You'd be manufacturing hallucinations to enforce a rule you didn't actually need.

Conditional Requirement Lives in the Prompt

So how do you make sure category_detail is filled when the model picks other? The dependency is conditional, so it belongs in the field description and the system prompt — not in the schema's static required array.

Be explicit about the rule. Explicit criteria beat vague instructions every time.

system = (
    "Classify each ticket using the classify_ticket tool.\n"
    "Pick the most specific named category that fits.\n"
    "Choose 'other' ONLY when no named category applies. "
    "When you choose 'other', you MUST also provide category_detail "
    "as a short noun phrase naming the true category "
    "(e.g. 'partnership inquiry', 'legal request')."
)

Forcing Structured Output with tool_choice

To guarantee the model returns the classification as structured data rather than prose, force the tool call. Setting tool_choice to {"type": "tool", "name": "classify_ticket"} compels Claude to emit exactly that tool's input, schema-validated.

If you had several extraction tools and just wanted to guarantee some structured call, tool_choice: "any" would do; "auto" lets the model choose between text and a tool. For a single forced schema, name the tool explicitly.

resp = client.messages.create(
    model="claude-sonnet-4-5",
    max_tokens=512,
    system=system,
    tools=[classify_ticket],
    tool_choice={"type": "tool", "name": "classify_ticket"},
    messages=[{"role": "user", "content": ticket_text}],
)

Reading the Result Safely

On the consuming side, branch on the enum. The other bucket is where you read category_detail — and where you should expect it to sometimes be missing, because it's optional.

Defensive access (a default of empty string) keeps your code robust against a legitimately absent field, which is exactly the behavior you designed for.

block = next(b for b in resp.content if b.type == "tool_use")
result = block.input
category = result["category"]

if category == "other":
    detail = result.get("category_detail", "")
    log_uncategorized(ticket_text, detail)  # capture for later enum growth
else:
    route_to_queue(category)

Mining 'other' to Grow the Enum

The detail field isn't just a fallback — it's a feedback loop. Every other record carries a human-readable label for a case your taxonomy missed.

Periodically aggregate those details. When a cluster like "partnership inquiry" shows up 40 times a week, you've found your next first-class enum value. You promote it from free text to a named category, and your classifier gets sharper — driven by real data, not guesswork.

Pairs Naturally with Retry-with-Feedback

This pattern composes cleanly with validation. If a result violates your conditional rule — say category is other but category_detail came back empty — that's a structural error, and retry-with-feedback fixes exactly those.

Send the model the original ticket, its own wrong output, and the precise validation error. Crucially, retry helps because the information needed (the real category) is present in the source. Retry would not help if the information were simply absent from the ticket.

if result["category"] == "other" and not result.get("category_detail"):
    feedback = (
        "You returned category='other' but left category_detail empty. "
        "Re-classify and provide a short detail phrase."
    )
    # resend: original ticket + the bad output + this exact error

When NOT to Add 'other'

The pattern is for extensibility under uncertainty — open-world taxonomies like ticket categories, document types, or intent labels where new cases will keep appearing.

Don't bolt other onto a genuinely closed set. A priority field of low / medium / high is exhaustive by definition; an other there just invites the model to dodge a real decision. Reserve the escape hatch for enums that legitimately can't anticipate every value.

The Full Pattern in One View

Put the pieces together and you have a small, robust contract:

  • Enum with named values plus other — the schema enforces the closed set.
  • Optional detail field — never required, so the model won't fabricate it.
  • Prompt + description carry the conditional "fill detail when other" rule.
  • Consumer branches on the enum and logs the detail.
  • Validation/retry catches a missing-but-required-by-rule detail.

It's a clean separation: the schema guarantees shape; the prompt guarantees behavior; the loop captures what you didn't foresee.

Quick Check: Designing the 'other' Field

You're building a ticket-classifier tool whose category enum includes billing, technical, account, and other. You add a category_detail string that should be populated whenever the model picks other. How should you encode the requirement that category_detail be filled for other cases?

Recap: Extensible Enums

Key takeaways:

  • Closed enums silently misclassify inputs they never anticipated; an other value gives the model an honest escape hatch.
  • Pair other with a free-text detail field to capture what the unexpected case actually was.
  • Keep the detail field optional — never require a field that may be absent, or the model will fabricate it.
  • Put the conditional "fill detail when other" rule in the prompt and field description, not the static required array.
  • Mine logged other details to grow the enum with real first-class values over time.
  • Use tool_use + JSON Schema to enforce the enum, and retry-with-feedback for structural violations.

Często zadawane pytania

Czy lekcja „Wartości enum z „other” na potrzeby rozszerzalności” jest bezpłatna?

Tak — pełny tekst „Wartości enum z „other” na potrzeby rozszerzalności” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Claude Architect, przejdź na CoddyKit PRO. Kurs Claude Architect zawiera 4 lekcji w sumie.

Co nauczysz się w „Wartości enum z „other” na potrzeby rozszerzalności”?

Dodaj wartość „other” oraz pole ze szczegółami Ćwiczysz Claude Architect z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Claude Architect?

Nie wymagamy żadnego doświadczenia. Claude Architect w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.

Ile czasu zajmuje lekcja „Wartości enum z „other” na potrzeby rozszerzalności”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Claude Architect?

Tak. Każda lekcja Claude Architect zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. tool_use dla gwarantowanej struktury
  2. Projektowanie schematu JSON
  3. Pola wymagane a opcjonalne/wartości null
  4. Wartości enum z „other” na potrzeby rozszerzalności
← Powrót do Claude Architect