首页
/ Nano-GraphRAG 使用教程

Nano-GraphRAG 使用教程

2026-01-30 04:09:57作者:柏廷章Berta

1. 项目介绍

Nano-GraphRAG 是一个简单、易于修改的 GraphRAG(关系图生成与检索)实现。它旨在提供一个更小、更快、更清洁的 GraphRAG,同时保留核心功能。该项目是基于 Python 语言,支持异步操作,并且代码完全类型化。Nano-GraphRAG 可以与多种组件(如 faiss、neo4j、ollama 等)配合使用,适用于需要长期用户记忆的多用户 RAG 解决方案。

2. 项目快速启动

安装

从源代码安装

首先克隆仓库:

git clone https://github.com/gusye1234/nano-graphrag.git
cd nano-graphrag
pip install -e .

从 PyPi 安装

pip install nano-graphrag

使用

以下是一个快速启动的示例:

from nano_graphrag import GraphRAG, QueryParam

# 初始化 GraphRAG
graph_func = GraphRAG(working_dir="./dickens")

# 插入文本
with open("./book.txt", "r") as f:
    graph_func.insert(f.read())

# 执行全局搜索
print(graph_func.query("What are the top themes in this story?"))

# 执行局部搜索
print(graph_func.query("What are the top themes in this story?", param=QueryParam(mode="local")))

# 下次从相同目录初始化 GraphRAG 时,它会自动重新加载所有上下文

确保在运行之前设置了 OpenAI API 密钥:

export OPENAI_API_KEY="sk-..."

如果使用的是 Azure OpenAI API 或 Amazon Bedrock API,请按照项目说明进行配置。

3. 应用案例和最佳实践

下载文本数据

以下示例展示了如何下载《圣诞颂歌》并使用 nano-graphrag 进行处理:

curl https://raw.githubusercontent.com/gusye1234/nano-graphrag/main/tests/mock_data.txt > ./book.txt

异步操作

对于每个同步方法 NAME(...),都有一个对应的异步方法 aNAME(...)

await graph_func.ainsert(...)
await graph_func.aquery(...)

自定义分块

nano-graphrag 允许自定义分块方法。例如,使用内置的文本分隔符分块:

from nano_graphrag._op import chunking_by_separators
GraphRAG(..., chunk_func=chunking_by_separators,...)

4. 典型生态项目

目前 nano-graphrag 支持以下组件:

  • LLM(大型语言模型):OpenAI、Amazon Bedrock、DeepSeek、ollama
  • 嵌入模型:OpenAI、Amazon Bedrock、Sentence-transformers
  • 向量数据库:nano-vectordb、hnswlib、milvus-lite、faiss
  • 图存储:networkx、neo4j
  • 可视化:graphml

这些组件可以帮助开发者根据自己的需求构建和扩展 nano-graphrag 的功能。

登录后查看全文
热门项目推荐
相关项目推荐

项目优选

收起