Deep Hierarchical Classification: sorting content to the deepest level of the category tree
💡 One-sentence summary: use Jev hierarchical classification to penetrate deep category trees—one Choice per level for the full probability distribution, K=3 parallel beam search descending level by level, sorting and truncating by geometric mean score.
Your category table may be much deeper than you think. The official Hierarchical Classification cookbook runs experiments on four real category trees: the CPC patent classification with 254,274 nodes, Shopify retail product categories with 12,378, MeSH biomedical topics with 65,373, and a source code directory tree with 125 nodes. A document isn't fully classified until it reaches a leaf—for example, a patent abstract for a "bird perch" must ultimately land in the specific category A01K31/12 Perches for poultry or birds, e.g. roosts.
A single Choice allows at most 255 options—nowhere near enough for 250K nodes. The official approach: treat the category tree as a menu and ask level by level—each node only asks "which direct child best matches," and the probability distribution of the answer becomes the edge to the next level. This is one of the scenarios the official documentation explicitly names as a true second request: the code must receive the previous level's answer before it knows which options to offer next (the exact words in primitives.md: uses each Choice answer to decide which options the next request offers).
Asking level by level hides a trap: shallow-level judgments are often ambiguous ("does this product description count as pet supplies or furniture?"), and if you bet on only one answer per level, one wrong step is unrecoverable. The official solution is beam search: keep K=3 candidate paths, expand them in parallel each round, and use deep-level evidence to fix shallow-level ambiguity. Official tests: greedy hits 2/4, beam K=3 hits 4/4. This lesson walks you through the whole thing in about 20 minutes (official difficulty: Intermediate).
What You'll Be Able to Do After This Lesson
- Turn any deep hierarchical category system (e-commerce categories, email folders, ticketing systems, source code directories) into a nested dictionary, with one Choice per level asking downward
- Write a complete beam search implementation: K=3 candidate paths, geometric mean score sorting,
ThreadPoolExecutorparallel expansion - Read the separation metric and know when to hand off to a human instead of forcing a classification
- Explain in depth the test results from the official 4 datasets: greedy 2/4 → beam 4/4, including how beam fixes shallow-level ambiguity on CPC and Shopify
Why Jev instead of plain LLM-based hierarchical classification?
A plain LLM can also ask level by level "which child should we go to," but at every level you have to parse the text it produces, and it can't give you quantified confidence. With Jev, every level's answer comes with a probability distribution:
| Capability | Plain LLM level-by-level classification | Jev hierarchical classification |
|---|---|---|
| Options per level | The model improvises freely; category names drift all the time | The answer is always one of the current node's direct children, no parsing needed |
| Confidence level | You have to ask "are you sure," and the reply is still text | Every edge carries a probability; the geometric mean score is computed directly |
| Shallow-level ambiguity | Bet on one; if wrong, keep forcing it downward | beam search keeps K=3 paths; deep-level evidence repairs it in hindsight |
| Parallel candidate paths | Requests sent level by level, path by path; latency multiplies by K | Each path in the beam gets its own question, all sent in parallel in the same round |
| Observability and debugging | The intermediate process is a black box | The probabilities of every node and every edge are stored; which level went wrong is clear at a glance |
The last point is no small matter. The official cookbook specifically emphasizes that decomposing into a hierarchy itself gives you observability (which node has the most misclassifications, how many times each edge has been traversed) and testability (after the category table is updated, unit tests directly quantify the impact on classification quality).
Your Current Predicament
- "3 million products in the catalog, a category tree with 6 levels and 12,000 nodes. AI product classification works fine at shallow levels, but the deeper it goes, the less anyone can say for sure, so people review items one by one"
- "We set up a three-level folder structure for AI email classification, but the model always forces a single folder choice; one wrong level makes everything after it wrong, and we don't even know which level went wrong"
- "Want the LLM to output JSON classification results, but one broken format takes the pipeline down for a day; want to add 'route to a human when uncertain,' but don't know how to quantify uncertainty"
When to use this technique
Use this when you need to:
- Classify documents into a category tree dozens of levels deep with thousands to hundreds of thousands of nodes, and land on a leaf
- Keep alternates when a level's judgment is ambiguous—evidence from deeper levels gets the final say
- Leave a probability trail at every step: which level went wrong, which edge is most ambiguous—all inspectable
And you don't want to:
- Stuff more than 255 options at once (Choice hard limit)
- Parse free-form text the LLM spits out at each level
- Retune prompts and rerun the full dataset every time the category table updates
🎒 Preparation before starting
- Completed Choice multiple-choice questions: know how to write an options map in
criteria, can readchoiceandprobabilities - Got Installation and your first request working:
.venvis usable,TYPESAFE_API_KEYis in the environment variables - (Smoother) Read Parallel questions and speculative fan-out: the beam parallel expansion on this page is the same "evaluate questions in parallel" capability
- A cup of water ☕—the code on this page is built up in six steps into one file: one tree, two kinds of search, one set of metrics; you won't see output until step 6
Follow along
Create hierarchical_classification.py and paste the code block from each step below into the same file in order. This page does not download the official dataset—the official loading code is long and the download is sizable; we use the official verified conclusions and numbers directly, and the code focuses on the algorithm itself. Swap in your own category tree and it will run.
Step 1: Turn the flat category tree into a nested dictionary
Why: The first thing in hierarchical classification isn't sending requests—it's turning your category table into Tree = dict[str, Tree]—each node lists only its direct children. What the next level looks like can only be known after the previous level's answer, which is exactly the definition of a "true second request."
Paste in the skeleton first:
import os
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typesafe_sdk import Choice, RetryPolicy, TypeSafeClient
Tree = dict[str, "Tree"] # 每个节点 = {直接子类名: 它自己的子树};叶子 = {}
# 换成你的类目:邮箱文件夹、电商类目、工单体系都行
TREE: Tree = {
"退货/物流": {
"退货流程": {"退货地址": {}, "退款进度": {}},
"物流查询": {"快递单号": {}, "配送异常": {}},
},
"产品咨询": {
"尺码规格": {},
"使用方法": {},
},
}
DOCUMENT = "客户消息:我上周退的裙子,退款怎么还没到账?"Each key in Tree is the options for one question at the current node; an empty dictionary {} is a leaf—once classified here, classification ends.
What you should see: The file doesn't produce anything yet—TREE and DOCUMENT are just data; the request-sending code isn't pasted until step 2.
- Every node in my
TREElists only direct children, with no cross-level jumps
Step 2: Write child_question: one Choice per level asking "which direct child matches best"
Why: The official approach assembles each node's child list into one Choice: instructions is a fixed single sentence, and criteria is the child mapping. Keys use short names like c0 and c1, and the answer is mapped back to the original label afterward—category names are often long and weird (Cat Window Beds & Perches), and short key names keep the probability distribution clean.
Next, paste in the client and question construction:
MODEL, BEAM_WIDTH, MAX_DEPTH, EPSILON = "jev-1.12", 3, 12, 1e-9
client = TypeSafeClient(
api_key=os.environ["TYPESAFE_API_KEY"],
retry=RetryPolicy(max_retries=5, backoff_initial=1.0, backoff_max=20.0),
)
def child_question(labels: tuple[str, ...]) -> tuple[Choice, dict[str, str]]:
"""Build the direct-child Choice and its reversible option mapping."""
keys = {f"c{i}": label for i, label in enumerate(labels)}
question = Choice(
instructions="Which direct child category best matches this document?",
criteria=keys,
)
return question, keys
def subtree(tree: Tree, path: tuple[str, ...]) -> Tree:
"""Return the direct-child menu below ``path``."""
value = tree
for label in path:
value = value[label]
return valueMODEL uses jev-1.12, the model the official cookbook sampled with; switching to jev-latest also works, though the probability numbers will differ slightly from the official recorded ones. MAX_DEPTH=12 is a safety valve—the official MeSH Crohn Disease path is 6 levels deep, so this is enough and prevents stack overflow.
What you should see: Still no output—the client and child_question() are just definitions; no code calls them yet.
- I can explain why the keys of
criteriausec0/c1instead of the original category names
Step 3: Implement greedy: at each level, bet on only the single highest-probability child
Why: Greedy is the most intuitive approach and also the official baseline. Get it running first, and you'll see with your own eyes the fatal flaw of hierarchical classification: one early mistake, no recovery.
Next, paste in the request wrapper and greedy:
def choose(state: str, labels: tuple[str, ...]) -> dict[str, float]:
"""Ask one atomic direct-child question and return its distribution."""
if len(labels) == 1: # 只有一个子类:不是决策,不发请求
return {labels[0]: 1.0}
question, keys = child_question(labels)
response = client.system_one(state=state, questions={"child": question}, model=MODEL)
probabilities = response.answers["child"].probabilities
return {label: probabilities[key] for key, label in keys.items()}
def greedy_search(tree: Tree, document: str) -> dict:
"""Follow only the locally highest-probability child."""
path, probability_product, decision_count = (), 1.0, 0
for _ in range(MAX_DEPTH):
labels = tuple(subtree(tree, path))
if not labels:
break
probabilities = choose(document, labels)
label = max(probabilities, key=probabilities.get)
if len(probabilities) > 1:
probability_product *= max(probabilities[label], EPSILON)
decision_count += 1
path += (label,)
score = probability_product ** (1 / decision_count) if decision_count else 1.0
return {"path": path, "score": score}Two official details. A single-child node is not a decision: choose() directly returns 1.0 when there's only one child—no request sent, not counted in decision_count—the probability product is divided by the number of decisions, so these "fake decisions" don't dilute it. EPSILON=1e-9: An edge with probability 0 would turn the whole path into 0 in the product, ruining the geometric mean score; the official implementation uses 1e-9 as a floor.
Run (with TYPESAFE_API_KEY set):
python hierarchical_classification.pyWhat you should see: Still no output—the greedy function was just defined. But you can walk through it verbally first: one question of 退货/物流 vs 产品咨询, one question of 退货流程 vs 物流查询, one question of 退货地址 vs 退款进度—three requests to reach a leaf.
- I can explain why a single-child node doesn't count as a decision
Step 4: Implement beam search: keep the best 3 paths and expand them in parallel level by level
Why: This is the core of this lesson. Greedy goes all wrong if it errs at a shallow level; beam search keeps K candidates and sends all expandable paths in parallel each round, using evidence from deeper levels to give shallow-level ambiguity a second chance.
Next, paste in:
def extend_candidate(candidate: dict, label: str, probabilities: dict[str, float]) -> dict:
"""Append one edge and recompute its geometric-mean path score."""
is_decision = len(probabilities) > 1
probability_product = candidate["probability_product"] * (
max(probabilities[label], EPSILON) if is_decision else 1.0
)
decision_count = candidate["decision_count"] + is_decision
return {
"path": candidate["path"] + (label,),
"probability_product": probability_product,
"decision_count": decision_count,
"score": probability_product ** (1 / decision_count) if decision_count else 1.0,
}
def beam_search(tree: Tree, document: str) -> dict:
"""Parallel width-three beam search using geometric-mean probability."""
beam = [{"path": (), "probability_product": 1.0, "decision_count": 0, "score": 1.0}]
for _ in range(MAX_DEPTH):
expandable = [c for c in beam if subtree(tree, c["path"])]
finished = [c for c in beam if not subtree(tree, c["path"])]
if not expandable:
break
with ThreadPoolExecutor(max_workers=BEAM_WIDTH) as executor:
distributions = list(
executor.map(
lambda c: choose(document, tuple(subtree(tree, c["path"]))),
expandable,
)
)
expanded = []
for candidate, probabilities in zip(expandable, distributions, strict=True):
for label in probabilities:
expanded.append(extend_candidate(candidate, label, probabilities))
beam = sorted(finished + expanded, key=lambda c: c["score"], reverse=True)[:BEAM_WIDTH]
beam = sorted(beam, key=lambda c: c["score"], reverse=True)
return {"beam": beam}Read it according to the official formulas:
path_score = product(edge_probabilities) ** (1 / decisions)—the geometric mean. Why not the product: The product penalizes deep paths—a path with 10 levels all 0.9 (0.35) would lose to a path with 3 levels all 0.9 (0.73); the geometric mean normalizes for depth, so shallow and deep leaves compete fairlyseparation = top_path_score / second_path_score—the ratio of the first-place to second-place score, not used for pruning; it's for you to see the degree of ambiguity- Each round,
beamis sorted by score and truncated to K=3; paths that have reached a leaf stay infinishedwith their scores and continue to compete in the final ranking
💡 This is the unique value of Jev
Beam search itself is an old algorithm, used in machine translation decoding for decades. What Jev provides is the fuel: the complete probability distribution at every step. An ordinary LLM gives you only one "answer it thinks is right" per level, leaving the beam's K paths unscorable; with Jev every edge is a quantified probability, so geometric means, ranking, and pruning are all pure code. The official material also makes an important point: each path in the beam is sent together as parallel questions, so exploring a few more paths adds almost no wall-clock latency.
What you should see: Still no output—beam_search() has been defined but nothing calls it yet; it runs for the first time in step 6.
- I can explain why the geometric mean is used instead of the product to score paths
Step 5: Run four official category trees and compare the two approaches to Jev hierarchical classification
Why: Your TREE is too small to show the gap. The official run goes through four real category trees, checking answers against known answers.
You should see (the officially recorded reference results):
| Category tree | Version | Node count | Document example | Greedy result | Beam K=3 result |
|---|---|---|---|---|---|
| CPC patents | 2026.05 | 254,274 | Bird perch patent abstract | ❌ E99Z99/00 (fallback category) | ✅ A01K31/12 |
| Shopify products | 2026-02 | 12,378 | Cat window bed product description | ❌ Pet Chairs | ✅ Cat Window Beds & Perches |
| MeSH biomedical | 2026 | 65,373 | Crohn disease clinical abstract | ✅ Crohn Disease | ✅ Crohn Disease |
| CookSafe source code | snapshot 2026-08-06 | 125 | Find the experiment retrieval module | ✅ retrievers.py | ✅ retrievers.py |
Both failure cases died the same way. Look at how the Shopify "cat window bed" product description died:
- At layer 2, greedy chose
Pet BedsunderPet Supplies(probability 0.53), discardingCat Supplies(0.45) — that single step's gap of 8 percentage points dragged the whole path into a world where dog dens and cat beds are indistinguishable, finally landing onPet Chairs - The other path kept by beam goes
Cat Supplies0.45 →Cat Furniture0.98 →Cat Window Beds & Perches0.92 — layers 3 and 4 are consecutively high-probability, the geometric mean score overtakes, and it wins - Same story for CPC: greedy at layer 1 got taken away by
E 固定建筑0.62 (the correct answerA 人类必需only had 0.34), then went intoE99Z 兜底类; the A path kept by beam sings loudly all the way from layer 2 onward with 0.95, 0.99, 0.71, 0.99
MeSH and CookSafe both got it right either way — the value of beam is not guaranteed victory, it's fixing shallow-layer ambiguity; when the shallow layers are clear, it just spends a few extra questions' worth of tokens.
- I can recount at which layer greedy went wrong in the Shopify example and how beam rescued it
Step 6: Read the top/second separation and decide whether to escalate to a human
Why: once you have the final classification, you still need to answer "can this classification be trusted". A byproduct of beam is separation: the ratio of the top and second path scores.
result = beam_search(TREE, DOCUMENT)
beam = result["beam"]
if len(beam) > 1:
separation = beam[0]["score"] / max(beam[1]["score"], EPSILON)
print(f"top/second = {separation:.2f}x")
print("leaf:", beam[0]["path"][-1] if beam[0]["path"] else "no leaf")You should see: one line each for the top/second ratio and the final leaf (replace with your own TREE, the values will naturally differ). The officially recorded numbers for the four trees give you a sense of calibration: CPC 1.04×, Shopify 1.17×, MeSH 1.81×, CookSafe 2.20×. Close to 1× means ambiguity — in the CPC case the answer was correct, but the top and second were nearly touching, showing the document is genuinely fuzzy between two deep categories. The official qualitative description of this metric: near 1× is ambiguous; a large ratio means a clear separation.
It is not used for pruning — pruning only looks at each path's own geometric mean score. separation is for humans to look at: for classifications hugging 1×, don't write them straight to the database; escalate to a human or use self-consistency to vote again.
- My code outputs the top/second ratio; I know the difference between 1.04× and 2.20×
📋 Magic Prompt
The "Prompt" on this page is a question template for the API — copy it, replace the 【】 placeholders, and you can use it on your own category tree. The three-piece set: layer-by-layer questioning, scoring with pruning, single-child nodes.
📝 Direct child question (Choice version)
Expected effect: turn the "where to go next" of any category node into a single Choice; the answer comes with a full distribution, so all K paths can get edge probabilities.
from typesafe_sdk import Choice
# 必填项:【】里换成你当前节点的直接子类
question, keys = child_question(("【子类A】", "【子类B】", "【子类C】"))
# child_question 的核心是:
# Choice(
# instructions="Which direct child category best matches this document?",
# criteria={"c0": "【子类A】", "c1": "【子类B】", "c2": "【子类C】"},
# )
# 输出规范:answer.choice 是最高概率子类的键;answer.probabilities 是全部子类的分布
# 约束条件:
# ✅ 只列直接子类,不要跨层塞孙类
# ✅ 键名用 c0/c1 短名,label 放进 criteria 的值
# ❌ 不要塞超过 255 个选项——Choice 硬上限🔧 Path scoring and pruning (geometric mean version)
Expected effect: give each candidate path a depth-normalized score, sort by score and truncate to K paths — shallow and deep leaves compared fairly.
# 必填项:【】里换成你的 beam 宽度和深度安全阀
BEAM_WIDTH = 【3 起步,官方示例值;类目树深且浅层模糊可加宽】
MAX_DEPTH = 【12 起步,盖过你最深的路径;防爆栈】
EPSILON = 1e-9
# score = product(edge_probabilities) ** (1 / decision_count)
# 约束条件:
# ✅ 单子节点(len(probabilities)==1)不进连乘、不计决策数
# ✅ 每轮把已到叶子的路径留在 finished 里参与最终排序
# ❌ 不要用连乘打分——深路径被系统性惩罚✅ Numerical stability for deep trees (log-space version)
Expected effect: when the category tree exceeds 10 layers, the floating-point error from repeated multiplication will smear the scores; switch to the equivalent formula in log space.
# 官方原文的替代方案:exp(mean(log(probs))) 等价于 product ** (1/decisions)
import math
def log_space_score(probs: list[float]) -> float:
return math.exp(sum(math.log(max(p, EPSILON)) for p in probs) / len(probs))
# 约束条件:
# ✅ 树深 > 10 层时换这个公式,避免精度损失
# ❌ 不要在浅树上也换——多一层换算,没必要Checkpoint ✅
hierarchical_classification.pyruns: beam returns K=3 sorted paths for myTREE, printing the top/second ratio and the final leaf- I can name beam's three components: geometric mean score, truncating to K each round, keeping finished paths
- I can recount the official 4 dataset conclusions: greedy 2/4, beam 4/4, Shopify died at layer 2 with 0.53 vs 0.45
- I know a single-child node doesn't count as a decision (returns 1.0, not counted in decision_count)
- I know a separation close to 1× should be escalated to a human, and is not used for pruning
Pitfall reminders
❌ Stuffing the entire category tree into one question
Choice has a hard cap of 255 options (choice.md verbatim: A Choice question accepts up to 255 options). A tree with 250,000 nodes is not a matter of "splitting into a few more questions" — the hierarchical structure itself is the answer: one question per layer, question count = depth, not = node count. The official MeSH Crohn Disease path is 6 layers; with beam K=3 the total requests are only a dozen or so.
❌ Scoring paths with a chained product instead of a geometric mean
The chained product naturally penalizes deep paths: a full 0.9 10-layer path (0.35) loses to a full 0.9 3-layer path (0.73), even though each step is equally solid. The geometric mean product ** (1/decisions) normalizes for depth—in the official words: The probability is length-normalized so that shallow and deep leaves are compared fairly. For extra safety on deep trees: exp(mean(log(probs))) avoids precision loss.
❌ Sending requests serially layer by layer, with no parallelism within the beam
The K paths of a beam are mutually independent, so executor.map fires them all at once—this is exactly the "parallel question evaluation" capability from Jev parallel questions. Waiting for answers serially path by path multiplies the wall-clock time of K=3 by 3, and the beam's scalability is gone.
❌ Treating a DAG like MeSH directly as a tree and walking it
In MeSH, one descriptor can have multiple parents (a DAG). The official approach: expand the official tree number paths into a tree—a descriptor with multiple tree numbers occupies multiple positions in the tree. If your category table is a DAG (one product listed under multiple categories), first think clearly about which expansion you want; walking it directly will drop paths at the forks.
❌ Putting Chinese-language documents straight into production
The official docs state plainly that English is the primary training language; CJK works but with lower accuracy. Test Chinese product descriptions and Chinese emails first with real data, focusing on how well the probabilities separate at each layer—for a tree where shallow layers all hug 0.5, no beam width can save it. See models and pricing for details.
Advanced tips (optional)
Swap the scoring metric. The official alternative metric: min(top_prob/second_top_prob)—optimize paths where "every node is clearly separated" rather than "clear on average." Worth trying when shallow layers have many nodes and a single ambiguous node carries a big cost.
Cache replay. The official recipe decorates choose() with JsonCache from the cooksafe library—answers are stored in JSON keyed by "state + question," so reruns cost zero requests and zero spend. For scenarios where the category table changes daily and documents are added daily, caching can save real money (usage shown in step 1 of live chat filtering).
Look at the official diagrams. The cookbook page has full-traversal SVGs of all four trees (official links: CPC, Shopify, MeSH, source code)—orange for the greedy route, green for the beam winner, purple for retained paths, dashed lines for pruned edges; every number in step 5 of this page can be matched on the diagrams.
Run regression after updating the category table. The testability the officials emphasize: store documents with known answers as a test set, rerun the beam after every category revision, and changes in hit rate and separation are immediately visible—far more solid than "tweak the prompt and hope for the best."
Lesson summary
✅ The Jev hierarchical classification pipeline: category tree → nested dict → one Choice per layer → K=3 parallel beam search → ranking by geometric-mean score → separation to judge ambiguity.
✅ Official benchmarks: CPC 254,274 nodes, Shopify 12,378, MeSH 65,373, CookSafe 125—greedy hits 2/4, beam K=3 hits 4/4; for both CPC and Shopify, shallow-layer ambiguity (0.53 vs 0.45, 0.62 vs 0.34) was rescued by the beam's deeper evidence.
✅ Three key design choices: a single child node doesn't count as a decision (1.0 and excluded from decision_count), geometric mean for depth normalization (the chained product penalizes deep paths), and EPSILON=1e-9 as a floor for zero-probability edges.
✅ This is a true second-request scenario officially called out: the code must have the previous layer's answer before it can build the next layer's options—one of three real examples alongside skill_suggestion and autoformat.
Key configuration fields, revisited:
| Field | Value on this page | Notes |
|---|---|---|
BEAM_WIDTH | 3 | Official example value; widen it if shallow-layer ambiguity is heavy |
MAX_DEPTH | 12 | Safety valve; MeSH goes 6 layers deep |
EPSILON | 1e-9 | Floor for zero-probability edges, protecting the geometric mean |
MODEL | "jev-1.12" | Official sampled version; switching to jev-latest gives different numbers |
RetryPolicy | max_retries=5, backoff 1.0→20.0 | Official example configuration |
| Questions per layer | 1 | The beam's multiple paths are sent in parallel within the same round |
Related tutorials:
- 75-industry classification—when categories have only two levels and 75 options fit in one call, use confidence gating instead of hierarchical traversal
- Choice questions—the foundation of this page: the criteria options map, the probabilities distribution, and the 255 cap
- Self-consistency—when separation hugs 1×, don't force a split; vote several times and check the agreement rate
Next lesson preview
The beam preserves deep-layer accuracy, but some tasks polarize right at the shallow layer—when the answer is uncertain, rather than forcing a pick, automatically escalate to the top-level category. Next lesson: 75-industry classification: escalate to the top category when confidence is low.
You will learn:
- A single Choice with 75 options classifies into all SEC industry groups, with confidence built into the answer
- confidence ≥ 0.9 reports the industry group; below that, a lookup escalates to the parent top-level category—zero second calls
- Official benchmark on 60 annual reports: gating raises the usable rate from 39/60 to 48/60