GraphRAG 安装与使用教程

张开发
2026/4/10 6:49:13 15 分钟阅读

分享文章

GraphRAG 安装与使用教程
一、GraphRAG 简介GraphRAGGraph Retrieval-Augmented Generation是由微软研究院开发的基于知识图谱的检索增强生成框架。它通过构建结构化的知识图谱来增强大语言模型LLM的推理能力相比传统 RAG 方法在处理复杂、多跳查询时表现更优。核心特性特性说明知识图谱构建自动从非结构化文本中提取实体、关系和声明社区检测使用 Leiden 算法发现图谱中的社区结构分层摘要生成不同粒度社区级→全局级的摘要报告多种搜索模式支持 Local Search、Global Search、DRIFT Search模块化设计可自定义工作流、提示词和模型配置适用场景大规模文档分析- 如法律合同、研究报告、技术文档复杂查询推理- 需要连接多个信息片段的问答主题发现与总结- 自动识别文档集合的主题结构企业知识管理- 构建可查询的知识库二、环境准备系统要求Python: 3.10 - 3.12推荐 3.11操作系统: Linux/macOS/Windows内存: 至少 8GB RAM处理大型数据集建议 16GB存储: 根据数据量建议预留 10GB 空间前置依赖确保已安装pip和venv# 检查 Python 版本python--version# 应显示 3.10.x 或更高# 检查 pippip--version三、安装方法方法一标准安装推荐# 创建虚拟环境python-mvenv graphrag_env# 激活虚拟环境# Linux/macOS:sourcegraphrag_env/bin/activate# Windows:graphrag_env\Scripts\activate# 安装 GraphRAGpipinstallgraphrag# 验证安装graphrag--version方法二安装特定版本# 安装最新稳定版pipinstallgraphrag2.1.0# 或安装开发版包含最新功能pipinstallgraphrag--pre方法三从源码安装开发者# 克隆仓库gitclone https://github.com/microsoft/graphrag.gitcdgraphrag# 创建虚拟环境python-mvenv venvsourcevenv/bin/activate# Windows: venv\Scripts\activate# 安装依赖pipinstallpoetry poetryinstall# 或使用 pippipinstall-e.方法四使用 Conda# 创建 conda 环境conda create-ngraphragpython3.11conda activate graphrag# 安装 GraphRAGpipinstallgraphrag四、快速开始步骤 1准备数据创建工作目录并放入文本文件mkdir-p./ragtest/inputecho在这里放入你的.txt文本文件./ragtest/input/sample.txt步骤 2初始化项目# 进入工作目录cdragtest# 初始化 GraphRAG生成配置文件graphrag init--root.执行后会生成settings.yaml- 主配置文件.env- 环境变量API 密钥等prompts/- 提示词模板目录步骤 3配置 API 密钥编辑.env文件# OpenAI 配置默认GRAPHRAG_API_KEYsk-your-openai-api-key-here# 或 Azure OpenAIGRAPHRAG_API_KEYyour-azure-api-keyGRAPHRAG_LLM_MODELazure/gpt-4oGRAPHRAG_EMBEDDING_MODELazure/text-embedding-3-small步骤 4配置模型settings.yaml编辑settings.yaml根据需求选择模式标准模式完整功能models:default_chat_model:type:openai_chatmodel:gpt-4o-miniapi_key:${GRAPHRAG_API_KEY}default_embedding_model:type:openai_embeddingmodel:text-embedding-3-smallapi_key:${GRAPHRAG_API_KEY}workflows:-create_base_text_units-create_final_documents-extract_graph-finalize_graph-create_communities-create_community_reports-generate_text_embeddings快速模式NLP 加速低成本models:default_chat_model:type:openai_chatmodel:gpt-4o-minidefault_embedding_model:type:openai_embeddingmodel:text-embedding-3-smallworkflows:-create_base_text_units-create_final_documents-extract_graph_nlp# 使用 NLP 替代 LLM-prune_graph-finalize_graph-create_communities-create_community_reports_text# 文本报告-generate_text_embeddings步骤 5构建索引# 标准构建graphrag index--root.# 或使用 Python APIpython-c import asyncio from graphrag.api import build_index from graphrag.config.load_config import load_config async def main(): config load_config(.) await build_index(configconfig) asyncio.run(main()) 构建过程会显示进度 Workflow: create_base_text_units ✅ Loaded 5 text units Workflow: extract_graph ✅ Extracted 150 entities, 230 relationships Workflow: create_communities ✅ Found 12 communities ...步骤 6查询知识库Global Search全局总结graphrag query\--root.\--methodglobal\--query这些文档的主要主题是什么Local Search局部检索graphrag query\--root.\--methodlocal\--query特定实体的详细信息DRIFT Search动态推理graphrag query\--root.\--methoddrift\--query需要多步推理的复杂问题五、Python API 使用基础用法importasynciofromgraphrag.apiimportbuild_index,global_search,local_searchfromgraphrag.config.load_configimportload_configasyncdefmain():# 加载配置configload_config(./ragtest)# 构建索引只需执行一次# await build_index(configconfig)# 执行全局搜索resultawaitglobal_search(configconfig,query总结这些文档的核心内容)print(result.response)if__name____main__:asyncio.run(main())自定义工作流fromgraphrag.index.workflows.factoryimportPipelineFactory# 定义自定义工作流asyncdefcustom_entity_extraction(config,context):自定义实体抽取逻辑# 实现自定义处理returncontext# 注册工作流PipelineFactory.register(custom_extraction,custom_entity_extraction)# 在 settings.yaml 中使用# workflows:# - create_base_text_units# - custom_extraction# - finalize_graph六、常见问题Q1: 安装时报错Microsoft Visual C 14.0 is required解决安装 Visual Studio Build Tools# Windows 下载并安装# https://visualstudio.microsoft.com/visual-cpp-build-tools/# 或使用 conda 预编译包condainstall-cconda-forge graphragQ2: 构建索引时内存不足解决减小批次大小chunks:size:300# 减小块大小overlap:50# 减小重叠batch_size:5# 减小批次数Q3: 使用本地模型Ollama/LM Studiomodels:default_chat_model:type:openai_chatmodel:llama3.1api_base:http://localhost:11434/v1# Ollamaapi_key:dummydefault_embedding_model:type:openai_embeddingmodel:nomic-embed-textapi_base:http://localhost:11434/v1api_key:dummyQ4: 如何更新 GraphRAGpipinstall--upgradegraphrag七、项目结构ragtest/ ├── input/ # 输入文本文件 ├── output/ │ └── 20260409-XXXXXX/ # 索引结果时间戳命名 │ ├── artifacts/ # 图谱数据Parquet 格式 │ └── reports/ # 社区报告 ├── prompts/ # 提示词模板 ├── cache/ # 缓存目录 ├── settings.yaml # 主配置 └── .env # API 密钥八、进阶配置自定义实体类型extract_graph:entity_types:[在这里填入你需要的实体类型]调整社区层级create_communities:max_cluster_size:100# 最大社区规模use_lcc:true# 使用最大连通分量增量更新fromgraphrag.apiimportbuild_indexfromgraphrag.config.enumsimportIndexingMethod# 增量更新添加新文档awaitbuild_index(configconfig,methodIndexingMethod.Standard,is_updateTrue# 启用增量模式)九、参考资源官方文档: https://microsoft.github.io/graphrag/GitHub 仓库: https://github.com/microsoft/graphrag快速入门指南: https://microsoft.github.io/graphrag/get_started/工作原理: https://microsoft.github.io/graphrag/index/overview/

更多文章