kb-common 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
kb_common/__init__.py ADDED
@@ -0,0 +1,42 @@
1
+ """Common infrastructure shared by KB business packages.
2
+
3
+ This package is the extraction target for a standalone PyPI distribution.
4
+ It intentionally contains no project-search or document-search business rules.
5
+ """
6
+
7
+ from kb_common.embeddings import EmbeddingModel
8
+ from kb_common.pipeline import (
9
+ BuildVectorRecordsStep,
10
+ CandidateMergeStep,
11
+ EmbeddingModelProtocol,
12
+ Pipeline,
13
+ PipelineContext,
14
+ PipelineError,
15
+ PipelineStep,
16
+ StepError,
17
+ VectorRetrieveStep,
18
+ VectorStoreProtocol,
19
+ WriteVectorIndexStep,
20
+ )
21
+ from kb_common.vector_store import VectorIndex, VectorRecord, VectorStore
22
+
23
+ __version__ = "0.1.0"
24
+
25
+ __all__ = [
26
+ "BuildVectorRecordsStep",
27
+ "CandidateMergeStep",
28
+ "EmbeddingModel",
29
+ "EmbeddingModelProtocol",
30
+ "Pipeline",
31
+ "PipelineContext",
32
+ "PipelineError",
33
+ "PipelineStep",
34
+ "StepError",
35
+ "VectorIndex",
36
+ "VectorRecord",
37
+ "VectorRetrieveStep",
38
+ "VectorStore",
39
+ "VectorStoreProtocol",
40
+ "WriteVectorIndexStep",
41
+ "__version__",
42
+ ]
@@ -0,0 +1,77 @@
1
+ """本地嵌入模型封装"""
2
+
3
+ import os
4
+ from pathlib import Path
5
+ from typing import Optional
6
+
7
+ os.environ.setdefault("OMP_NUM_THREADS", "1")
8
+ os.environ.setdefault("MKL_NUM_THREADS", "1")
9
+
10
+ from huggingface_hub import snapshot_download
11
+ from sentence_transformers import SentenceTransformer
12
+
13
+
14
+ class EmbeddingModel:
15
+ """嵌入模型封装"""
16
+
17
+ def __init__(
18
+ self,
19
+ model_name: str = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
20
+ device: str = "cpu",
21
+ ):
22
+ """
23
+ Args:
24
+ model_name: 模型名称
25
+ device: 运行设备 (cpu/cuda)
26
+ """
27
+ self._model: Optional[SentenceTransformer] = None
28
+ self._model_name = model_name
29
+ self._device = device
30
+
31
+ @property
32
+ def model(self) -> SentenceTransformer:
33
+ """懒加载模型"""
34
+ if self._model is None:
35
+ try:
36
+ import torch
37
+
38
+ torch.set_num_threads(1)
39
+ except ImportError:
40
+ pass
41
+
42
+ model_path = self._resolve_local_model_path()
43
+ try:
44
+ self._model = SentenceTransformer(str(model_path), device=self._device)
45
+ except Exception as exc:
46
+ raise RuntimeError(
47
+ f"本地嵌入模型加载失败: {model_path}。"
48
+ "请确认模型缓存完整,或先在有网络环境下载模型。"
49
+ ) from exc
50
+ return self._model
51
+
52
+ def _resolve_local_model_path(self) -> Path:
53
+ """解析本地模型路径,避免 SentenceTransformer 的 repo-id 分支联网。"""
54
+ model_path = Path(self._model_name).expanduser()
55
+ if model_path.exists():
56
+ return model_path
57
+
58
+ try:
59
+ return Path(
60
+ snapshot_download(self._model_name, local_files_only=True)
61
+ ).expanduser()
62
+ except Exception as exc:
63
+ raise RuntimeError(
64
+ f"本地嵌入模型缓存不存在或不可用: {self._model_name}。"
65
+ "当前服务启动不进行联网下载;请先在有网络环境下载模型,"
66
+ "或将 embedding.model 配置为本地模型目录。"
67
+ ) from exc
68
+
69
+ def encode(self, text: str) -> list[float]:
70
+ """将文本编码为向量"""
71
+ embedding = self.model.encode(text, convert_to_numpy=True)
72
+ return embedding.tolist()
73
+
74
+ def encode_batch(self, texts: list[str]) -> list[list[float]]:
75
+ """批量编码文本"""
76
+ embeddings = self.model.encode(texts, convert_to_numpy=True)
77
+ return [e.tolist() for e in embeddings]
@@ -0,0 +1,42 @@
1
+ """公共 Pipeline 编排层。
2
+
3
+ 提供步骤组合模型,将"如何串步骤、传递上下文、管理共享资源"
4
+ 的能力从业务模块中抽离。
5
+ """
6
+
7
+ from kb_common.pipeline.artifacts import ( # noqa: F401
8
+ ENRICHED_ITEMS,
9
+ NORMALIZED_ITEMS,
10
+ PARSED_ITEMS,
11
+ PRESENTATION,
12
+ RANKED_RESULTS,
13
+ RETRIEVED_CANDIDATES,
14
+ SOURCE_ITEMS,
15
+ STORED_ITEMS,
16
+ VECTOR_RECORDS,
17
+ )
18
+ from kb_common.pipeline.context import PipelineContext # noqa: F401
19
+ from kb_common.pipeline.errors import PipelineError, StepError # noqa: F401
20
+ from kb_common.pipeline.indexing import ( # noqa: F401
21
+ BuildVectorRecordsStep,
22
+ VectorStoreProtocol,
23
+ WriteVectorIndexStep,
24
+ )
25
+ from kb_common.pipeline.retrieval import ( # noqa: F401
26
+ CandidateMergeStep,
27
+ EmbeddingModelProtocol,
28
+ VectorRetrieveStep,
29
+ )
30
+ from kb_common.pipeline.runner import Pipeline # noqa: F401
31
+ from kb_common.pipeline.steps import ( # noqa: F401
32
+ EnrichStep,
33
+ IndexStep,
34
+ NormalizeStep,
35
+ ParseStep,
36
+ PipelineStep,
37
+ PresentStep,
38
+ RankStep,
39
+ RetrieveStep,
40
+ SourceStep,
41
+ StoreStep,
42
+ )
@@ -0,0 +1,18 @@
1
+ """通用 artifact 键名常量。
2
+
3
+ 步骤之间通过 `context.artifacts` 传递命名产物。
4
+ 使用稳定键名可避免步骤间隐式耦合。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ # 通用产物键名
10
+ SOURCE_ITEMS = "source_items"
11
+ PARSED_ITEMS = "parsed_items"
12
+ NORMALIZED_ITEMS = "normalized_items"
13
+ ENRICHED_ITEMS = "enriched_items"
14
+ STORED_ITEMS = "stored_items"
15
+ VECTOR_RECORDS = "vector_records"
16
+ RETRIEVED_CANDIDATES = "retrieved_candidates"
17
+ RANKED_RESULTS = "ranked_results"
18
+ PRESENTATION = "presentation"
@@ -0,0 +1,24 @@
1
+ """Pipeline 共享上下文。
2
+
3
+ 一次 pipeline 运行中所有步骤共享的状态载体。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass, field
9
+ from typing import Any
10
+
11
+
12
+ @dataclass
13
+ class PipelineContext:
14
+ """一次 pipeline 运行的共享上下文。
15
+
16
+ 步骤通过 context 读取配置、共享资源和参数,
17
+ 并通过 artifacts 在步骤之间传递中间产物。
18
+ """
19
+
20
+ config: Any | None = None
21
+ resources: dict[str, Any] = field(default_factory=dict)
22
+ params: dict[str, Any] = field(default_factory=dict)
23
+ artifacts: dict[str, Any] = field(default_factory=dict)
24
+ metrics: dict[str, Any] = field(default_factory=dict)
@@ -0,0 +1,47 @@
1
+ """Pipeline 错误类型。
2
+
3
+ 公共 pipeline 层不依赖领域模块,所有错误类型均为通用诊断信息。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import Optional
9
+
10
+
11
+ class PipelineError(Exception):
12
+ """Pipeline 运行时的基础错误。"""
13
+
14
+ def __init__(
15
+ self,
16
+ message: str,
17
+ *,
18
+ pipeline_name: Optional[str] = None,
19
+ step_name: Optional[str] = None,
20
+ ) -> None:
21
+ super().__init__(message)
22
+ self.pipeline_name = pipeline_name
23
+ self.step_name = step_name
24
+
25
+ def __str__(self) -> str:
26
+ parts = []
27
+ if self.pipeline_name:
28
+ parts.append(f"[pipeline={self.pipeline_name}]")
29
+ if self.step_name:
30
+ parts.append(f"[step={self.step_name}]")
31
+ parts.append(super().__str__())
32
+ return " ".join(parts)
33
+
34
+
35
+ class StepError(PipelineError):
36
+ """步骤执行时发生的错误。"""
37
+
38
+ def __init__(
39
+ self,
40
+ message: str,
41
+ *,
42
+ pipeline_name: Optional[str] = None,
43
+ step_name: Optional[str] = None,
44
+ original_error: Optional[Exception] = None,
45
+ ) -> None:
46
+ super().__init__(message, pipeline_name=pipeline_name, step_name=step_name)
47
+ self.original_error = original_error
@@ -0,0 +1,111 @@
1
+ """通用向量索引步骤。
2
+
3
+ 公共 pipeline 层不依赖领域模块,只定义索引步骤协议。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import Any, Callable, Protocol
9
+
10
+ from kb_common.pipeline.context import PipelineContext
11
+ from kb_common.pipeline.steps import IndexStep
12
+
13
+
14
+ class VectorStoreProtocol(Protocol):
15
+ """向量存储协议 — 公共层不依赖具体 VectorStore 实现。"""
16
+
17
+ def upsert_records(
18
+ self, records: list[dict], batch_size: int = 5000
19
+ ) -> dict[str, Any]:
20
+ """批量写入向量记录,返回 {"created": int, "updated": int}。"""
21
+ ...
22
+
23
+
24
+ class BuildVectorRecordsStep(IndexStep):
25
+ """将领域对象构建为 VectorRecord 列表。
26
+
27
+ 领域对象到 VectorRecord 的映射由外部 mapper 函数提供,
28
+ 本步骤只负责调用 mapper 并将结果写入 context.artifacts[VECTOR_RECORDS]。
29
+ """
30
+
31
+ def __init__(
32
+ self,
33
+ mapper: Callable[[Any], dict],
34
+ source_key: str = "parsed_items",
35
+ target_key: str = "vector_records",
36
+ ) -> None:
37
+ """
38
+ Args:
39
+ mapper: 领域对象 -> VectorRecord 的映射函数
40
+ source_key: context.artifacts 中源数据键名
41
+ target_key: context.artifacts 中输出键名
42
+ """
43
+ self._mapper = mapper
44
+ self._source_key = source_key
45
+ self._target_key = target_key
46
+
47
+ @property
48
+ def name(self) -> str:
49
+ return "build_vector_records"
50
+
51
+ def run(self, context: PipelineContext) -> PipelineContext:
52
+ source_items = context.artifacts.get(self._source_key, [])
53
+ vector_records = [self._mapper(item) for item in source_items]
54
+ context.artifacts[self._target_key] = vector_records
55
+ return context
56
+
57
+
58
+ class WriteVectorIndexStep(IndexStep):
59
+ """将 vector_records 写入向量索引。
60
+
61
+ 从 context.artifacts[VECTOR_RECORDS] 读取记录,
62
+ 从 context.resources 或 context.params 获取 VectorStore,
63
+ 调用 upsert_records() 写入,并将统计写回 context.artifacts["index_stats"]。
64
+ """
65
+
66
+ def __init__(
67
+ self,
68
+ store_key: str = "vector_store",
69
+ source_key: str = "vector_records",
70
+ target_key: str = "index_stats",
71
+ ) -> None:
72
+ """
73
+ Args:
74
+ store_key: context.resources 中 VectorStore 实例的键名
75
+ source_key: context.artifacts 中 vector_records 键名
76
+ target_key: context.artifacts 中输出统计键名
77
+ """
78
+ self._store_key = store_key
79
+ self._source_key = source_key
80
+ self._target_key = target_key
81
+
82
+ @property
83
+ def name(self) -> str:
84
+ return "write_vector_index"
85
+
86
+ def run(self, context: PipelineContext) -> PipelineContext:
87
+ vector_store: VectorStoreProtocol | None = context.resources.get(
88
+ self._store_key
89
+ )
90
+ if vector_store is None:
91
+ raise RuntimeError(
92
+ f"VectorStore not found in " f"context.resources[{self._store_key!r}]"
93
+ )
94
+
95
+ vector_records = context.artifacts.get(self._source_key, [])
96
+ if not vector_records:
97
+ # 空记录集:返回 created=0, updated=0
98
+ context.artifacts[self._target_key] = {
99
+ "created": 0,
100
+ "updated": 0,
101
+ "total": 0,
102
+ }
103
+ return context
104
+
105
+ result = vector_store.upsert_records(vector_records)
106
+ context.artifacts[self._target_key] = {
107
+ "created": result["created"],
108
+ "updated": result["updated"],
109
+ "total": len(vector_records),
110
+ }
111
+ return context
@@ -0,0 +1,122 @@
1
+ """公共检索步骤骨架。
2
+
3
+ 公共 pipeline 层不包含排序、评分、过滤等领域规则。
4
+ 只提供向量检索和候选合并的通用骨架步骤。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import Callable, Optional, Protocol
10
+
11
+ from kb_common.pipeline.context import PipelineContext
12
+ from kb_common.pipeline.steps import RetrieveStep
13
+
14
+
15
+ class EmbeddingModelProtocol(Protocol):
16
+ """嵌入模型协议。"""
17
+
18
+ def encode(self, text: str) -> list[float]:
19
+ """编码文本为向量。"""
20
+ ...
21
+
22
+
23
+ class VectorRetrieveStep(RetrieveStep):
24
+ """通用向量检索步骤。
25
+
26
+ 将查询文本编码为向量,搜索向量索引,将结果写入 artifacts。
27
+ 不包含领域排序或过滤规则。
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ query_builder: Callable[[PipelineContext], str],
33
+ embedding_key: str = "embedding_model",
34
+ store_key: str = "vector_store",
35
+ top_k_key: str = "top_k",
36
+ source_key: str = "retrieved_candidates",
37
+ default_top_k: int = 50,
38
+ where_builder: Optional[Callable[[PipelineContext], Optional[dict]]] = None,
39
+ ) -> None:
40
+ self._query_builder = query_builder
41
+ self._embedding_key = embedding_key
42
+ self._store_key = store_key
43
+ self._top_k_key = top_k_key
44
+ self._source_key = source_key
45
+ self._default_top_k = default_top_k
46
+ self._where_builder = where_builder
47
+
48
+ @property
49
+ def name(self) -> str:
50
+ return "vector_retrieve"
51
+
52
+ def run(self, context: PipelineContext) -> PipelineContext:
53
+ query_text = self._query_builder(context)
54
+ if not query_text:
55
+ context.artifacts[self._source_key] = []
56
+ return context
57
+
58
+ model: EmbeddingModelProtocol | None = context.resources.get(
59
+ self._embedding_key
60
+ )
61
+ if model is None:
62
+ raise RuntimeError(
63
+ f"EmbeddingModel not found in "
64
+ f"context.resources[{self._embedding_key!r}]"
65
+ )
66
+
67
+ store = context.resources.get(self._store_key)
68
+ if store is None:
69
+ raise RuntimeError(
70
+ f"VectorStore not found in " f"context.resources[{self._store_key!r}]"
71
+ )
72
+
73
+ top_k: int = context.params.get(self._top_k_key, self._default_top_k)
74
+ where: Optional[dict] = None
75
+ if self._where_builder is not None:
76
+ where = self._where_builder(context)
77
+
78
+ query_embedding = model.encode(query_text)
79
+ results = store.search(query_embedding, top_k=top_k, where=where)
80
+
81
+ context.artifacts[self._source_key] = results
82
+ return context
83
+
84
+
85
+ class CandidateMergeStep(RetrieveStep):
86
+ """候选去重合并步骤。
87
+
88
+ 将多个来源的候选列表合并,按稳定键去重。
89
+ 不包含领域排序规则。
90
+ """
91
+
92
+ def __init__(
93
+ self,
94
+ primary_key: str = "id",
95
+ fallback_metadata_key: str = "pdf_path",
96
+ source_keys: Optional[list[str]] = None,
97
+ target_key: str = "merged_candidates",
98
+ ) -> None:
99
+ self._primary_key = primary_key
100
+ self._fallback_metadata_key = fallback_metadata_key
101
+ self._source_keys = source_keys or []
102
+ self._target_key = target_key
103
+
104
+ @property
105
+ def name(self) -> str:
106
+ return "candidate_merge"
107
+
108
+ def run(self, context: PipelineContext) -> PipelineContext:
109
+ merged = []
110
+ seen_keys: set[str] = set()
111
+ for key_name in self._source_keys:
112
+ candidates = context.artifacts.get(key_name, [])
113
+ for item in candidates:
114
+ key = item.get(self._primary_key) or (
115
+ (item.get("metadata") or {}).get(self._fallback_metadata_key)
116
+ )
117
+ if key in seen_keys:
118
+ continue
119
+ seen_keys.add(key)
120
+ merged.append(item)
121
+ context.artifacts[self._target_key] = merged
122
+ return context
@@ -0,0 +1,68 @@
1
+ """Pipeline 执行器。
2
+
3
+ 顺序执行步骤列表,记录运行指标。
4
+ 第一阶段只支持顺序执行,不引入 DAG、并发或重试。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import logging
10
+ import time
11
+ from typing import Optional
12
+
13
+ from kb_common.pipeline.context import PipelineContext
14
+ from kb_common.pipeline.errors import StepError
15
+ from kb_common.pipeline.steps import PipelineStep
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class Pipeline:
21
+ """顺序执行步骤的组合器。
22
+
23
+ 按注册顺序依次调用每个步骤的 `run` 方法,
24
+ 步骤抛出的异常会被包装为 `StepError` 并附加 pipeline/step 名称。
25
+ """
26
+
27
+ def __init__(self, name: str, steps: Optional[list[PipelineStep]] = None) -> None:
28
+ self.name = name
29
+ self.steps: list[PipelineStep] = steps or []
30
+
31
+ def run(self, context: PipelineContext) -> PipelineContext:
32
+ """按顺序执行所有步骤,返回最终上下文。"""
33
+ context.metrics["pipeline_name"] = self.name
34
+ step_times: list[dict[str, object]] = []
35
+
36
+ for step in self.steps:
37
+ started = time.monotonic()
38
+ try:
39
+ context = step.run(context)
40
+ except Exception as exc:
41
+ elapsed = time.monotonic() - started
42
+ step_times.append({"name": step.name, "elapsed": elapsed})
43
+ context.metrics["step_times"] = step_times
44
+ context.metrics["failed_step"] = step.name
45
+ raise StepError(
46
+ str(exc),
47
+ pipeline_name=self.name,
48
+ step_name=step.name,
49
+ original_error=exc,
50
+ ) from exc
51
+ elapsed = time.monotonic() - started
52
+ step_times.append({"name": step.name, "elapsed": elapsed})
53
+ logger.debug(
54
+ "pipeline=%s step=%s elapsed=%.3fs",
55
+ self.name,
56
+ step.name,
57
+ elapsed,
58
+ )
59
+
60
+ context.metrics["step_times"] = step_times
61
+ return context
62
+
63
+ def __repr__(self) -> str:
64
+ step_names = [s.name for s in self.steps]
65
+ return f"Pipeline(name={self.name!r}, steps={step_names})"
66
+
67
+ def __len__(self) -> int:
68
+ return len(self.steps)
@@ -0,0 +1,104 @@
1
+ """Pipeline 步骤协议与基础步骤类型。
2
+
3
+ 公共层只定义步骤类别和执行约定,具体实现留给领域项目。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from abc import ABC, abstractmethod
9
+
10
+ from kb_common.pipeline.context import PipelineContext
11
+
12
+
13
+ class PipelineStep(ABC):
14
+ """领域无关的步骤协议。
15
+
16
+ 每个步骤实现 `run` 方法,接收并返回 `PipelineContext`。
17
+ 子类必须提供 `name` 属性。
18
+ """
19
+
20
+ @property
21
+ @abstractmethod
22
+ def name(self) -> str:
23
+ """步骤名称,用于日志和错误诊断。"""
24
+ ...
25
+
26
+ @abstractmethod
27
+ def run(self, context: PipelineContext) -> PipelineContext:
28
+ """执行步骤逻辑,返回更新后的上下文。"""
29
+ ...
30
+
31
+ def __repr__(self) -> str:
32
+ return f"{type(self).__name__}(name={self.name!r})"
33
+
34
+
35
+ class SourceStep(PipelineStep):
36
+ """读取输入源。"""
37
+
38
+ @property
39
+ def name(self) -> str:
40
+ return "source"
41
+
42
+
43
+ class ParseStep(PipelineStep):
44
+ """解析为领域对象。"""
45
+
46
+ @property
47
+ def name(self) -> str:
48
+ return "parse"
49
+
50
+
51
+ class NormalizeStep(PipelineStep):
52
+ """字段清洗和归一化。"""
53
+
54
+ @property
55
+ def name(self) -> str:
56
+ return "normalize"
57
+
58
+
59
+ class EnrichStep(PipelineStep):
60
+ """增强领域对象。"""
61
+
62
+ @property
63
+ def name(self) -> str:
64
+ return "enrich"
65
+
66
+
67
+ class StoreStep(PipelineStep):
68
+ """持久化领域对象。"""
69
+
70
+ @property
71
+ def name(self) -> str:
72
+ return "store"
73
+
74
+
75
+ class IndexStep(PipelineStep):
76
+ """生成并写入向量记录。"""
77
+
78
+ @property
79
+ def name(self) -> str:
80
+ return "index"
81
+
82
+
83
+ class RetrieveStep(PipelineStep):
84
+ """召回候选。"""
85
+
86
+ @property
87
+ def name(self) -> str:
88
+ return "retrieve"
89
+
90
+
91
+ class RankStep(PipelineStep):
92
+ """领域排序。"""
93
+
94
+ @property
95
+ def name(self) -> str:
96
+ return "rank"
97
+
98
+
99
+ class PresentStep(PipelineStep):
100
+ """输出适配。"""
101
+
102
+ @property
103
+ def name(self) -> str:
104
+ return "present"
@@ -0,0 +1,201 @@
1
+ """领域无关的 ChromaDB 向量索引封装"""
2
+
3
+ import hashlib
4
+ from pathlib import Path
5
+ from typing import Optional, TypedDict
6
+
7
+ import chromadb
8
+ from chromadb.config import Settings
9
+
10
+
11
+ class VectorRecord(TypedDict):
12
+ """待写入向量索引的通用记录"""
13
+
14
+ record_key: str
15
+ embedding: list[float]
16
+ metadata: dict
17
+ document: str
18
+
19
+
20
+ class VectorStore:
21
+ """ChromaDB 向量索引封装
22
+
23
+ 该类只关心通用记录键、向量、元数据和索引文本,不包含 PDF 或项目语义。
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ persist_dir: str = "/mnt/data/db/",
29
+ collection_name: str = "pdf_documents",
30
+ ):
31
+ """
32
+ Args:
33
+ persist_dir: 数据持久化目录
34
+ collection_name: 集合名称
35
+ """
36
+ self._persist_dir = Path(persist_dir)
37
+ self._persist_dir.mkdir(parents=True, exist_ok=True)
38
+
39
+ self._client = chromadb.PersistentClient(
40
+ path=str(self._persist_dir),
41
+ settings=Settings(anonymized_telemetry=False),
42
+ )
43
+ self._collection = self._client.get_or_create_collection(
44
+ name=collection_name,
45
+ metadata={"hnsw:space": "cosine"},
46
+ )
47
+
48
+ def _generate_id(self, record_key: str) -> str:
49
+ """根据业务记录键生成稳定索引 ID"""
50
+ return hashlib.md5(record_key.encode()).hexdigest()
51
+
52
+ def upsert_record(
53
+ self,
54
+ record_key: str,
55
+ embedding: list[float],
56
+ metadata: dict,
57
+ document: str,
58
+ ) -> str:
59
+ """更新或插入一条通用向量记录"""
60
+ record_id = self._generate_id(record_key)
61
+
62
+ before = self._collection.count()
63
+ self._collection.upsert(
64
+ ids=[record_id],
65
+ embeddings=[embedding],
66
+ metadatas=[metadata],
67
+ documents=[document],
68
+ )
69
+ after = self._collection.count()
70
+
71
+ return "created" if after > before else "updated"
72
+
73
+ def upsert_records(
74
+ self,
75
+ records: list[VectorRecord],
76
+ batch_size: int = 5000,
77
+ ) -> dict:
78
+ """批量更新或插入通用向量记录,自动分批避免超出 ChromaDB 限制"""
79
+ before = self._collection.count()
80
+ for start in range(0, len(records), batch_size):
81
+ batch = records[start : start + batch_size]
82
+ ids = [self._generate_id(item["record_key"]) for item in batch]
83
+ self._collection.upsert(
84
+ ids=ids,
85
+ embeddings=[item["embedding"] for item in batch],
86
+ metadatas=[item["metadata"] for item in batch],
87
+ documents=[item["document"] for item in batch],
88
+ )
89
+ after = self._collection.count()
90
+ created = after - before
91
+ return {"created": created, "updated": len(records) - created}
92
+
93
+ def search(
94
+ self,
95
+ query_embedding: list[float],
96
+ top_k: int = 5,
97
+ where: Optional[dict] = None,
98
+ ) -> list[dict]:
99
+ """向量相似度搜索"""
100
+ kwargs = {
101
+ "query_embeddings": [query_embedding],
102
+ "n_results": top_k,
103
+ "include": ["metadatas", "documents", "distances"],
104
+ }
105
+ if where:
106
+ kwargs["where"] = where
107
+ results = self._collection.query(**kwargs)
108
+
109
+ search_results = []
110
+ for i in range(len(results["ids"][0])):
111
+ search_results.append(
112
+ {
113
+ "id": results["ids"][0][i],
114
+ "metadata": results["metadatas"][0][i],
115
+ "document": results["documents"][0][i],
116
+ "distance": results["distances"][0][i],
117
+ }
118
+ )
119
+
120
+ return search_results
121
+
122
+ def get(self, where: Optional[dict] = None, limit: int = 20) -> list[dict]:
123
+ """按元数据获取记录"""
124
+ kwargs = {"include": ["metadatas", "documents"]}
125
+ if where:
126
+ kwargs["where"] = where
127
+ if limit:
128
+ kwargs["limit"] = limit
129
+ results = self._collection.get(**kwargs)
130
+
131
+ records = []
132
+ for i, doc_id in enumerate(results["ids"]):
133
+ records.append(
134
+ {
135
+ "id": doc_id,
136
+ "metadata": results["metadatas"][i],
137
+ "document": results["documents"][i],
138
+ "distance": 1.0,
139
+ }
140
+ )
141
+ return records
142
+
143
+ def get_all_metadatas(self) -> list[dict]:
144
+ """获取所有文档的元数据"""
145
+ results = self._collection.get(include=["metadatas"])
146
+ return results["metadatas"]
147
+
148
+ def clear(self) -> None:
149
+ """清空集合"""
150
+ all_ids = self._collection.get()["ids"]
151
+ if all_ids:
152
+ self._collection.delete(ids=all_ids)
153
+
154
+ def delete_by_key(self, record_key: str) -> bool:
155
+ """根据业务记录键删除记录"""
156
+ record_id = self._generate_id(record_key)
157
+ existing = self._collection.get(ids=[record_id])
158
+ if existing["ids"]:
159
+ self._collection.delete(ids=[record_id])
160
+ return True
161
+ return False
162
+
163
+ def count(self) -> int:
164
+ """返回文档数量"""
165
+ return self._collection.count()
166
+
167
+ def upsert(
168
+ self,
169
+ pdf_path: str,
170
+ doc_type: str,
171
+ embedding: list[float],
172
+ metadata: dict,
173
+ document: str,
174
+ ) -> str:
175
+ """兼容旧接口:使用 pdf_path 作为通用 record_key"""
176
+ return self.upsert_record(
177
+ record_key=pdf_path,
178
+ embedding=embedding,
179
+ metadata=metadata,
180
+ document=document,
181
+ )
182
+
183
+ def upsert_batch(self, items: list[dict], batch_size: int = 5000) -> dict:
184
+ """兼容旧接口:接受 pdf_path/text 或 record_key/document 字段"""
185
+ records = [
186
+ VectorRecord(
187
+ record_key=item.get("record_key", item.get("pdf_path")),
188
+ embedding=item["embedding"],
189
+ metadata=item["metadata"],
190
+ document=item.get("document", item.get("text", "")),
191
+ )
192
+ for item in items
193
+ ]
194
+ return self.upsert_records(records, batch_size=batch_size)
195
+
196
+ def delete_by_path(self, pdf_path: str) -> bool:
197
+ """兼容旧接口:根据 PDF 路径删除记录"""
198
+ return self.delete_by_key(pdf_path)
199
+
200
+
201
+ VectorIndex = VectorStore
@@ -0,0 +1,28 @@
1
+ Metadata-Version: 2.4
2
+ Name: kb-common
3
+ Version: 0.1.0
4
+ Summary: Common pipeline
5
+ Requires-Python: >=3.12
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: chromadb>=0.4.0
8
+ Requires-Dist: huggingface-hub
9
+ Requires-Dist: sentence-transformers>=5.3.0
10
+ Provides-Extra: dev
11
+ Requires-Dist: pytest>=7.0; extra == "dev"
12
+ Requires-Dist: ruff; extra == "dev"
13
+ Requires-Dist: build; extra == "dev"
14
+ Requires-Dist: twine; extra == "dev"
15
+
16
+ # kb-common
17
+
18
+ Common infrastructure
19
+
20
+ The package contains:
21
+
22
+ - sequential pipeline orchestration primitives
23
+ - generic retrieval and indexing steps
24
+ - local `EmbeddingModel`
25
+ - ChromaDB-backed `VectorStore`
26
+
27
+ It intentionally does not contain project-search or document-search business
28
+ rules.
@@ -0,0 +1,15 @@
1
+ kb_common/__init__.py,sha256=titdgISQX02egzFSJr-l4ASywv0daHSuuYG8isncP_o,1016
2
+ kb_common/embeddings.py,sha256=xdss2YmStKS3bw3Y_nmh6whw-CUqTGJpCIO3IQ18MjI,2622
3
+ kb_common/vector_store.py,sha256=7pVieG5MiwqnLduJH0kB90MAd4PvWQFAUT3-_QVo6ZU,6370
4
+ kb_common/pipeline/__init__.py,sha256=ARZb4q6MFfuBOxbrYDfx9KZ6Ve-WPdBh_BMBhXm3H5w,1098
5
+ kb_common/pipeline/artifacts.py,sha256=C6J019ODhMfQjFt4PUo_-2awCm5nQBXNENKU8lwXpp0,517
6
+ kb_common/pipeline/context.py,sha256=VJdNdxBJdvaGjpnelVOifp14pkUDgjjJm8l-I7Azy5Y,687
7
+ kb_common/pipeline/errors.py,sha256=7k9ITuGVsW0JmYLZgQIL1jaIhFb2XKShv51t7IUcrNM,1266
8
+ kb_common/pipeline/indexing.py,sha256=iWX7xwLO8ADkFpbWm6k7uTQW4STD4MbfRknkfDedjdE,3631
9
+ kb_common/pipeline/retrieval.py,sha256=0vM9d_UUhBGlQgoTQYjK_0ZTlves8m2PLvOUk4uFbug,3952
10
+ kb_common/pipeline/runner.py,sha256=udoW-45dDWmQOdKsG7OH4k9vY46_4mS_7KcbFuiUNyU,2264
11
+ kb_common/pipeline/steps.py,sha256=6LNPbJpAQ4GDPafA8Jx7X3eVLP2wwHnwPPblw7Kes3Q,2033
12
+ kb_common-0.1.0.dist-info/METADATA,sha256=5ROTmcHny41Q59pVKdB-PXnvymBfO-qLgPqN-y6NagM,709
13
+ kb_common-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
14
+ kb_common-0.1.0.dist-info/top_level.txt,sha256=hKJJTpJw0Z_r-lsnhmR8a-fjkcz9RtjR1OYPbF8GN9I,10
15
+ kb_common-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ kb_common