# standardization **Repository Path**: zhengxuhong/standardization ## Basic Information - **Project Name**: standardization - **Description**: Disease name standardization service based on vector retrieval + LLM - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-06-16 - **Last Updated**: 2026-11-04 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Disease Name Standardization Service 基于可组合 Pipeline 的术语标准化库。Pipeline 使用外部已构建的 Chroma Collection 作为唯一术语来源,通过精确、模糊、向量 Top-k、MMR 和邻居构建候选,再由 Top1 或 LLM 完成选择。 公共 API 位于 `src.engine`;结果存储位于 `src.storage`。Embedding、Chroma 写入和词表构建属于外部数据准备,不属于本库职责。 ## 核心概念 ```text CleanStage → CandidateBuildStage(Exact/Fuzzy/VectorTopK/MMR/Neighbor) → CandidateSelectStage(Top1/LLM) → ReportStage(可选) ``` - 每个 Stage 返回新的 `MatchState` 和追加的 `StageTrace`; - Pipeline 顺序执行所有 Stage; - 不提供 Cascade、条件分支或正常流程提前终止; - Stage 异常会被 Runner 捕获,生成带 `error` 的 trace 并结束本次运行; - `PipelineResult` 包含 Pipeline 名称、简介、错误、当前 state 和完整 history。 ## Chroma metadata 契约 每条名称文档都是一个独立候选,不能提前按 `term_id` 或标签合并。 ```json { "term_id": "HP:0001250", "name": "Seizure", "is_primary": true, "details": "{\"definition\":\"A seizure is abnormal...\",\"synonyms\":[\"Epileptic seizure\"]}" } ``` - `term_id`、`name` 必填; - `details` 是自由字段 JSON object; - 同一个 term 的主名和同义名全部保留; - Pipeline 只读取 Collection,不执行嵌入、写入、重建或模型部署; - 不提供 SQLite/MySQL 术语详情查询。 `ChromaSource` 参数: ```python from src.engine import ChromaSource source = ChromaSource( collection=chroma_client.get_collection("hpo_terms"), id_field="term_id", name_field="name", details_field="details", primary_field="is_primary", ) ``` ## 精确和模糊匹配 ```python from src.engine import ( ChromaSource, LLMSelector, exact_pipeline, fuzzy_llm_pipeline, fuzzy_pipeline, ) exact = exact_pipeline( source, case_sensitive=True, strip=True, collapse=False, ) fuzzy = fuzzy_pipeline( source, scorer="ratio", min_score=0.6, top_k=10, case_sensitive=True, ) fuzzy_with_llm = fuzzy_llm_pipeline( source, selector=LLMSelector(llm_client), min_score=0.6, top_k=10, ) ``` 清洗层只执行去首尾空白、空白折叠等文本清洗,不处理大小写。大小写属于 Exact/Fuzzy Builder。 ## 向量 Top-k + 单次 LLM ```python from src.engine import LLMSelector, vector_topk_llm_pipeline selector = LLMSelector( llm_client, model=None, temperature=0.1, max_tokens=8192, timeout=120, max_retries=3, reasoning_effort=None, include_candidate_details=True, max_candidate_detail_chars=400, ) pipeline = vector_topk_llm_pipeline( source, embedder=query_embedder, selector=selector, fetch_k=50, top_k=10, ) result = pipeline.run("seizure", query_embedding=[...]) ``` `embedder` 只用于查询文本转向量;如果 `run()` 已传入 `query_embedding`,不会再次嵌入。 ## MMR + LLM ```python from src.engine import mmr_llm_pipeline pipeline = mmr_llm_pipeline( source, embedder=query_embedder, selector=selector, top_k=30, max_distance=None, mmr_lambda=0.7, ) ``` MMR 在当前 Chroma Collection 的每一条名称向量上运行,不按 `term_id` 去重。候选列表保留同一术语的不同名称。 ## MMR + LLM + 邻居 + LLM ```python from src.engine import mmr_neighbor_llm_pipeline pipeline = mmr_neighbor_llm_pipeline( source, embedder=query_embedder, first_selector=selector, second_selector=selector, top_k=30, neighbor_fetch_k=20, neighbor_top_k=10, anchor_source="primary_label", ) ``` 邻居阶段读取上一层的 `selected` 作为锚点,输出“锚点 + 邻居候选”,但不改变 `selected`。因此邻居后必须再配置一个选择层。若没有 preceding selected,Pipeline 会记录 Stage 错误并返回失败结果。 ## 自定义 Pipeline ```python from src.engine import ( CandidateBuildStage, CandidateSelectStage, CleanStage, MMRBuilder, Pipeline, ReportStage, Top1Selector, ) pipeline = Pipeline( [ CleanStage(), CandidateBuildStage(MMRBuilder(source, top_k=30)), CandidateSelectStage(Top1Selector()), ReportStage("mmr_top1"), ], name="mmr_top1", description="全库 MMR 后直接选择第一项", ) ``` ## 选择层和默认提示词 `Top1Selector` 直接取当前候选列表第一项,不调用 LLM。 `LLMSelector` 每次只执行一次 LLM 选择。同一个类可在 Pipeline 中复用多次,由位置决定作用,不存在单独的 Verify Stage。 默认设置: - `temperature=0.1` - `max_tokens=8192` - `timeout=120` - `max_retries=3` - `reasoning_effort=None` - `include_candidate_details=True` - `max_candidate_detail_chars=400` - `response_format={"type": "json_object"}` 默认提示词只包含: - 只能从候选列表选择; - term_id 必须逐字复制; - 无合适候选返回 null; - 不得编造编号; - 只输出 JSON。 不包含文献语境、距离规则、缩写、同义名或上下位词规则。词表专属限制通过 `SelectionPrompt(extra_rules=(...))` 添加。 ### Prompt token 预算 `max_prompt_tokens` 必须与 `token_counter` 一起使用: ```python selector = LLMSelector( llm_client, token_counter=my_token_counter, max_prompt_tokens=96000, ) ``` 提供 `token_counter` 但省略 `max_prompt_tokens` 时,默认预算为 96000。只设置 `max_prompt_tokens` 而不提供 tokenizer 会直接报错,避免伪造 token 估算。 ## 结果、Trace 和报告 ```python result.selected result.state.candidates result.history result.pipeline_name result.pipeline_description result.error result.state.report ``` - `history` 始终包含完整 Stage trace; - LLM Stage 的 input 包含实际发送的 system/user messages; - Stage 异常会记录 stage 名称、参数、耗时和 `error`; - `ReportStage` 只负责格式化报告,不是完整 trace 的唯一来源。 ## 结果存储 SQLite/MySQL 继续作为结果存储,并新增 `save_pipeline()`: ```python from src.engine import SqliteResultStore store = SqliteResultStore("results.db") store.save_pipeline(result) ``` ```python from src.engine import MySQLResultStore store = MySQLResultStore( host="localhost", port=3306, user="standardization", password="...", database="standardization", ) store.save_pipeline(result) ``` `save_pipeline()` 除转换后的标准化字段外,还保存: - Pipeline 名称和简介; - 完整 history 和 Report 的 JSON; - 当前选中候选和候选列表; - Stage 错误信息。 失败结果不属于已处理项;`processed_names(retry_unmatched=True)` 只返回已成功匹配项。 ## 数据准备脚本 数据准备不属于安装包,也不存在 console entry point。脚本位于 `scripts/`: ```bash uv run python scripts/download_vocabularies.py mondo hpo hgnc uv run python scripts/embed_collection.py --help uv run python scripts/deduplicator.py uv run python scripts/rare_candidate_parser.py uv run python scripts/rebuild_mondo_terms.py ``` 这些脚本生成 Chroma 集合或词表数据;Pipeline 只消费最终 Collection。 legacy rare-first: ```bash uv run python scripts/rare_first_matching.py --help ``` 该脚本保留旧实现,不进入新公共 API。 ## 环境配置 ```bash LLM_BASE_URL=https://api.deepseek.com/v1 LLM_MODEL=deepseek-chat LLM_API_KEYS=key1,key2,... EMBEDDING_SERVICE_URL=http://your-embedding-service:20000 CHROMA_HOST=localhost CHROMA_PORT=20011 ``` 依赖通过 Git 引用: - `string-cleaning` - `string-matching` ## 验证 ```bash uv run pytest uv run ruff check src tests scripts uv run mypy uv build ```