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

本地 CLI、关系聚类与向量检索

PYTHONCPython 3.12、Microsoft GraphRAG 3.3.0,固定模型回复和本地数据。graph_lab.py
graph_lab.py175 行
"""Check Microsoft GraphRAG's 3.3 CLI and local graph operations without model calls."""
import inspect
from importlib.metadata import version
import json
import logging
import os
from pathlib import Path
import socket
from tempfile import TemporaryDirectory

from unittest.mock import patch

import pandas as pd
from typer.testing import CliRunner

from graphrag.cli.main import app
from graphrag.config.load_config import load_config
from graphrag.index.operations.cluster_graph import cluster_graph
from graphrag_vectors import F, VectorStoreDocument
from graphrag_vectors.lancedb import LanceDBVectorStore

CASES = []
RUNNER = CliRunner()


def observe(name, given, operation, expected, actual):
    assert actual == expected, (name, expected, actual)
    CASES.append(dict(name=name, input=given, operation=operation, expected=expected, actual=actual))


def cli_and_config(root):
    args = ["init", "--root", str(root), "--model", "gpt-4.1-mini", "--embedding", "text-embedding-3-small"]
    init = RUNNER.invoke(app, args)
    assert init.exit_code == 0, (init.output, init.exception)
    settings = root / "settings.yaml"
    observe("graphrag_init_layout", "空工作目录,显式指定两个模型名称", "执行真实 graphrag init",
            [True, True, True, True],
            [settings.is_file(), (root / "input").is_dir(), (root / "prompts/extract_graph.txt").is_file(),
             (root / ".env").read_text(encoding="utf8").strip() == "GRAPHRAG_API_KEY=<API_KEY>"])
    original = settings.read_bytes()
    duplicate = RUNNER.invoke(app, args)
    observe("graphrag_init_existing", "已初始化且无 --force", "再次初始化并比较设置字节",
            [1, "ValueError", True],
            [duplicate.exit_code, type(duplicate.exception).__name__, settings.read_bytes() == original])

    config = load_config(root, {"chunking": {"size": 128, "overlap": 16}})
    observe("graphrag_config_fields", "默认项目配置,覆盖分块为 128/16",
            "调用 graphrag.config.load_config",
            ["gpt-4.1-mini", "text-embedding-3-small", 128, 16, "lancedb"],
            [config.completion_models["default_completion_model"].model,
             config.embedding_models["default_embedding_model"].model,
             config.chunking.size, config.chunking.overlap, config.vector_store.type])
    options = ["--root", str(root)]
    valid = RUNNER.invoke(app, ["index", *options, "--dry-run", "--skip-validation"])
    if valid.exit_code != 0:
        raise RuntimeError(valid.output) from valid.exception
    observe("graphrag_index_dry_run", "固定项目,跳过会连接模型的校验",
            "执行 index --dry-run --skip-validation,并查索引输出",
            [0, []], [valid.exit_code, sorted(path.name for path in root.rglob("*.parquet"))])
    for flag in ("--resume", "--update"):
        bad = RUNNER.invoke(app, ["index", *options, flag])
        observe("graphrag_index_unknown_" + flag[2:], flag, "交给真实 CLI 解析",
                [2, True], [bad.exit_code, "No such option" in bad.output])
    update = RUNNER.invoke(app, ["update", "--help"])
    observe("graphrag_update_entry", "update --help", "查看独立更新子命令",
            [0, True, True], [update.exit_code, "--root" in update.output, "--method" in update.output])

    # Exercise the real parser/dispatcher without loading an index or using a model.
    from graphrag.cli import query

    with patch.object(query, "run_local_search") as dispatch:
        position = RUNNER.invoke(app, ["query", *options, "--method", "local", "哪个班次值守"])
        assert position.exit_code == 0, (position.output, position.exception)
        kwargs = dispatch.call_args.kwargs
        old_option = RUNNER.invoke(app, ["query", *options, "--method", "local", "--query", "不应调度"])
        observe("graphrag_query_dispatch", "位置参数和 --query 两种输入",
                "真实 CLI 解析后观察 local 调用参数,查询后端替换为记录器",
                [0, 1, "哪个班次值守", True, 2, True],
                [position.exit_code, dispatch.call_count, kwargs["query"], kwargs["root_dir"] == root,
                 old_option.exit_code, "No such option" in old_option.output])
    for method in ("global", "drift", "basic"):
        question = "查找本站巡检交接"
        with patch.object(query, "run_" + method + "_search") as selected:
            dispatched = RUNNER.invoke(app, ["query", *options, "--method", method, question])
            assert dispatched.exit_code == 0, (dispatched.output, dispatched.exception)
            observe("graphrag_query_dispatch_" + method, [method, question],
                    "真实 CLI 调用相应的检索分支,后端用记录器隔离",
                    [1, question], [selected.call_count, selected.call_args.kwargs["query"]])
    tune = RUNNER.invoke(app, ["prompt-tune", "--help"])
    observe("graphrag_prompt_tune_cli", "prompt-tune --help",
            "核对固定版本的语言、输出和旧配置选项",
            [0, True, True, False],
            [tune.exit_code, "--language" in tune.output, "--output" in tune.output, "--config" in tune.output])

    from graphrag import api

    names = ["global_search", "local_search", "drift_search", "basic_search"]
    observe("graphrag_api_surface", "四个查询入口、旧 search 与旧配置导入",
            "检查实际可调用协程和旧导入",
            [[True, True, True, True], False, False],
            [[inspect.iscoroutinefunction(getattr(api, name)) for name in names],
             hasattr(api, "search"), hasattr(api, "GraphRagConfig")])


def graph_and_vectors(root):
    edges = pd.DataFrame([
        ("BUOY", "HARBOR", 4), ("HARBOR", "TOWER", 3), ("TOWER", "BUOY", 3),
        ("WELL", "GARDEN", 2),
    ], columns=["source", "target", "weight"])
    table = root / "harbor_edges.parquet"
    edges.to_parquet(table, index=False)
    loaded = pd.read_parquet(table)
    observe("graphrag_parquet_edges", "4 条带权边,包含 2 个连通分量",
            "写入与回读临时 Parquet,比较列和值",
            [["source", "target", "weight"], True], [list(loaded.columns), loaded.equals(edges)])

    def communities(frame, use_lcc):
        return sorted(sorted(nodes) for level, _, _, nodes in cluster_graph(
            frame, max_cluster_size=12, use_lcc=use_lcc, seed=19) if level == 0)

    harbor = ["BUOY", "HARBOR", "TOWER"]
    garden = ["GARDEN", "WELL"]
    observe("graphrag_leiden_components", "两个分离子图,固定 seed=19",
            "运行 Microsoft GraphRAG 使用的 Leiden 聚类,切换最大连通分量选项",
            [[harbor, garden], [harbor], [harbor, garden]],
            [communities(loaded, False), communities(loaded, True), communities(loaded.iloc[::-1], False)])

    store = LanceDBVectorStore(db_uri=str(root / "vectors"), index_name="harbor", vector_size=2,
                              fields={"area": "str"})
    store.connect()
    store.create_index()
    store.load_documents([
        VectorStoreDocument("buoy", [1.0, 0.0], {"area": "harbor"}),
        VectorStoreDocument("tower", [0.8, 0.2], {"area": "harbor"}),
        VectorStoreDocument("garden", [0.0, 1.0], {"area": "park"}),
    ])
    queries = [([1.0, 0.0], None), ([0.0, 1.0], None), ([0.0, 1.0], F.area == "harbor")]
    found = [store.similarity_search_by_vector(vec, k=1, filters=where)[0].document.id
             for vec, where in queries]
    observe("graphrag_lance_search", "两组固定向量与区域过滤条件",
            "写入实际 LanceDB 后查询最近结果", ["buoy", "garden", "tower"], found)
    try:
        store.load_documents([VectorStoreDocument("invalid", [1.0, 0.0, 0.0])])
    except ValueError as error:
        actual = ["dimension 3" in str(error), "vector_size 2" in str(error)]
    else:
        actual = [False, False]
    observe("graphrag_lance_dimension", "2 维索引,写入 3 维向量",
            "核对 SDK 的实际校验错误", [True, True], actual)


def main():
    def offline(*_args, **_kwargs):
        raise AssertionError("Unexpected network connection")

    logging.disable(logging.CRITICAL)
    env = {"LITELLM_LOCAL_MODEL_COST_MAP": "True", "GRAPHRAG_API_KEY": "local-placeholder-only"}
    with patch.dict(os.environ, env), patch.object(socket.socket, "connect", offline):
        with TemporaryDirectory(prefix="mbsky-graphrag-") as folder:
            root = Path(folder).resolve()
            original_directory = Path.cwd()
            try:
                cli_and_config(root)
                graph_and_vectors(root)
            finally:
                os.chdir(original_directory)
                logging.shutdown()
    print(json.dumps(dict(versions={p: version(p) for p in (
        "graphrag", "graphrag-vectors", "graspologic-native", "lancedb", "pandas", "pyarrow")}, cases=CASES),
        ensure_ascii=False))


if __name__ == "__main__":
    main()
本例需在 CPython 3.12、Microsoft GraphRAG 3.3.0,固定模型回复和本地数据。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:CPython 3.12、Microsoft GraphRAG 3.3.0,固定模型回复和本地数据。

入口文件:projects/ai-agent-graphrag/graph_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 graph_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 CPython 3.12、Microsoft GraphRAG 3.3.0,固定模型回复和本地数据。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AI Agent(智能体)

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

下载课程关联工程包:AI Agent(智能体)

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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