蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行个人知识库哈希增量更新、删除隔离、PDF 1 基引用与 messages 流式过滤实验

PYTHONWindows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。explore-project-knowledge-qa.py
explore-project-knowledge-qa.py453 行
"""Offline runtime verification lab for LangChain Ch 34: Personal Knowledge Base QA."""
import hashlib
import json
import math
import platform
import re
import tempfile
import warnings
from pathlib import Path
from typing import Any, Iterator

warnings.filterwarnings("ignore", category=DeprecationWarning)

from langchain.agents import create_agent
from langchain.tools import tool
from langchain_community.document_loaders import TextLoader
from langchain_core.documents import Document
from langchain_core.embeddings import Embeddings
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.messages import AIMessage, AIMessageChunk, BaseMessage
from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, ChatResult
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_text_splitters import RecursiveCharacterTextSplitter


class OfflineEmbeddings(Embeddings):
    def __init__(self, dim: int = 128):
        self.dim = dim

    def _embed(self, text: str) -> list[float]:
        vec = [0.0] * self.dim
        tokens = re.findall(r"[a-z0-9_]+|[\u4e00-\u9fff]", text.lower())
        feats = list(tokens) + [tokens[i] + tokens[i + 1] for i in range(len(tokens) - 1)]
        for f in feats:
            h = int(hashlib.md5(f.encode("utf-8")).hexdigest()[:8], 16)
            vec[h % self.dim] += 1.0
        mag = math.sqrt(sum(v * v for v in vec)) or 1.0
        return [v / mag for v in vec]

    def embed_documents(self, texts: list[str]) -> list[list[float]]:
        return [self._embed(t) for t in texts]

    def embed_query(self, text: str) -> list[float]:
        return self._embed(text)


def format_source(doc: Document) -> str:
    meta = doc.metadata
    name = meta.get("source", "未知文档")
    parts = [name]
    if meta.get("page") is not None:
        parts.append(f"第 {meta['page'] + 1} 页")
    if meta.get("chunk_index") is not None:
        parts.append(f"片段 {meta['chunk_index'] + 1}")
    return " / ".join(parts)


class OfflineKnowledgeBase:
    """Offline hash-versioned KnowledgeBase mirroring Ch 34 architecture."""

    def __init__(self, chunk_size: int = 500, chunk_overlap: int = 80):
        self.embeddings = OfflineEmbeddings(dim=128)
        self.splitter = RecursiveCharacterTextSplitter(
            chunk_size=chunk_size,
            chunk_overlap=chunk_overlap,
            separators=["\n\n", "\n", "。", "!", "?", ";", ",", " ", ""],
            add_start_index=True,
        )
        self.vector_store = InMemoryVectorStore(embedding=self.embeddings)
        self._ids_by_source: dict[str, list[str]] = {}

    def _source_key(self, path: Path) -> str:
        return hashlib.sha256(str(path.resolve()).encode("utf-8")).hexdigest()

    def add_file(self, file_path: str) -> int:
        path = Path(file_path).resolve()
        if not path.is_file():
            raise FileNotFoundError(str(path))
        if path.suffix.lower() not in {".txt", ".md"}:
            raise ValueError(f"不支持的文件格式:{path.suffix.lower()}")

        file_hash = hashlib.sha256(path.read_bytes()).hexdigest()
        source_key = self._source_key(path)
        old_ids = self._ids_by_source.get(source_key, [])
        prefix = f"{source_key}-{file_hash}-"
        if old_ids and all(i.startswith(prefix) for i in old_ids):
            return 0

        docs = TextLoader(str(path), encoding="utf-8").load()
        for d in docs:
            d.metadata.update(
                {
                    "source": path.name,
                    "source_path": str(path),
                    "source_key": source_key,
                    "file_hash": file_hash,
                }
            )
        chunks = [d for d in self.splitter.split_documents(docs) if d.page_content.strip()]
        if not chunks:
            raise ValueError(f"没有提取到可索引的文字:{path.name}")

        new_ids = [f"{source_key}-{file_hash}-{i}" for i in range(len(chunks))]
        for i, d in enumerate(chunks):
            d.metadata["chunk_index"] = i

        self.vector_store.add_documents(chunks, ids=new_ids)
        obsolete = list(set(old_ids) - set(new_ids))
        if obsolete:
            self.vector_store.delete(ids=obsolete)
        self._ids_by_source[source_key] = new_ids
        return len(chunks)

    def add_text(self, text: str, source: str = "manual") -> int:
        if not text.strip():
            raise ValueError("不能添加空文本")
        source_key = "manual-" + hashlib.sha256(source.encode("utf-8")).hexdigest()
        content_hash = hashlib.sha256(text.encode("utf-8")).hexdigest()
        old_ids = self._ids_by_source.get(source_key, [])
        prefix = f"{source_key}-{content_hash}-"
        if old_ids and all(i.startswith(prefix) for i in old_ids):
            return 0

        chunks = self.splitter.create_documents(
            [text],
            metadatas=[{"source": source, "source_key": source_key, "file_hash": content_hash}],
        )
        new_ids = [f"{source_key}-{content_hash}-{i}" for i in range(len(chunks))]
        for i, d in enumerate(chunks):
            d.metadata["chunk_index"] = i

        self.vector_store.add_documents(chunks, ids=new_ids)
        obsolete = list(set(old_ids) - set(new_ids))
        if obsolete:
            self.vector_store.delete(ids=obsolete)
        self._ids_by_source[source_key] = new_ids
        return len(chunks)

    def remove_file(self, file_path: str) -> int:
        source_key = self._source_key(Path(file_path))
        ids = self._ids_by_source.pop(source_key, [])
        if ids:
            self.vector_store.delete(ids=ids)
        return len(ids)

    def search(self, query: str, k: int = 3, min_score: float = 0.0) -> list[Document]:
        scored = self.vector_store.similarity_search_with_score(query, k=k)
        return [d for d, s in scored if s >= min_score]

    def get_retriever(self, k: int = 3):
        return self.vector_store.as_retriever(search_kwargs={"k": k})


class StreamingOfflineKbModel(BaseChatModel):
    """Deterministic offline model supporting both invoke() and token-chunk stream()."""

    counter: int = 0

    @property
    def _llm_type(self) -> str:
        return "offline-streaming-kb-model"

    def bind_tools(self, tools: Any, **kwargs: Any) -> "StreamingOfflineKbModel":
        return self

    def _build_reply(self, messages: list[BaseMessage]) -> tuple[bool, str, str]:
        last = messages[-1]
        if last.type == "tool":
            txt = str(last.content)
            if "没有检索到相关资料" in txt:
                return False, "知识库中缺乏相关依据,无法回答该问题。", ""
            first = txt.split("\n\n")[0]
            body = ""
            for line in first.splitlines():
                if line.startswith("内容:"):
                    body = line[len("内容:"):]
            return False, f"根据知识库检索:{body} [来源1]", ""
        return True, "", str(last.content)

    def _generate(self, messages: list[BaseMessage], stop: Any = None, **kwargs: Any) -> ChatResult:
        self.counter += 1
        need_tool, reply, query = self._build_reply(messages)
        if need_tool:
            ai = AIMessage(
                content="",
                tool_calls=[
                    {
                        "name": "search_knowledge",
                        "args": {"query": query},
                        "id": f"call_kb_{self.counter}",
                        "type": "tool_call",
                    }
                ],
            )
            return ChatResult(generations=[ChatGeneration(message=ai)])
        return ChatResult(generations=[ChatGeneration(message=AIMessage(content=reply))])

    def _stream(self, messages: list[BaseMessage], stop: Any = None, **kwargs: Any) -> Iterator[ChatGenerationChunk]:
        self.counter += 1
        need_tool, reply, query = self._build_reply(messages)
        if need_tool:
            yield ChatGenerationChunk(
                message=AIMessageChunk(
                    content="",
                    tool_call_chunks=[
                        {
                            "name": "search_knowledge",
                            "args": json.dumps({"query": query}, ensure_ascii=False),
                            "id": f"call_stream_{self.counter}",
                            "index": 0,
                        }
                    ],
                )
            )
            return
        step = 6
        for i in range(0, len(reply), step):
            yield ChatGenerationChunk(message=AIMessageChunk(content=reply[i : i + step]))


def case_knowledge_base_incremental_update_and_delete() -> dict:
    kb = OfflineKnowledgeBase(chunk_size=80, chunk_overlap=10)
    with tempfile.TemporaryDirectory() as tmp:
        docs_dir = Path(tmp) / "docs"
        docs_dir.mkdir()
        md_file = docs_dir / "python.md"
        txt_file = docs_dir / "notes.txt"
        bad_file = docs_dir / "archive.docx"

        md_file.write_text("# Python 笔记\n\n函数使用 def 定义,用于封装重复逻辑。\n", encoding="utf-8")
        txt_file.write_text("列表用于保存有序元素,字典用于键值对存储。\n", encoding="utf-8")
        bad_file.write_bytes(b"PK\x03\x04")

        first_md = kb.add_file(str(md_file))
        first_txt = kb.add_file(str(txt_file))
        skip_md = kb.add_file(str(md_file))
        count_before_edit = len(kb.vector_store.store)

        # Modify file -> adds new hash version (2 chunks > chunk_size=80) and deletes old chunk IDs
        md_file.write_text(
            "# Python 笔记 V2\n\n"
            "装饰器可以在不修改原函数主体的情况下扩展函数行为,常用于日志记录、权限检查与缓存封装。\n\n"
            "生成器通过 yield 按需产出数据,适合处理大文件与流式序列,能够显著降低内存占用。\n",
            encoding="utf-8",
        )
        updated_md = kb.add_file(str(md_file))
        after_edit_texts = [v["text"] for v in kb.vector_store.store.values()]

        removed_txt = kb.remove_file(str(txt_file))
        txt_still_on_disk = txt_file.is_file()

        try:
            kb.add_file(str(bad_file))
            unsupported_rejected = False
        except ValueError:
            unsupported_rejected = True

        try:
            kb.add_file(str(docs_dir / "missing.txt"))
            missing_rejected = False
        except FileNotFoundError:
            missing_rejected = True

    actual = {
        "first_import_chunks": [first_md, first_txt],
        "unchanged_reimport_skipped": skip_md == 0,
        "count_before_edit": count_before_edit,
        "updated_md_chunks": updated_md,
        "old_md_version_removed": not any("函数使用 def 定义" in t for t in after_edit_texts),
        "new_md_version_indexed": any("装饰器可以在不修改原函数" in t for t in after_edit_texts),
        "removed_txt_chunks": removed_txt,
        "disk_file_preserved_after_remove": txt_still_on_disk,
        "unsupported_extension_rejected": unsupported_rejected,
        "missing_file_rejected": missing_rejected,
    }
    expected = {
        "first_import_chunks": [1, 1],
        "unchanged_reimport_skipped": True,
        "count_before_edit": 2,
        "updated_md_chunks": 2,
        "old_md_version_removed": True,
        "new_md_version_indexed": True,
        "removed_txt_chunks": 1,
        "disk_file_preserved_after_remove": True,
        "unsupported_extension_rejected": True,
        "missing_file_rejected": True,
    }
    return {
        "name": "knowledge_base_incremental_update_and_delete",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_format_source_citation_and_truncation() -> dict:
    md_doc = Document(
        page_content="Python 装饰器说明",
        metadata={"source": "python.md", "chunk_index": 2},
    )
    pdf_doc = Document(
        page_content="A" * 2400,
        metadata={"source": "manual.pdf", "page": 11, "chunk_index": 2},
    )
    truncated = pdf_doc.page_content[:1500]
    actual = {
        "md_citation": format_source(md_doc),
        "pdf_citation": format_source(pdf_doc),
        "truncated_len": len(truncated),
    }
    expected = {
        "md_citation": "python.md / 片段 3",
        "pdf_citation": "manual.pdf / 第 12 页 / 片段 3",
        "truncated_len": 1500,
    }
    return {
        "name": "format_source_citation_and_truncation",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_rag_agent_invoke_and_unanswerable_guard() -> dict:
    kb = OfflineKnowledgeBase()
    kb.add_text("Python 基础学习内容包括变量、数据类型、条件判断、循环、函数和模块。", source="Python 基础笔记")
    kb.add_text("Python 学习路线可以从基础语法开始,再学习数据结构、Web 开发或数据分析。", source="Python 学习路线")
    kb.add_text("函数用于封装重复代码。Python 通过 def 定义函数,可以接收参数并返回结果。", source="Python 函数笔记")
    dup_skip = kb.add_text("函数用于封装重复代码。Python 通过 def 定义函数,可以接收参数并返回结果。", source="Python 函数笔记")

    @tool
    def search_knowledge(query: str) -> str:
        """检索个人知识库并返回内容与来源。"""
        docs = kb.search(query, k=3, min_score=0.25)
        if not docs:
            return "没有检索到相关资料"
        return "\n\n".join(
            f"[来源{i}] {format_source(d)}\n内容:{d.page_content[:1500]}"
            for i, d in enumerate(docs, 1)
        )

    agent = create_agent(
        model=StreamingOfflineKbModel(),
        tools=[search_knowledge],
        system_prompt="你是个人知识库助手,依据检索结果回答并标注来源。",
    )
    res_fn = agent.invoke({"messages": [{"role": "user", "content": "Python 函数有什么作用?"}]})
    res_salary = agent.invoke({"messages": [{"role": "user", "content": "我上个月的工资是多少?"}]})
    fn_tools = [m for m in res_fn["messages"] if m.type == "tool"]

    actual = {
        "duplicate_add_text_skipped": dup_skip == 0,
        "fn_tool_invoked": len(fn_tools) == 1,
        "fn_answer_grounded": "def 定义函数" in str(res_fn["messages"][-1].content)
        and "[来源1]" in str(res_fn["messages"][-1].content),
        "unanswerable_refused": "缺乏相关依据" in str(res_salary["messages"][-1].content),
    }
    expected = {
        "duplicate_add_text_skipped": True,
        "fn_tool_invoked": True,
        "fn_answer_grounded": True,
        "unanswerable_refused": True,
    }
    return {
        "name": "rag_agent_invoke_and_unanswerable_guard",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_stream_mode_messages_filtering() -> dict:
    kb = OfflineKnowledgeBase()
    kb.add_text("Python 学习路线可以从基础语法开始,再学习数据结构、Web 开发或数据分析。", source="Python 学习路线")

    @tool
    def search_knowledge(query: str) -> str:
        """检索个人知识库并返回内容与来源。"""
        docs = kb.search(query, k=2, min_score=0.1)
        if not docs:
            return "没有检索到相关资料"
        return "\n\n".join(
            f"[来源{i}] {format_source(d)}\n内容:{d.page_content[:1500]}"
            for i, d in enumerate(docs, 1)
        )

    agent = create_agent(
        model=StreamingOfflineKbModel(),
        tools=[search_knowledge],
        system_prompt="你是个人知识库助手。",
    )

    visible_chunks: list[str] = []
    skipped_tool_chunks = 0
    skipped_non_model = 0
    for chunk, metadata in agent.stream(
        {"messages": [{"role": "user", "content": "如何规划 Python 学习路线?"}]},
        stream_mode="messages",
    ):
        if metadata.get("langgraph_node") != "model":
            skipped_non_model += 1
            continue
        if getattr(chunk, "tool_call_chunks", None):
            skipped_tool_chunks += 1
            continue
        if isinstance(chunk.content, str) and chunk.content:
            visible_chunks.append(chunk.content)

    assembled = "".join(visible_chunks)
    actual = {
        "visible_chunk_count_gt_1": len(visible_chunks) > 1,
        "skipped_tool_call_chunks": skipped_tool_chunks >= 1,
        "skipped_tool_node_messages": skipped_non_model >= 1,
        "assembled_contains_roadmap": "基础语法开始" in assembled and "[来源1]" in assembled,
        "no_raw_json_in_output": '{"query"' not in assembled,
    }
    expected = {
        "visible_chunk_count_gt_1": True,
        "skipped_tool_call_chunks": True,
        "skipped_tool_node_messages": True,
        "assembled_contains_roadmap": True,
        "no_raw_json_in_output": True,
    }
    return {
        "name": "stream_mode_messages_filtering",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_knowledge_base_incremental_update_and_delete(),
        case_format_source_citation_and_truncation(),
        case_rag_agent_invoke_and_unanswerable_guard(),
        case_stream_mode_messages_filtering(),
    ]
    print(
        json.dumps(
            {
                "version": platform.python_version(),
                "system": platform.system(),
                "cases": cases,
            },
            ensure_ascii=False,
        )
    )


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。

入口文件:projects/langchain-project-knowledge-qa-lab/explore-project-knowledge-qa.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-project-knowledge-qa.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、LangChain 本地离线隔离依赖。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:LangChain

课程关联工程包(登记关联37章) · 含当前章节或实例 · mbskycom202612a509.zip

下载课程关联工程包:LangChain

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a530.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习