# Jev hierarchical classification: beam search over 250K nodes

> Use Jev hierarchical classification to sort documents to the deepest level of the category tree—one Choice per level yields a probability distribution, and…

Source: https://gaodong.ai/en/jev/4-scenarios/a2-hierarchical-classification

---

# 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](https://docs.typesafe.ai/cookbooks/hierarchical_classification.md) 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](/jev/2-daily/02-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](https://docs.typesafe.ai/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, `ThreadPoolExecutor` parallel 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? {#为什么用-jev-而不是普通-llm-分层分类}

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](/jev/2-daily/02-choice))
- 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](/jev/2-daily/02-choice): know how to write an options map in `criteria`, can read `choice` and `probabilities`
- [ ] Got [Installation and your first request](/jev/1-start/03-install-first-request) working: `.venv` is usable, `TYPESAFE_API_KEY` is in the environment variables
- [ ] (Smoother) Read [Parallel questions and speculative fan-out](/jev/3-workflow/01-parallel-questions): 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 {#第-1-步-把扁平类目树改成嵌套字典}

**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:

```python
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 `TREE` lists only direct children, with no cross-level jumps

### Step 2: Write child_question: one Choice per level asking "which direct child matches best" {#第-2-步-写-child-question-每层一道-choice-问「哪个直接子类最匹配」}

**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:

```python
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 value
```

`MODEL` 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 `criteria` use `c0/c1` instead of the original category names

### Step 3: Implement greedy: at each level, bet on only the single highest-probability child {#第-3-步-实现-greedy-每层只押概率最高的一个子节点}

**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:

```python
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):

```bash
python hierarchical_classification.py
```

**What 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 {#第-4-步-实现-beam-search-保留最好的-3-条路径逐层并行展开}

**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:

```python
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 fairly
- `separation = 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, `beam` is sorted by score and truncated to K=3; paths that have reached a leaf stay in `finished` with their scores and continue to compete in the final ranking

::: tip 💡 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 {#第-5-步-跑四棵官方类目树-对比-jev-层级分类的两种走法}

**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 Beds` under `Pet Supplies` (probability 0.53), discarding `Cat 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 on `Pet Chairs`
- The other path kept by beam goes `Cat Supplies` 0.45 → `Cat Furniture` 0.98 → `Cat Window Beds & Perches` 0.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 answer `A 人类必需` only had 0.34), then went into `E99Z 兜底类`; 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 {#第-6-步-读懂-top-second-分离度-决定要不要转人工}

**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.

```python
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](/jev/4-scenarios/a4-self-consistency) to vote again.

- [ ] My code outputs the top/second ratio; I know the difference between 1.04× and 2.20×

## 📋 Magic Prompt {#📋-魔法-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) {#📝-直接子类提问-choice-版}

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.

```python
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.

```python
# 必填项：【】里换成你的 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.

```python
# 官方原文的替代方案：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.py` runs: beam returns K=3 sorted paths for my `TREE`, 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](https://docs.typesafe.ai/primitives/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 {#❌-每层串行发请求-不做-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](/jev/3-workflow/01-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 {#❌-把-mesh-这类-dag-直接当树走}

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](/jev/reference/02-models-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](/jev/4-scenarios/a1-twitch-filter)).

**Look at the official diagrams.** The cookbook page has full-traversal SVGs of all four trees (official links: [CPC](https://mintcdn.com/ts-docs/2NirYCl-v96cw05F/cookbooks/hierarchical_classification/cpc_tree.svg), [Shopify](https://mintcdn.com/ts-docs/2NirYCl-v96cw05F/cookbooks/hierarchical_classification/shopify_tree.svg), [MeSH](https://mintcdn.com/ts-docs/2NirYCl-v96cw05F/cookbooks/hierarchical_classification/mesh_tree.svg), [source code](https://mintcdn.com/ts-docs/2NirYCl-v96cw05F/cookbooks/hierarchical_classification/codebase_tree.svg))—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](/jev/4-scenarios/a3-confidence-classification)—when categories have only two levels and 75 options fit in one call, use confidence gating instead of hierarchical traversal
- [Choice questions](/jev/2-daily/02-choice)—the foundation of this page: the criteria options map, the probabilities distribution, and the 255 cap
- [Self-consistency](/jev/4-scenarios/a4-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](/jev/4-scenarios/a3-confidence-classification).

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
