Перечисления со значением «other» для расширяемости
Добавляйте значение «other» и отдельное поле с подробностями
«Перечисления со значением «other» для расширяемости» — бесплатный урок Claude Architect на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Claude Architect, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Claude Architect содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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 errorWhen 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
othervalue gives the model an honest escape hatch. - Pair
otherwith 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
requiredarray. - Mine logged
otherdetails 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.
Часто задаваемые вопросы
Урок «Перечисления со значением «other» для расширяемости» бесплатный?
Да — полный текст урока «Перечисления со значением «other» для расширяемости» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Claude Architect, подпишись на CoddyKit PRO. Курс Claude Architect содержит 4 уроков всего.
Чему я научусь в уроке «Перечисления со значением «other» для расширяемости»?
Добавляйте значение «other» и отдельное поле с подробностями Ты практикуешь Claude Architect с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Claude Architect?
Предыдущий опыт не требуется. Claude Architect на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Перечисления со значением «other» для расширяемости»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Claude Architect?
Да. Каждый урок Claude Architect включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- tool_use для гарантированной структуры
- Проектирование схемы JSON
- Обязательные и необязательные поля, допускающие отсутствие значения
- Перечисления со значением «other» для расширяемости