A2X 自动层次化分类树构建模块(build)设计详解:BFS 递归 + LLM 驱动的全自动 Taxonomy 生成

原创2026-10-09 10:05:062,251 阅读
文章标签:人工智能AI Agent服务注册发现认证鉴权后端

A2X 自动层次化分类树构建模块(build)设计详解:BFS 递归 + LLM 驱动的全自动 Taxonomy 生成

导读

A2X(Agent-to-X)是 openJiuwen agent-protocol 仓库中用于智能体服务发现的核心方案,而构建模块(a2x_registry/a2x/build/)正是整个 A2X 体系的"分类树生产者":它接收一份扁平的 service.json 服务列表,完全由 LLM 驱动,自动生成可供语义导航使用的层次化分类树(taxonomy.json + class.json),全程无需人工设计或维护目录结构。本文以 build_design.md 为骨架,结合 a2x_registry/a2x/build/ 下的真实源码实现,完整讲解其 BFS 递归主流程、CLI 与 Python 调用方式、全部配置项、输入输出格式、三类设计视图,以及断点续传、关键词缓存、跨域多父归属等关键机制,读者可据此直接运行、调参或二次开发自己的自动分类树构建管线。


1. 构建模块在 A2X 体系中的定位

在 a2x_design.md 的系统整体视图中,注册模块(a2x_registry/register/)负责服务生命周期管理并输出 service.json,构建模块消费这份 service.json,产出分类树(taxonomy.json + class.json),再被搜索模块消费。数据流关系为:

注册模块 → service.json → 构建模块 → 分类树 → 搜索模块

构建模块的职责被精确定义为:将一份扁平的服务列表自动转化为层次化分类树,全程由 LLM 驱动,无需人工设计或维护目录结构。它与"传统基线(MCP 全上下文)"、"向量基线(ChromaDB 检索)"形成互补:分类树的质量直接决定 A2X 递归语义导航(LLM 沿"领域 → 子领域 → 具体能力 → 服务"逐层逼近,查找成本接近 O(log N))的上限,因此自动构建出的树必须覆盖完整、边界清晰、层级合理。


2. 流程逻辑说明:BFS 递归主循环

整个构建过程以 BFS 递归 为主循环,从根节点开始,逐层拆分过大的节点(超过 max_service_size 的叶节点入队继续细分),直至所有叶节点足够小或达到最大深度 max_depth。每个节点的拆分由 NodeSplitter 编排,包含以下五个步骤:

  1. 分类设计(CategoryDesigner.design):根据节点规模自动选择策略——大节点(服务数 > keyword_threshold)先通过 KeywordExtractor 批量提取功能关键词,再基于关键词频率设计分类;小节点直接基于服务描述设计分类。仅 root 节点的关键词会缓存到 keywords.json 供复用,子节点的关键词不保存(因为子节点关键词限定在各自功能域内,混用会导致污染)。Root 节点还会额外经过 LLM 验证和修正(_validate_and_fix_root_categories,最多 2 次重试)。
  2. 服务分类(NodeSplitter._classify_all):将所有服务并行分配到子分类中(每服务 1 次 LLM 调用,使用 ThreadPoolExecutor 以 workers 个线程并发)。匹配过多子分类的服务标记为"泛分类"(generic),无法匹配的标记为"未分类"(unclassified),两者均留在父节点。
  3. 收敛判断(NodeSplitter._should_terminate):若无泛分类且无未分类服务,或达到最大迭代次数 max_refine_iterations,则收敛退出迭代。
  4. 迭代优化(CategoryDesigner.refine):未收敛时,将分类统计(normal/generic/unclassified 数量、每个子分类的服务数、tiny 子分类提示)和问题服务反馈给 LLM,调整子分类方案后重新分类。
  5. 边界处理(NodeSplitter._finalize_assignments):删除过小的子分类(服务数 ≤ delete_threshold),将其中的服务重新归入未分类列表(留在父节点)。

BFS 主循环(TaxonomyBuilder)在每个节点拆分后,将仍然过大的子节点入队继续细分,直至所有叶节点足够小或达到最大深度。每次拆分后立即保存中间结果(_save_output),支持断点续传。

最后,跨域多父归属(CrossDomainAssigner)识别应同时出现在多个功能域的服务,将其链接到其他域的最佳叶分类,提升跨域可发现性。

分类规则(generic_ratio 判定,源码佐证)

在 node_splitter.py 中,每个服务的分类结果按匹配子分类数 n_cats 分三档(阈值为 max(1, int(N * generic_ratio)),N 为子分类总数):

类别 判定条件 处理方式
正常(Normal) 1 <= n_cats <= N * generic_ratio 接受,允许多父归属
泛分类(Generic) n_cats > N * generic_ratio 清空其 category_ids,留在父节点
未分类(Unclassified) n_cats == 0 留在父节点

收敛条件(_should_terminate,node_splitter.py)为:iteration >= max_refine 或 n_generic == 0 且 n_unclassified == 0。


3. 对外调用接口

3.1 CLI 入口

构建模块以 Python 模块方式提供 CLI(入口见 main.py):

# 完全重构(output-dir 默认为 database/{数据集名}/taxonomy)
python -m a2x_registry.a2x.build --service-path database/ToolRet_clean/service.json

# 断点续传(完成则跳过,中断则继续,配置变更则重建)
python -m a2x_registry.a2x.build --service-path database/ToolRet_clean/service.json --resume yes

# 复用关键词重构(调试用,跳过关键词提取)
python -m a2x_registry.a2x.build --service-path database/ToolRet_clean/service.json --resume keyword

CLI 支持的全部可选参数(默认值均与 AutoHierarchicalConfig 一致,可直接与 Python 接口互相换算):

参数 默认值 说明
--output-dir path database/{数据集名}/taxonomy 自定义输出目录
--keyword-batch-size N 50 关键词提取每批服务数
--keyword-threshold N 500 服务数 > 该值走关键词提取,否则直接基于描述设计
--max-service-size N 40 叶节点最大服务数(超出则入队继续拆分)
--max-categories-size N 20 每个节点最多子分类数
--generic-ratio F 0.333 泛分类阈值
--delete-threshold N 2 超小子分类删除阈值
--max-depth N 3 最大递归深度(设为 1 可跳过递归细分)
--workers N 20 并行工作线程数
--max-refine-iterations N 3 最大精炼迭代轮数
--no-cross-domain 关闭 禁用跨域分配(--resume 为 store_true 开关)
--resume {no,keyword,yes} no 构建模式:no=完全重构、keyword=复用缓存关键词、yes=智能断点续传

启动时 CLI 会打印一份完整配置摘要(数据集名、服务路径、输出目录、resume 模式及各关键阈值),便于确认本次构建的生效参数。

数据集命名约定:service.json 所在的上级目录名即为数据集名。例如 database/ToolRet_clean/service.json → 数据集名 ToolRet_clean,默认输出至 database/ToolRet_clean/taxonomy。该逻辑实现在 config.py 的 dataset_name property 中(Path(self.service_path).parent.name)。

3.2 Python 接口

from a2x_registry.a2x.build import AutoHierarchicalConfig, TaxonomyBuilder

config = AutoHierarchicalConfig(
    service_path="your_services.json",
    # output_dir 默认为 "database/{数据集名}/taxonomy"
)

builder = TaxonomyBuilder(config)
builder.build()                    # 完全重构
builder.build(resume="yes")        # 断点续传
builder.build(resume="keyword")    # 复用关键词重构

build() 的三种模式语义(见 taxonomy_builder.py):

  • resume="no":完全重构——_clean_output() 删除全部中间产物(taxonomy.json、class.json、keywords.json、build_config.json、assignments.json),从零开始;
  • resume="keyword":重构但保留 keywords.json(_clean_output(preserve_keywords=True)),跳过 root 关键词提取,用于调试迭代;
  • resume="yes":智能续传——_evaluate_resume() 根据输出目录中是否存在 taxonomy.json 与 build_config.json、配置是否匹配、build_status 是否为 "complete",决定 skip(完成且配置匹配则跳过)/ resume(未完成则从检查点继续)/ rebuild(配置变更或无检查点则重建)。

TaxonomyBuilder 还支持传入 stop_event(threading.Event)实现外部取消,构建期间每步都会调用 _check_cancelled(),收到取消请求时抛出 InterruptedError。

3.3 配置项(AutoHierarchicalConfig)

完整配置定义见 config.py,除文档列出的字段外,源码还包含若干补充字段。以下为全部字段及含义:

@dataclass
class AutoHierarchicalConfig:
    # 路径
    service_path: str = "database/ToolRet_clean/service.json"
    output_dir: str = None   # 默认 "database/{dataset_name}/taxonomy"

    # 关键词提取
    keyword_batch_size: int = 50       # 每批服务数
    max_keywords_per_service: int = 5  # 每个服务最多关键词数
    temperature_keywords: float = 0.0  # 关键词提取采样温度(源码补充)

    # 分类设计
    temperature_design: float = 0.0    # 分类设计采样温度(源码补充)
    keyword_threshold: int = 500       # 大/小节点设计策略切换阈值
    max_categories_size: int = 20      # 每个节点最多子分类数

    # 分类/精炼
    generic_ratio: float = 1/3         # 泛分类阈值(匹配超过此比例的子分类则为泛分类)
    delete_threshold: int = 2          # 超小子分类删除阈值
    classification_retries: int = 2    # 单服务分类失败重试次数(源码补充)
    max_refine_iterations: int = 3     # 最大精炼迭代轮数
    temperature_classify: float = 0.0  # 单服务分类采样温度(源码补充)

    # 树结构
    max_service_size: int = 40         # 叶节点最大服务数(超出则入队继续拆分)
    max_depth: int = 3                 # 最大递归深度
    min_leaf_size: int = 5             # 叶节点最小服务数(精炼提示用,源码补充)

    # 并行
    workers: int = 20                  # 并行工作线程数

    # LLM max_tokens
    max_tokens_design: int = 6000       # 分类设计(关键词 / root 重设计)
    max_tokens_design_small: int = 4000 # 分类设计(描述 / 子节点精炼)
    max_tokens_classify: int = 300      # 单服务分类
    max_tokens_validate: int = 3000     # root 分类验证
    max_tokens_keywords: int = 4000     # 关键词提取(每批)

    # 跨域
    enable_cross_domain: bool = True   # 是否启用跨域多父归属

    # 构建结束写入(非构建参数)
    service_hash: Optional[str] = None # SHA256(服务 name+description 排序对)

值得注意的几点源码细节:

  • output_dir 在 __post_init__ 中按 database/{dataset_name}/taxonomy 推导,因此不传也会自动补齐;
  • _NON_BUILD_FIELDS = frozenset({"output_dir", "workers", "service_hash"}) 标记不影响构建结果的字段:build_params() 只返回影响产物内容的参数,matches_saved_config() 用它们与已保存的 build_config.json 比对(浮点字段容差 1e-3,service_path 仅按数据集名比较,不同绝对路径指向同一数据集仍视为匹配);
  • service_hash 为服务 (name, description) 排序对的 SHA256,由 taxonomy_builder.py 在保存时写入 build_config.json,供注册服务检测分类树是否过期。

4. 输入输出格式

4.1 输入 — service.json

[
  {"id": "svc_1", "name": "FlightBooking", "description": "Book flights...", "inputSchema": {...}}
]

关键字段为 id(唯一标识)、name 与 description——构建只依赖这三个字段,inputSchema 等其余字段会随服务对象透传进 services_index。_compute_service_hash 也只对 (name, description) 排序对取哈希,印证这两个字段是驱动分类树结构的唯一因素。

4.2 输出 — taxonomy.json(树结构 + 构建状态)

{
  "version": "2.0-hierarchical",
  "root": "root",
  "build_status": "complete",
  "categories": {
    "root": {"children": ["cat_travel", "cat_finance"], "services": ["svc_generic"]},
    "cat_travel": {"children": ["cat_flights", "cat_hotels"], "services": []},
    "cat_flights": {"children": [], "services": ["svc_1", "svc_2"]}
  }
}

build_status 取值:"bfs"(BFS 拆分中)、"cross_domain"(BFS 完成,跨域待处理)、"complete"(构建完成)。中间保存策略保证了这三个状态可被断点续传直接识别:_evaluate_resume() 读取该字段决定 skip/resume/rebuild。

4.3 输出 — class.json(分类元数据)

{
  "version": "2.0-hierarchical",
  "categories": {
    "cat_travel": {
      "name": "Travel & Tourism",
      "description": "Services for booking flights, hotels, and travel planning",
      "boundary": "Not for financial transactions or insurance",
      "decision_rule": "If the service helps users plan or book trips"
    }
  }
}

每个分类携带 name、description、boundary(边界,即"不属于什么")与 decision_rule(判定规则,即"什么服务归入此类")四项元数据,这些正是后续 LLM 语义导航进行逐层决策的依据。源码中 _parse_categories 还会保留 associated_keywords(用于 root 验证失败时的关键词重分配),但该字段不写入 class.json。

4.4 输出 — assignments.json(分配详情,调试用)

{
  "svc_1": {"category_ids": ["cat_flights"], "reasoning": "Flight booking service"}
}

记录每个服务的最终归属分类与 LLM 给出的 reasoning,便于排查分类质量。

4.5 输出目录文件清单

输出目录(默认 database/{数据集名}/taxonomy)共包含五类文件,其中 keywords.json(root 关键词缓存)与 build_config.json(构建配置 + service_hash)是支撑续传/复用机制的关键:

文件 内容 生命周期
taxonomy.json 树结构 + build_status 每次拆分后即时保存
class.json 分类元数据 每次拆分后即时保存
assignments.json 分配详情 非空时保存
keywords.json root 关键词缓存 resume=no 时删除,keyword/yes 时保留
build_config.json 构建参数 + service_hash 每次保存时写入

5. 逻辑视图

flowchart TB
    SVC([服务列表]) --> TB

    subgraph TB_BOX[TaxonomyBuilder — BFS 主循环]
        direction TB
        TB[从队列取出<br/>过大的节点] --> NS

        subgraph NS_BOX[NodeSplitter.split_node]
            direction TB
            NS[开始拆分] --> STRATEGY{服务数 ><br/>keyword_threshold?}
            STRATEGY -->|是| KE[关键词提取<br/>KeywordExtractor.extract]
            KE --> KW_DESIGN[基于关键词设计分类]
            STRATEGY -->|否| DESC_DESIGN[基于描述设计分类]
            KW_DESIGN --> ROOT_CHK{is_root?}
            ROOT_CHK -->|是| VALIDATE[验证 + 修正]
            ROOT_CHK -->|否| CLASSIFY
            VALIDATE --> CLASSIFY
            DESC_DESIGN --> CLASSIFY
            CLASSIFY[并行分类服务] --> CONVERGE{收敛?}
            CONVERGE -->|否| REFINE[迭代优化<br/>CategoryDesigner.refine]
            REFINE --> CLASSIFY
            CONVERGE -->|是| EDGE[边界处理<br/>泛分类/超小分类/未分类]
        end

        EDGE --> SAVE[中间保存]
        SAVE --> CHECK{子节点服务数<br/>> max_service_size?}
        CHECK -->|是| TB
        CHECK -->|否| DONE([所有叶节点<br/>足够小])
    end

    DONE --> CDA[跨域多父归属<br/>CrossDomainAssigner]
    CDA --> TAX[(taxonomy.json<br/>+ class.json)]

    style SVC fill:#eceff1,stroke:#607d8b
    style TAX fill:#e8eaf6,stroke:#3f51b5,stroke-width:2px
    style KE fill:#fff3e0,stroke:#ff9800
    style KW_DESIGN fill:#ffe0b2,stroke:#ff9800
    style DESC_DESIGN fill:#ffe0b2,stroke:#ff9800
    style REFINE fill:#fff3e0,stroke:#ff9800
    style CLASSIFY fill:#ffcc80,stroke:#ff9800
    style CDA fill:#fff9c4,stroke:#f9a825
    style STRATEGY fill:#ffab91,stroke:#ff5722
    style ROOT_CHK fill:#ffab91,stroke:#ff5722
    style CONVERGE fill:#ffab91,stroke:#ff5722
    style CHECK fill:#ffab91,stroke:#ff5722
    style DONE fill:#c8e6c9,stroke:#4caf50

关键实现对应:_find_pending_nodes()(taxonomy_builder.py)负责在全新构建(root 含全部服务、无子节点,root 入队)与续传(仅未拆分的超大叶节点入队)两种场景下扫描待拆节点;_run_bfs()(同文件 #L260-L311)执行主循环,每个节点拆分后立即 _save_output(),并将 > max_service_size 的子节点按 depth < max_depth 条件入队。


6. 顺序图:一次完整构建的 LLM 交互时序

sequenceDiagram
    participant U as 用户
    participant TB as TaxonomyBuilder
    participant NS as NodeSplitter
    participant CD as CategoryDesigner
    participant KE as KeywordExtractor
    participant CDA as CrossDomainAssigner
    participant L as LLM

    U->>TB: build(resume="no")
    TB->>TB: 加载服务, 初始化 taxonomy
    TB->>TB: build_status = "bfs"

    rect rgb(255, 243, 224)
        Note over TB,L: BFS 主循环 — 对每个过大的节点
        TB->>NS: split_node(node, services, is_root)

        rect rgb(255, 248, 225)
            Note over NS,L: Step 1: 分类设计 (CategoryDesigner.design)
            NS->>CD: design_categories(services, is_root)
            alt 大节点 (服务数 > keyword_threshold)
                CD->>KE: extract(services)
                loop 每批 50 服务
                    KE->>L: 服务描述 + 已有关键词
                    L-->>KE: keywords[]
                end
                KE-->>CD: 关键词频率表
                CD->>L: 基于关键词频率设计分类
                L-->>CD: categories[]
                opt 仅 root 节点
                    CD->>L: 验证 + 修正违规分类
                    L-->>CD: validated categories
                end
            else 小节点 (服务数 ≤ keyword_threshold)
                CD->>L: 基于服务描述设计分类
                L-->>CD: categories[]
            end
            CD-->>NS: 子分类方案
        end

        rect rgb(255, 224, 178)
            Note over NS,L: Step 2: 分类 + 精炼迭代
            loop 最多 max_refine_iterations 轮(默认 3)
                par 并行分类 (workers 线程)
                    NS->>L: 服务描述 + 子分类列表 → 选择所属分类
                    L-->>NS: category_ids
                end
                NS->>NS: 计算统计, 检查收敛
                break 收敛(无泛分类且无未分类)
                    NS->>NS: 退出迭代
                end
                NS->>CD: refine_categories(统计 + 问题服务)
                CD->>L: 调整子分类方案
                L-->>CD: refined subcategories
                CD-->>NS: 优化后的方案
            end
            NS->>NS: 边界处理(泛分类/超小分类/未分类)
        end

        NS-->>TB: NodeSplitResult
        TB->>TB: 应用结果, 中间保存
        TB->>TB: 过大的子节点入队
    end

    TB->>TB: build_status = "cross_domain"

    rect rgb(255, 249, 196)
        Note over TB,L: 跨域多父归属
        TB->>CDA: assign(taxonomy, class_data, services)
        loop 每个有服务的叶分类 (并行)
            CDA->>L: 服务 + 其他顶级域 → 识别跨域服务
            L-->>CDA: cross_assignments[]
        end
        loop 每个跨域服务 (并行)
            CDA->>L: 服务 + 目标域子分类 → 定位最佳叶分类
            L-->>CDA: target_leaf_id
        end
        CDA-->>TB: additions
    end

    TB->>TB: build_status = "complete", 保存
    TB-->>U: 构建完成

6.1 源码层面的关键交互细节

  • 关键词分批提取(keyword_extractor.py):每批 keyword_batch_size(50)个服务,后一批 prompt 会携带前序累计的关键词列表(existing_keywords_text),由 LLM 避免同义词重复;关键词统一 strip().lower().replace(' ', '_') 归一化,返回 {keyword: count} 并按频次降序。
  • 关键词缓存命中判定(category_designer.py):仅 root 节点会先尝试 _load_cached_keywords() 读取 {output_dir}/keywords.json;命中则跳过提取(对应 resume=keyword/yes),未命中则提取并 _save_keywords()(对应 resume=no)。
  • root 验证与修正(同文件 #L369-L419):_llm_validate_categories 让 LLM 逐分类审计功能域合规性;发现违规后收集违规分类的 associated_keywords,调用 _redesign_violated_categories 让 LLM 将这些关键词重分配到合法域,最多重试 2 次;重设计结果若不足 3 个分类则保守保留原方案。
  • 单服务分类重试(node_splitter.py):每次分类默认最多 1 + classification_retries(3)次尝试;LLM 调用失败或返回非 JSON 时重试,且重试 prompt 会附加"请只输出 JSON"的纠错说明;分类结果中的 category_ids 会过滤掉不在当前子分类集合内的非法 id。
  • 进度反馈(progress.py):分类、关键词提取、跨域两阶段均通过终端原位进度条展示进度,同时向 logging 发射进度记录,供 Web UI 日志捕获。
  • 跨域两阶段(cross_domain_assigner.py):Phase 1 对每个有服务的叶分类并行询问 LLM 哪些服务还应出现在其他顶级域(约束:每服务最多额外 1 个域、只建议确有可发现性收益的服务、典型 10%-30% 服务受益);Phase 2 为每个跨域候选在目标域叶分类中定位最佳归属,confidence < 40 的候选被拒绝,目标域无叶分类时退化为挂到域根。只有顶级域数量 ≥ 2 时才执行该阶段。

7. 类图

classDiagram
    class TaxonomyBuilder {
        -config: AutoHierarchicalConfig
        -taxonomy: Dict
        -class_data: Dict
        -services_index: Dict
        -all_assignments: Dict
        +build(resume: str) void
        -_evaluate_resume() str
        -_clean_output(preserve_keywords) void
        -_init_taxonomy() void
        -_load_existing_output() void
        -_load_services_index() void
        -_find_pending_nodes() Deque
        -_run_bfs(queue, splitter) int
        -_get_node_info(node_id) Dict
        -_apply_split_result(node_id, result) void
        -_accumulate_assignments(result) void
        -_apply_cross_domain(client) void
        -_save_output() void
        -_print_summary(elapsed, total_split) void
    }

    class NodeSplitter {
        -client: LLMClient
        -config: AutoHierarchicalConfig
        -designer: CategoryDesigner
        +split_node(node_id, parent_info, services, is_root) NodeSplitResult
        -_classify_refine_loop(node_id, parent_info, services, subcategories, is_root) tuple
        -_finalize_assignments(assignments, subcategories) List
        -_classify_all(services, subcategories, parent_info) Dict
        -_classify_single(service, ...) ClassificationResult
        -_compute_stats(assignments, subcategories) Dict
        -_should_terminate(stats, iteration, max_refine) bool
    }

    class CategoryDesigner {
        -client: LLMClient
        -config: AutoHierarchicalConfig
        -keyword_extractor: KeywordExtractor
        +design_categories(services, node_info, is_root, max_categories) Dict
        +refine_categories(parent_info, subcategories, assignments, services, stats, is_root) Dict
        -_design_from_keywords(services, ..., is_root) Dict
        -_design_from_descriptions(services, ...) Dict
        -_validate_and_fix_root_categories(categories, keywords) Dict
        -_load_cached_keywords() Dict
        -_save_keywords(keywords) void
    }

    class KeywordExtractor {
        -client: LLMClient
        -config: AutoHierarchicalConfig
        +extract(services, node_info) Dict~str, int~
        -_extract_batch(services, existing_keywords, ...) Dict
    }

    class CrossDomainAssigner {
        -client: LLMClient
        -workers: int
        +assign(taxonomy, class_data, services_index) Dict
        -_phase1_identify(...) List
        -_phase2_place(...) Dict
    }

    class AutoHierarchicalConfig {
        +service_path: str
        +output_dir: str
        +dataset_name: str [property]
        +keyword_threshold: int
        +max_service_size: int
        +max_depth: int
        +enable_cross_domain: bool
        +get_max_categories() int
        +build_params() Dict
        +matches_saved_config(path) bool
        +save(path) void
    }

    TaxonomyBuilder --> AutoHierarchicalConfig : uses
    TaxonomyBuilder --> NodeSplitter : creates
    TaxonomyBuilder --> CrossDomainAssigner : creates
    NodeSplitter --> CategoryDesigner : owns
    CategoryDesigner --> KeywordExtractor : owns

7.1 职责边界说明

  • TaxonomyBuilder 是唯一对外门面:负责 resume 决策、BFS 调度、结果落盘与构建摘要输出(_print_summary 会统计拆分数、分类总数、叶节点数、最大深度、深度分布、总分配数与耗时,并逐项打印顶级域的服务分布)。它不直接接触 LLM,而是创建 NodeSplitter 与 CrossDomainAssigner 完成实际 LLM 工作。
  • NodeSplitter 编排单节点拆分的"设计 → 分类/精炼 → 边界处理"三步,CategoryDesigner 与 KeywordExtractor 均为其成员。
  • 根节点与子节点复用同一套代码路径(is_root 仅影响关键词缓存、验证修正与 prompt 上下文),这是"统一 BFS 递归"设计的核心体现。

8. 与增量构建、后端服务的衔接

8.1 增量构建

分类树建好之后,服务集合还会持续变化。仓库为此在 incremental_builder.py 提供了 IncrementalBuilder,支持在不全量重建的前提下向既有分类树增删服务:remove_service(service_id) 从所有分类节点与索引中移除服务;add_service(service) 先让 LLM 选出相关顶级域(SELECT_DOMAINS_TEMPLATE,多数服务 1 个域、横切服务 2-3 个域),再在目标域内定位最佳叶分类(PLACE_IN_CATEGORY_TEMPLATE,confidence < 40 时挂到域根)。它可作为全量构建的补充,服务于高频增量更新场景。

8.2 后端触发与状态查询

在 README.md 描述的完整部署形态中,构建可通过后端 REST API 触发与监控:

curl -X POST http://localhost:8000/api/datasets/my_dataset/build \
curl http://localhost:8000/api/datasets/my_dataset/build/status
curl http://localhost:8000/api/datasets/my_dataset/build/stream

build_config.json 中写入的 service_hash 正是供 RegistryService 判断"service.json 已变化、分类树需要重建"的依据(见 taxonomy_builder.py 的注释)。


9. 实践建议与注意事项

  1. 运行前提:构建是纯 LLM 工作流,只需配置好 LLM API key(llm_apikey.json),不需要向量检索等重型依赖即可运行(依赖布局说明见 README.md)。
  2. 参数调试路径:先用小数据集(服务数 ≤ keyword_threshold)验证"描述设计 → 分类 → 精炼"链路;--max-depth 1 可跳过递归细分快速获得单层分类;--resume keyword 可在不改关键词的前提下反复调试下游分类与精炼逻辑。
  3. token 预算:max_tokens_classify=300 是最小预算(单服务分类输出极简 JSON),大节点设计为 6000、root 验证为 3000,调整时需按各操作实际输出规模合理配比。
  4. 收敛质量:泛分类与未分类服务会留在父节点,generic_ratio 越小越容易触发"泛分类";delete_threshold 控制超小分类的清理力度,两者共同决定父节点的"垃圾桶"大小与树的纯净度。
  5. 断点续传:默认开启——每次拆分后即时保存,中断后以 --resume yes 继续即可;若更改了影响产物的构建参数(build_params() 范围内,output_dir/workers 除外),续传会自动降级为全量重建。

10. 相关文档与源码索引

内容 路径
构建模块设计文档(本文主体) AgentRegistry/docs/build_design.md
A2X 系统整体设计 AgentRegistry/docs/a2x_design.md
配置定义 AgentRegistry/a2x_registry/a2x/build/config.py
CLI 入口 AgentRegistry/a2x_registry/a2x/build/main.py
BFS 主循环与断点续传 AgentRegistry/a2x_registry/a2x/build/taxonomy_builder.py
节点拆分编排 AgentRegistry/a2x_registry/a2x/build/node_splitter.py
分类设计与精炼 AgentRegistry/a2x_registry/a2x/build/category_designer.py
关键词提取 AgentRegistry/a2x_registry/a2x/build/keyword_extractor.py
跨域多父归属 AgentRegistry/a2x_registry/a2x/build/cross_domain_assigner.py
增量构建 AgentRegistry/a2x_registry/a2x/incremental/incremental_builder.py
进度条实现 AgentRegistry/a2x_registry/a2x/build/progress.py
项目总览与依赖说明 AgentRegistry/README.md
登录后查看全文
agent-protocol