[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"tool-gusye1234--nano-graphrag":3,"similar-gusye1234--nano-graphrag":110},{"id":4,"github_repo":5,"name":6,"description_en":7,"description_zh":8,"ai_summary_zh":8,"readme_en":9,"readme_zh":10,"quickstart_zh":11,"use_case_zh":12,"hero_image_url":13,"owner_login":14,"owner_name":15,"owner_avatar_url":16,"owner_bio":17,"owner_company":18,"owner_location":19,"owner_email":19,"owner_twitter":14,"owner_website":19,"owner_url":20,"languages":21,"stars":26,"forks":27,"last_commit_at":28,"license":29,"difficulty_score":30,"env_os":31,"env_gpu":32,"env_ram":33,"env_deps":34,"category_tags":45,"github_topics":49,"view_count":30,"oss_zip_url":19,"oss_zip_packed_at":19,"status":56,"created_at":57,"updated_at":58,"faqs":59,"releases":89},4361,"gusye1234\u002Fnano-graphrag","nano-graphrag","A simple, easy-to-hack GraphRAG implementation","nano-graphrag 是一个轻量级、易于理解和修改的 GraphRAG（基于图谱的检索增强生成）实现。它旨在解决官方 GraphRAG 项目代码庞大、结构复杂、难以阅读和二次开发的问题，让开发者能更轻松地掌握核心技术并融入自己的项目。\n\n该项目在保留核心功能的前提下，将核心代码压缩至约 1100 行，不仅运行更快、结构更清晰，还具备出色的可移植性，支持 Faiss、Neo4j、Ollama 等多种后端组件。此外，它原生支持异步操作和完整的类型提示，非常适合需要构建高效知识检索系统的 Python 开发者和技术研究人员使用。无论是想快速验证想法的原型开发，还是希望深入定制图谱构建逻辑的高级用户，都能从中受益。\n\nnano-graphrag 提供了灵活的部署选项，既兼容 OpenAI、Azure、Amazon Bedrock 等主流大模型服务，也支持在无 API 密钥的情况下通过本地模型（如 Transformers 和 Ollama）运行。其简洁的 API 设计让用户只需几行代码即可完成文档插入与全局或局部图谱查询，是探索图增强检索技术的理想入门工具。","\u003Cdiv align=\"center\">\n  \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\">\n    \u003Cpicture>\n      \u003Csource media=\"(prefers-color-scheme: dark)\" srcset=\"https:\u002F\u002Fassets.memodb.io\u002Fnano-graphrag-dark.png\">\n      \u003Cimg alt=\"Shows the MemoDB logo\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fgusye1234_nano-graphrag_readme_c7e714aaa3aa.png\" width=\"512\">\n    \u003C\u002Fpicture>\n  \u003C\u002Fa>\n  \u003Cp>\u003Cstrong>A simple, easy-to-hack GraphRAG implementation\u003C\u002Fstrong>\u003C\u002Fp>\n  \u003Cp>\n    \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fpython->=3.9.11-blue\">\n    \u003Ca href=\"https:\u002F\u002Fpypi.org\u002Fproject\u002Fnano-graphrag\u002F\">\n      \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fpypi\u002Fv\u002Fnano-graphrag.svg\">\n    \u003C\u002Fa>\n    \u003Ca href=\"https:\u002F\u002Fcodecov.io\u002Fgithub\u002Fgusye1234\u002Fnano-graphrag\" > \n     \u003Cimg src=\"https:\u002F\u002Fcodecov.io\u002Fgithub\u002Fgusye1234\u002Fnano-graphrag\u002Fgraph\u002Fbadge.svg?token=YFPMj9uQo7\"\u002F> \n \t\t\u003C\u002Fa>\n    \u003Ca href=\"https:\u002F\u002Fpepy.tech\u002Fproject\u002Fnano-graphrag\">\n      \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fgusye1234_nano-graphrag_readme_c0f8f0901205.png\">\n    \u003C\u002Fa>\n  \u003C\u002Fp>\n  \u003Cp>\n  \t\u003Ca href=\"https:\u002F\u002Fdiscord.gg\u002FsqCVzAhUY6\">\n      \u003Cimg src=\"https:\u002F\u002Fdcbadge.limes.pink\u002Fapi\u002Fserver\u002FsqCVzAhUY6?style=flat\">\n    \u003C\u002Fa>\n    \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fissues\u002F8\">\n       \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002F群聊-wechat-green\">\n    \u003C\u002Fa>\n  \u003C\u002Fp>\n\u003C\u002Fdiv>\n\n\n\n\n\n\n\n\n\n😭 [GraphRAG](https:\u002F\u002Farxiv.org\u002Fpdf\u002F2404.16130) is good and powerful, but the official [implementation](https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fgraphrag\u002Ftree\u002Fmain) is difficult\u002Fpainful to **read or hack**.\n\n😊 This project provides a **smaller, faster, cleaner GraphRAG**, while remaining the core functionality(see [benchmark](#benchmark) and [issues](#Issues) ).\n\n🎁 Excluding `tests` and prompts,  `nano-graphrag` is about **1100 lines of code**.\n\n👌 Small yet [**portable**](#Components)(faiss, neo4j, ollama...), [**asynchronous**](#Async) and fully typed.\n\n\n\n> If you're looking for a multi-user RAG solution for long-term user memory, have a look at this project: [memobase](https:\u002F\u002Fgithub.com\u002Fmemodb-io\u002Fmemobase) :)\n\n## Install\n\n**Install from source** (recommend)\n\n```shell\n# clone this repo first\ncd nano-graphrag\npip install -e .\n```\n\n**Install from PyPi**\n\n```shell\npip install nano-graphrag\n```\n\n\n\n## Quick Start\n\n> [!TIP]\n>\n> **Please set OpenAI API key in environment: `export OPENAI_API_KEY=\"sk-...\"`.** \n\n> [!TIP]\n> If you're using Azure OpenAI API, refer to the [.env.example](.\u002F.env.example.azure) to set your azure openai. Then pass `GraphRAG(...,using_azure_openai=True,...)` to enable.\n\n> [!TIP]\n> If you're using Amazon Bedrock API, please ensure your credentials are properly set through commands like `aws configure`. Then enable it by configuring like this: `GraphRAG(...,using_amazon_bedrock=True, best_model_id=\"us.anthropic.claude-3-sonnet-20240229-v1:0\", cheap_model_id=\"us.anthropic.claude-3-haiku-20240307-v1:0\",...)`. Refer to an [example script](.\u002Fexamples\u002Fusing_amazon_bedrock.py).\n\n> [!TIP]\n>\n> If you don't have any key, check out this [example](.\u002Fexamples\u002Fno_openai_key_at_all.py) that using `transformers` and `ollama` . If you like to use another LLM or Embedding Model, check [Advances](#Advances).\n\ndownload a copy of A Christmas Carol by Charles Dickens:\n\n```shell\ncurl https:\u002F\u002Fraw.githubusercontent.com\u002Fgusye1234\u002Fnano-graphrag\u002Fmain\u002Ftests\u002Fmock_data.txt > .\u002Fbook.txt\n```\n\nUse the below python snippet:\n\n```python\nfrom nano_graphrag import GraphRAG, QueryParam\n\ngraph_func = GraphRAG(working_dir=\".\u002Fdickens\")\n\nwith open(\".\u002Fbook.txt\") as f:\n    graph_func.insert(f.read())\n\n# Perform global graphrag search\nprint(graph_func.query(\"What are the top themes in this story?\"))\n\n# Perform local graphrag search (I think is better and more scalable one)\nprint(graph_func.query(\"What are the top themes in this story?\", param=QueryParam(mode=\"local\")))\n```\n\nNext time you initialize a `GraphRAG` from the same `working_dir`, it will reload all the contexts automatically.\n\n#### Batch Insert\n\n```python\ngraph_func.insert([\"TEXT1\", \"TEXT2\",...])\n```\n\n\u003Cdetails>\n\u003Csummary> Incremental Insert\u003C\u002Fsummary>\n\n`nano-graphrag` supports incremental insert, no duplicated computation or data will be added:\n\n```python\nwith open(\".\u002Fbook.txt\") as f:\n    book = f.read()\n    half_len = len(book) \u002F\u002F 2\n    graph_func.insert(book[:half_len])\n    graph_func.insert(book[half_len:])\n```\n\n> `nano-graphrag` use md5-hash of the content as the key, so there is no duplicated chunk.\n>\n> However, each time you insert, the communities of graph will be re-computed and the community reports will be re-generated\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary> Naive RAG\u003C\u002Fsummary>\n\n`nano-graphrag` supports naive RAG insert and query as well:\n\n```python\ngraph_func = GraphRAG(working_dir=\".\u002Fdickens\", enable_naive_rag=True)\n...\n# Query\nprint(rag.query(\n      \"What are the top themes in this story?\",\n      param=QueryParam(mode=\"naive\")\n)\n```\n\u003C\u002Fdetails>\n\n\n### Async\n\nFor each method `NAME(...)` , there is a corresponding async method `aNAME(...)`\n\n```python\nawait graph_func.ainsert(...)\nawait graph_func.aquery(...)\n...\n```\n\n### Available Parameters\n\n`GraphRAG` and `QueryParam` are `dataclass` in Python. Use `help(GraphRAG)` and `help(QueryParam)` to see all available parameters!  Or check out the [Advances](#Advances) section to see some options.\n\n\n\n## Components\n\nBelow are the components you can use:\n\n| Type            |                             What                             |                       Where                       |\n| :-------------- | :----------------------------------------------------------: | :-----------------------------------------------: |\n| LLM             |                            OpenAI                            |                     Built-in                      |\n|                 |                        Amazon Bedrock                        |                     Built-in                      |\n|                 |                           DeepSeek                           |              [examples](.\u002Fexamples)               |\n|                 |                           `ollama`                           |              [examples](.\u002Fexamples)               |\n| Embedding       |                            OpenAI                            |                     Built-in                      |\n|                 |                        Amazon Bedrock                        |                     Built-in                      |\n|                 |                    Sentence-transformers                     |              [examples](.\u002Fexamples)               |\n| Vector DataBase | [`nano-vectordb`](https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-vectordb) |                     Built-in                      |\n|                 |        [`hnswlib`](https:\u002F\u002Fgithub.com\u002Fnmslib\u002Fhnswlib)        |         Built-in, [examples](.\u002Fexamples)          |\n|                 |  [`milvus-lite`](https:\u002F\u002Fgithub.com\u002Fmilvus-io\u002Fmilvus-lite)   |              [examples](.\u002Fexamples)               |\n|                 | [faiss](https:\u002F\u002Fgithub.com\u002Ffacebookresearch\u002Ffaiss?tab=readme-ov-file) |              [examples](.\u002Fexamples)               |\n| Graph Storage   | [`networkx`](https:\u002F\u002Fnetworkx.org\u002Fdocumentation\u002Fstable\u002Findex.html) |                     Built-in                      |\n|                 |                [`neo4j`](https:\u002F\u002Fneo4j.com\u002F)                 | Built-in([doc](.\u002Fdocs\u002Fuse_neo4j_for_graphrag.md)) |\n| Visualization   |                           graphml                            |              [examples](.\u002Fexamples)               |\n| Chunking        |                        by token size                         |                     Built-in                      |\n|                 |                       by text splitter                       |                     Built-in                      |\n\n- `Built-in` means we have that implementation inside `nano-graphrag`. `examples` means we have that implementation inside an tutorial under [examples](.\u002Fexamples) folder.\n\n- Check [examples\u002Fbenchmarks](.\u002Fexamples\u002Fbenchmarks) to see few comparisons between components.\n- **Always welcome to contribute more components.**\n\n## Advances\n\n\n\n\u003Cdetails>\n\u003Csummary>Some setup options\u003C\u002Fsummary>\n\n- `GraphRAG(...,always_create_working_dir=False,...)` will skip the dir-creating step. Use it if you switch all your components to non-file storages.\n\n\u003C\u002Fdetails>\n\n\n\n\u003Cdetails>\n\u003Csummary>Only query the related context\u003C\u002Fsummary>\n\n`graph_func.query` return the final answer without streaming. \n\nIf you like to interagte `nano-graphrag` in your project, you can use `param=QueryParam(..., only_need_context=True,...)`, which will only return the retrieved context from graph, something like:\n\n````\n# Local mode\n-----Reports-----\n```csv\nid,\tcontent\n0,\t# FOX News and Key Figures in Media and Politics...\n1, ...\n```\n...\n\n# Global mode\n----Analyst 3----\nImportance Score: 100\nDonald J. Trump: Frequently discussed in relation to his political activities...\n...\n````\n\nYou can integrate that context into your customized prompt.\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>Prompt\u003C\u002Fsummary>\n\n`nano-graphrag` use prompts from `nano_graphrag.prompt.PROMPTS` dict object. You can play with it and replace any prompt inside.\n\nSome important prompts:\n\n- `PROMPTS[\"entity_extraction\"]` is used to extract the entities and relations from a text chunk.\n- `PROMPTS[\"community_report\"]` is used to organize and summary the graph cluster's description.\n- `PROMPTS[\"local_rag_response\"]` is the system prompt template of the local search generation.\n- `PROMPTS[\"global_reduce_rag_response\"]` is the system prompt template of the global search generation.\n- `PROMPTS[\"fail_response\"]` is the fallback response when nothing is related to the user query.\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>Customize Chunking\u003C\u002Fsummary>\n\n\n`nano-graphrag` allow you to customize your own chunking method, check out the [example](.\u002Fexamples\u002Fusing_custom_chunking_method.py).\n\nSwitch to the built-in text splitter chunking method:\n\n```python\nfrom nano_graphrag._op import chunking_by_seperators\n\nGraphRAG(...,chunk_func=chunking_by_seperators,...)\n```\n\n\u003C\u002Fdetails>\n\n\n\n\u003Cdetails>\n\u003Csummary>LLM Function\u003C\u002Fsummary>\n\nIn `nano-graphrag`, we requires two types of LLM, a great one and a cheap one. The former is used to plan and respond, the latter is used to summary. By default, the great one is `gpt-4o` and the cheap one is `gpt-4o-mini`\n\nYou can implement your own LLM function (refer to `_llm.gpt_4o_complete`):\n\n```python\nasync def my_llm_complete(\n    prompt, system_prompt=None, history_messages=[], **kwargs\n) -> str:\n  # pop cache KV database if any\n  hashing_kv: BaseKVStorage = kwargs.pop(\"hashing_kv\", None)\n  # the rest kwargs are for calling LLM, for example, `max_tokens=xxx`\n\t...\n  # YOUR LLM calling\n  response = await call_your_LLM(messages, **kwargs)\n  return response\n```\n\nReplace the default one with:\n\n```python\n# Adjust the max token size or the max async requests if needed\nGraphRAG(best_model_func=my_llm_complete, best_model_max_token_size=..., best_model_max_async=...)\nGraphRAG(cheap_model_func=my_llm_complete, cheap_model_max_token_size=..., cheap_model_max_async=...)\n```\n\nYou can refer to this [example](.\u002Fexamples\u002Fusing_deepseek_as_llm.py) that use [`deepseek-chat`](https:\u002F\u002Fplatform.deepseek.com\u002Fapi-docs\u002F) as the LLM model\n\nYou can refer to this [example](.\u002Fexamples\u002Fusing_ollama_as_llm.py) that use [`ollama`](https:\u002F\u002Fgithub.com\u002Follama\u002Follama) as the LLM model\n\n#### Json Output\n\n`nano-graphrag` will use `best_model_func` to output JSON with params `\"response_format\": {\"type\": \"json_object\"}`. However there are some open-source model maybe produce unstable JSON. \n\n`nano-graphrag` introduces a post-process interface for you to convert the response to JSON. This func's signature is below:\n\n```python\ndef YOUR_STRING_TO_JSON_FUNC(response: str) -> dict:\n  \"Convert the string response to JSON\"\n  ...\n```\n\nAnd pass your own func by `GraphRAG(...convert_response_to_json_func=YOUR_STRING_TO_JSON_FUNC,...)`.\n\nFor example, you can refer to [json_repair](https:\u002F\u002Fgithub.com\u002Fmangiucugna\u002Fjson_repair) to repair the JSON string returned by LLM. \n\u003C\u002Fdetails>\n\n\n\n\u003Cdetails>\n\u003Csummary>Embedding Function\u003C\u002Fsummary>\n\nYou can replace the default embedding functions with any `_utils.EmbedddingFunc` instance.\n\nFor example, the default one is using OpenAI embedding API:\n\n```python\n@wrap_embedding_func_with_attrs(embedding_dim=1536, max_token_size=8192)\nasync def openai_embedding(texts: list[str]) -> np.ndarray:\n    openai_async_client = AsyncOpenAI()\n    response = await openai_async_client.embeddings.create(\n        model=\"text-embedding-3-small\", input=texts, encoding_format=\"float\"\n    )\n    return np.array([dp.embedding for dp in response.data])\n```\n\nReplace default embedding function with:\n\n```python\nGraphRAG(embedding_func=your_embed_func, embedding_batch_num=..., embedding_func_max_async=...)\n```\n\nYou can refer to an [example](.\u002Fexamples\u002Fusing_local_embedding_model.py) that use `sentence-transformer` to locally compute embeddings.\n\u003C\u002Fdetails>\n\n\n\u003Cdetails>\n\u003Csummary>Storage Component\u003C\u002Fsummary>\n\nYou can replace all storage-related components to your own implementation, `nano-graphrag` mainly uses three kinds of storage:\n\n**`base.BaseKVStorage` for storing key-json pairs of data** \n\n- By default we use disk file storage as the backend. \n- `GraphRAG(.., key_string_value_json_storage_cls=YOURS,...)`\n\n**`base.BaseVectorStorage` for indexing embeddings**\n\n- By default we use [`nano-vectordb`](https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-vectordb) as the backend.\n- We have a built-in [`hnswlib`](https:\u002F\u002Fgithub.com\u002Fnmslib\u002Fhnswlib) storage also, check out this [example](.\u002Fexamples\u002Fusing_hnsw_as_vectorDB.py).\n- Check out this [example](.\u002Fexamples\u002Fusing_milvus_as_vectorDB.py) that implements [`milvus-lite`](https:\u002F\u002Fgithub.com\u002Fmilvus-io\u002Fmilvus-lite) as the backend (not available in Windows).\n- `GraphRAG(.., vector_db_storage_cls=YOURS,...)`\n\n**`base.BaseGraphStorage` for storing knowledge graph**\n\n- By default we use [`networkx`](https:\u002F\u002Fgithub.com\u002Fnetworkx\u002Fnetworkx) as the backend.\n- We have a built-in `Neo4jStorage` for graph, check out this [tutorial](.\u002Fdocs\u002Fuse_neo4j_for_graphrag.md).\n- `GraphRAG(.., graph_storage_cls=YOURS,...)`\n\nYou can refer to `nano_graphrag.base` to see detailed interfaces for each components.\n\u003C\u002Fdetails>\n\n\n\n## FQA\n\nCheck [FQA](.\u002Fdocs\u002FFAQ.md).\n\n\n\n## Roadmap\n\nSee [ROADMAP.md](.\u002Fdocs\u002FROADMAP.md)\n\n\n\n## Contribute\n\n`nano-graphrag` is open to any kind of contribution. Read [this](.\u002Fdocs\u002FCONTRIBUTING.md) before you contribute.\n\n\n\n\n## Benchmark\n\n- [benchmark for English](.\u002Fdocs\u002Fbenchmark-en.md)\n- [benchmark for Chinese](.\u002Fdocs\u002Fbenchmark-zh.md)\n- [An evaluation](.\u002Fexamples\u002Fbenchmarks\u002Feval_naive_graphrag_on_multi_hop.ipynb) notebook on a [multi-hop RAG task](https:\u002F\u002Fgithub.com\u002Fyixuantt\u002FMultiHop-RAG)\n\n\n\n## Projects that used `nano-graphrag`\n\n- [Medical Graph RAG](https:\u002F\u002Fgithub.com\u002FMedicineToken\u002FMedical-Graph-RAG): Graph RAG for the Medical Data\n- [LightRAG](https:\u002F\u002Fgithub.com\u002FHKUDS\u002FLightRAG): Simple and Fast Retrieval-Augmented Generation\n- [fast-graphrag](https:\u002F\u002Fgithub.com\u002Fcirclemind-ai\u002Ffast-graphrag): RAG that intelligently adapts to your use case, data, and queries\n- [HiRAG](https:\u002F\u002Fgithub.com\u002Fhhy-huang\u002FHiRAG): Retrieval-Augmented Generation with Hierarchical Knowledge\n\n> Welcome to pull requests if your project uses `nano-graphrag`, it will help others to trust this repo❤️\n\n\n\n## Issues\n\n- `nano-graphrag` didn't implement the `covariates` feature of `GraphRAG`\n- `nano-graphrag` implements the global search different from the original. The original use a map-reduce-like style to fill all the communities into context, while `nano-graphrag` only use the top-K important and central communites (use `QueryParam.global_max_consider_community` to control, default to 512 communities).\n\n","\u003Cdiv align=\"center\">\n  \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\">\n    \u003Cpicture>\n      \u003Csource media=\"(prefers-color-scheme: dark)\" srcset=\"https:\u002F\u002Fassets.memodb.io\u002Fnano-graphrag-dark.png\">\n      \u003Cimg alt=\"展示MemoDB的Logo\" src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fgusye1234_nano-graphrag_readme_c7e714aaa3aa.png\" width=\"512\">\n    \u003C\u002Fpicture>\n  \u003C\u002Fa>\n  \u003Cp>\u003Cstrong>一个简单易用、便于二次开发的GraphRAG实现\u003C\u002Fstrong>\u003C\u002Fp>\n  \u003Cp>\n    \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002Fpython->=3.9.11-blue\">\n    \u003Ca href=\"https:\u002F\u002Fpypi.org\u002Fproject\u002Fnano-graphrag\u002F\">\n      \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fpypi\u002Fv\u002Fnano-graphrag.svg\">\n    \u003C\u002Fa>\n    \u003Ca href=\"https:\u002F\u002Fcodecov.io\u002Fgithub\u002Fgusye1234\u002Fnano-graphrag\" > \n     \u003Cimg src=\"https:\u002F\u002Fcodecov.io\u002Fgithub\u002Fgusye1234\u002Fnano-graphrag\u002Fgraph\u002Fbadge.svg?token=YFPMj9uQo7\"\u002F> \n \t\t\u003C\u002Fa>\n    \u003Ca href=\"https:\u002F\u002Fpepy.tech\u002Fproject\u002Fnano-graphrag\">\n      \u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fgusye1234_nano-graphrag_readme_c0f8f0901205.png\">\n    \u003C\u002Fa>\n  \u003C\u002Fp>\n  \u003Cp>\n  \t\u003Ca href=\"https:\u002F\u002Fdiscord.gg\u002FsqCVzAhUY6\">\n      \u003Cimg src=\"https:\u002F\u002Fdcbadge.limes.pink\u002Fapi\u002Fserver\u002FsqCVzAhUY6?style=flat\">\n    \u003C\u002Fa>\n    \u003Ca href=\"https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fissues\u002F8\">\n       \u003Cimg src=\"https:\u002F\u002Fimg.shields.io\u002Fbadge\u002F群聊-wechat-green\">\n    \u003C\u002Fa>\n  \u003C\u002Fp>\n\u003C\u002Fdiv>\n\n\n\n\n\n\n\n\n\n😭 [GraphRAG](https:\u002F\u002Farxiv.org\u002Fpdf\u002F2404.16130) 功能强大且优秀，但其官方[实现](https:\u002F\u002Fgithub.com\u002Fmicrosoft\u002Fgraphrag\u002Ftree\u002Fmain)却难以阅读或修改。\n\n😊 本项目提供了一个**更小、更快、更简洁的GraphRAG实现**，同时保留了核心功能（详见[基准测试](#benchmark)和[问题讨论](#Issues)）。\n\n🎁 排除`tests`和提示模板后，`nano-graphrag`仅约**1100行代码**。\n\n👌 虽然体积小巧，但它具有[可移植性](#Components)（支持Faiss、Neo4j、Ollama等）、[异步支持](#Async)，并且实现了完全类型化。\n\n\n\n> 如果您正在寻找一种适用于长期用户记忆的多用户RAG解决方案，请查看此项目：[memobase](https:\u002F\u002Fgithub.com\u002Fmemodb-io\u002Fmemobase) :)\n\n## 安装\n\n**从源码安装**（推荐）\n\n```shell\n# 首先克隆本仓库\ncd nano-graphrag\npip install -e .\n```\n\n**从PyPI安装**\n\n```shell\npip install nano-graphrag\n```\n\n\n\n## 快速开始\n\n> [!TIP]\n>\n> **请在环境变量中设置OpenAI API密钥：`export OPENAI_API_KEY=\"sk-...\"`。**\n\n> [!TIP]\n> 如果您使用的是Azure OpenAI API，请参考 [.env.example](.\u002F.env.example.azure) 来配置您的Azure OpenAI信息。然后通过传递 `GraphRAG(...,using_azure_openai=True,...)` 来启用它。\n\n> [!TIP]\n> 如果您使用的是Amazon Bedrock API，请确保已通过 `aws configure` 等命令正确设置了凭证。之后可以通过如下方式启用：`GraphRAG(...,using_amazon_bedrock=True, best_model_id=\"us.anthropic.claude-3-sonnet-20240229-v1:0\", cheap_model_id=\"us.anthropic.claude-3-haiku-20240307-v1:0\",...)`。请参阅示例脚本 [using_amazon_bedrock.py](.\u002Fexamples\u002Fusing_amazon_bedrock.py)。\n\n> [!TIP]\n>\n> 如果您没有API密钥，可以查看这个示例 [no_openai_key_at_all.py](.\u002Fexamples\u002Fno_openai_key_at_all.py)，其中使用了`transformers`和`ollama`。如果您想使用其他LLM或嵌入模型，请参阅[进阶用法](#Advances)。\n\n下载查尔斯·狄更斯的《圣诞颂歌》：\n\n```shell\ncurl https:\u002F\u002Fraw.githubusercontent.com\u002Fgusye1234\u002Fnano-graphrag\u002Fmain\u002Ftests\u002Fmock_data.txt > .\u002Fbook.txt\n```\n\n然后使用以下Python代码片段：\n\n```python\nfrom nano_graphrag import GraphRAG, QueryParam\n\ngraph_func = GraphRAG(working_dir=\".\u002Fdickens\")\n\nwith open(\".\u002Fbook.txt\") as f:\n    graph_func.insert(f.read())\n\n# 执行全局GraphRAG搜索\nprint(graph_func.query(\"这篇故事的主要主题是什么？\"))\n\n# 执行局部GraphRAG搜索（我认为这种方式更好且更具扩展性）\nprint(graph_func.query(\"这篇故事的主要主题是什么？\", param=QueryParam(mode=\"local\")))\n```\n\n下次您从同一`working_dir`初始化`GraphRAG`时，它会自动重新加载所有上下文。\n\n#### 批量插入\n\n```python\ngraph_func.insert([\"TEXT1\", \"TEXT2\",...])\n```\n\n\u003Cdetails>\n\u003Csummary> 增量插入\u003C\u002Fsummary>\n\n`nano-graphrag`支持增量插入，不会重复计算或添加相同数据：\n\n```python\nwith open(\".\u002Fbook.txt\") as f:\n    book = f.read()\n    half_len = len(book) \u002F\u002F 2\n    graph_func.insert(book[:half_len])\n    graph_func.insert(book[half_len:])\n```\n\n> `nano-graphrag`使用内容的MD5哈希值作为键，因此不会出现重复的文本块。\n>\n> 不过，每次插入时，图中的社区结构都会被重新计算，并生成新的社区报告。\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary> 基础RAG模式\u003C\u002Fsummary>\n\n`nano-graphrag`同样支持基础RAG模式的插入和查询：\n\n```python\ngraph_func = GraphRAG(working_dir=\".\u002Fdickens\", enable_naive_rag=True)\n...\n# 查询\nprint(rag.query(\n      \"这篇故事的主要主题是什么？\",\n      param=QueryParam(mode=\"naive\")\n)\n```\n\u003C\u002Fdetails>\n\n\n### 异步支持\n\n对于每个方法 `NAME(...)`，都对应有一个异步方法 `aNAME(...)`。\n\n```python\nawait graph_func.ainsert(...)\nawait graph_func.aquery(...)\n...\n```\n\n### 可用参数\n\n`GraphRAG`和`QueryParam`都是Python中的`dataclass`。您可以使用 `help(GraphRAG)` 和 `help(QueryParam)` 查看所有可用参数！或者前往[进阶用法](#Advances)部分了解更多选项。\n\n## 组件\n\n以下是您可以使用的组件：\n\n| 类型            |                             什么                             |                       何处                       |\n| :-------------- | :----------------------------------------------------------: | :-----------------------------------------------: |\n| LLM             |                            OpenAI                            |                     内置                      |\n|                 |                        Amazon Bedrock                        |                     内置                      |\n|                 |                           DeepSeek                           |              [示例](.\u002Fexamples)               |\n|                 |                           `ollama`                           |              [示例](.\u002Fexamples)               |\n| Embedding       |                            OpenAI                            |                     内置                      |\n|                 |                        Amazon Bedrock                        |                     内置                      |\n|                 |                    Sentence-transformers                     |              [示例](.\u002Fexamples)               |\n| 向量数据库      | [`nano-vectordb`](https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-vectordb) |                     内置                      |\n|                 |        [`hnswlib`](https:\u002F\u002Fgithub.com\u002Fnmslib\u002Fhnswlib)        |         内置，[示例](.\u002Fexamples)          |\n|                 |  [`milvus-lite`](https:\u002F\u002Fgithub.com\u002Fmilvus-io\u002Fmilvus-lite)   |              [示例](.\u002Fexamples)               |\n|                 | [faiss](https:\u002F\u002Fgithub.com\u002Ffacebookresearch\u002Ffaiss?tab=readme-ov-file) |              [示例](.\u002Fexamples)               |\n| 图存储          | [`networkx`](https:\u002F\u002Fnetworkx.org\u002Fdocumentation\u002Fstable\u002Findex.html) |                     内置                      |\n|                 |                [`neo4j`](https:\u002F\u002Fneo4j.com\u002F)                 | 内置（[文档](.\u002Fdocs\u002Fuse_neo4j_for_graphrag.md)） |\n| 可视化          |                           graphml                            |              [示例](.\u002Fexamples)               |\n| 分块            |                        按 token 大小                         |                     内置                      |\n|                 |                       按文本分割器                       |                     内置                      |\n\n- `内置` 表示我们在 `nano-graphrag` 中已经实现了该功能。`示例` 表示我们在 [examples](.\u002Fexamples) 文件夹下的教程中提供了该实现。\n\n- 请查看 [examples\u002Fbenchmarks](.\u002Fexamples\u002Fbenchmarks)，以了解各组件之间的对比。\n- **我们始终欢迎更多组件的贡献。**\n\n## 进展\n\n\n\n\u003Cdetails>\n\u003Csummary>一些设置选项\u003C\u002Fsummary>\n\n- `GraphRAG(...,always_create_working_dir=False,...)` 将跳过创建目录的步骤。如果您将所有组件切换到非文件存储方式，可以使用此选项。\n\n\u003C\u002Fdetails>\n\n\n\n\u003Cdetails>\n\u003Csummary>仅查询相关上下文\u003C\u002Fsummary>\n\n`graph_func.query` 返回最终答案，不支持流式输出。 \n\n如果您希望在自己的项目中与 `nano-graphrag` 进行交互，可以使用 `param=QueryParam(..., only_need_context=True,...)`，它只会返回从图中检索到的上下文，例如：\n\n````\n# 本地模式\n-----报告-----\n```csv\nid,\tcontent\n0,\t# 福克斯新闻及媒体和政治领域的重要人物...\n1, ...\n```\n...\n\n# 全局模式\n----分析师 3----\n重要性得分：100\n唐纳德·J·特朗普：经常被讨论与其政治活动相关的内容...\n...\n````\n\n您可以将这些上下文整合到您自定义的提示中。\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>提示\u003C\u002Fsummary>\n\n`nano-graphrag` 使用来自 `nano_graphrag.prompt.PROMPTS` 字典对象中的提示。您可以尝试修改其中的任何提示。\n\n一些重要的提示：\n\n- `PROMPTS[\"entity_extraction\"]` 用于从文本块中提取实体和关系。\n- `PROMPTS[\"community_report\"]` 用于组织和总结图聚类的描述。\n- `PROMPTS[\"local_rag_response\"]` 是本地搜索生成的系统提示模板。\n- `PROMPTS[\"global_reduce_rag_response\"]` 是全球搜索生成的系统提示模板。\n- `PROMPTS[\"fail_response\"]` 是当用户查询没有任何相关内容时的备用响应。\n\n\u003C\u002Fdetails>\n\n\u003Cdetails>\n\u003Csummary>自定义分块\u003C\u002Fsummary>\n\n\n`nano-graphrag` 允许您自定义分块方法，请参阅 [示例](.\u002Fexamples\u002Fusing_custom_chunking_method.py)。\n\n切换到内置的文本分割器分块方法：\n\n```python\nfrom nano_graphrag._op import chunking_by_seperators\n\nGraphRAG(...,chunk_func=chunking_by_seperators,...)\n```\n\n\u003C\u002Fdetails>\n\n\n\n\u003Cdetails>\n\u003Csummary>LLM 函数\u003C\u002Fsummary>\n\n在 `nano-graphrag` 中，我们需要两种类型的 LLM：一种是高性能的，另一种是低成本的。前者用于规划和响应，后者用于摘要。默认情况下，高性能模型是 `gpt-4o`，低成本模型是 `gpt-4o-mini`。\n\n您可以实现自己的 LLM 函数（参考 `_llm.gpt_4o_complete`）：\n\n```python\nasync def my_llm_complete(\n    prompt, system_prompt=None, history_messages=[], **kwargs\n) -> str:\n  # 如果有缓存 KV 数据库，则将其移除\n  hashing_kv: BaseKVStorage = kwargs.pop(\"hashing_kv\", None)\n  # 剩余的 kwargs 用于调用 LLM，例如 `max_tokens=xxx`\n\t...\n  # 调用您的 LLM\n  response = await call_your_LLM(messages, **kwargs)\n  return response\n```\n\n用自定义函数替换默认函数：\n\n```python\n\n# 如需调整最大 token 数量或最大异步请求数量，请进行相应设置\nGraphRAG(最佳模型函数=my_llm_complete, 最佳模型最大 token 数量=..., 最佳模型最大异步请求数量=...)\nGraphRAG(经济模型函数=my_llm_complete, 经济模型最大 token 数量=..., 经济模型最大异步请求数量=...)\n```\n\n您可以参考这个[示例](.\u002Fexamples\u002Fusing_deepseek_as_llm.py)，它使用[`deepseek-chat`](https:\u002F\u002Fplatform.deepseek.com\u002Fapi-docs\u002F)作为 LLM 模型。\n\n您也可以参考这个[示例](.\u002Fexamples\u002Fusing_ollama_as_llm.py)，它使用[`ollama`](https:\u002F\u002Fgithub.com\u002Follama\u002Follama)作为 LLM 模型。\n\n#### JSON 输出\n\n`nano-graphrag` 会使用 `best_model_func` 来输出带有 `\"response_format\": {\"type\": \"json_object\"}` 参数的 JSON。然而，某些开源模型可能会生成不稳定的 JSON。\n\n为此，`nano-graphrag` 引入了一个后处理接口，用于将响应转换为 JSON。该函数的签名如下：\n\n```python\ndef YOUR_STRING_TO_JSON_FUNC(response: str) -> dict:\n  \"将字符串响应转换为 JSON\"\n  ...\n```\n\n然后通过 `GraphRAG(...convert_response_to_json_func=YOUR_STRING_TO_JSON_FUNC,...)` 将您自定义的函数传递进去。\n\n例如，您可以参考 [json_repair](https:\u002F\u002Fgithub.com\u002Fmangiucugna\u002Fjson_repair) 来修复 LLM 返回的 JSON 字符串。\n\u003C\u002Fdetails>\n\n\n\n\u003Cdetails>\n\u003Csummary>嵌入函数\u003C\u002Fsummary>\n\n您可以将默认的嵌入函数替换为任何 `_utils.EmbedddingFunc` 实例。\n\n例如，默认的嵌入函数是使用 OpenAI 的嵌入 API：\n\n```python\n@wrap_embedding_func_with_attrs(embedding_dim=1536, max_token_size=8192)\nasync def openai_embedding(texts: list[str]) -> np.ndarray:\n    openai_async_client = AsyncOpenAI()\n    response = await openai_async_client.embeddings.create(\n        model=\"text-embedding-3-small\", input=texts, encoding_format=\"float\"\n    )\n    return np.array([dp.embedding for dp in response.data])\n```\n\n要替换默认的嵌入函数，可以这样写：\n\n```python\nGraphRAG(embedding_func=your_embed_func, embedding_batch_num=..., embedding_func_max_async=...)\n```\n\n您可以参考一个[示例](.\u002Fexamples\u002Fusing_local_embedding_model.py)，它使用 `sentence-transformer` 在本地计算嵌入向量。\n\u003C\u002Fdetails>\n\n\n\u003Cdetails>\n\u003Csummary>存储组件\u003C\u002Fsummary>\n\n您可以将所有与存储相关的组件替换为自己的实现。`nano-graphrag` 主要使用三种类型的存储：\n\n**`base.BaseKVStorage` 用于存储键值对形式的数据**\n\n- 默认情况下，我们使用磁盘文件存储作为后端。\n- `GraphRAG(.., key_string_value_json_storage_cls=YOURS,...)`\n\n**`base.BaseVectorStorage` 用于索引嵌入向量**\n\n- 默认情况下，我们使用[`nano-vectordb`](https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-vectordb)作为后端。\n- 我们还内置了 [`hnswlib`](https:\u002F\u002Fgithub.com\u002Fnmslib\u002Fhnswlib) 存储，可以查看这个[示例](.\u002Fexamples\u002Fusing_hnsw_as_vectorDB.py)。\n- 另外，还有一个使用[`milvus-lite`](https:\u002F\u002Fgithub.com\u002Fmilvus-io\u002Fmilvus-lite)作为后端的[示例](.\u002Fexamples\u002Fusing_milvus_as_vectorDB.py)，不过该后端在 Windows 系统上不可用。\n- `GraphRAG(.., vector_db_storage_cls=YOURS,...)`\n\n**`base.BaseGraphStorage` 用于存储知识图谱**\n\n- 默认情况下，我们使用[`networkx`](https:\u002F\u002Fgithub.com\u002Fnetworkx\u002Fnetworkx)作为后端。\n- 我们还内置了一个 `Neo4jStorage` 用于图谱，可以查看这个[教程](.\u002Fdocs\u002Fuse_neo4j_for_graphrag.md)。\n- `GraphRAG(.., graph_storage_cls=YOURS,...)`\n\n您可以参考 `nano_graphrag.base` 查看每个组件的详细接口。\n\u003C\u002Fdetails>\n\n\n\n## 常见问题解答\n\n请查看[常见问题解答](.\u002Fdocs\u002FFAQ.md)。\n\n\n\n## 路线图\n\n请参阅[ROADMAP.md](.\u002Fdocs\u002FROADMAP.md)\n\n\n\n## 贡献\n\n`nano-graphrag` 欢迎任何形式的贡献。在贡献之前，请阅读[这篇文档](.\u002Fdocs\u002FCONTRIBUTING.md)。\n\n\n\n\n## 基准测试\n\n- [英文基准测试](.\u002Fdocs\u002Fbenchmark-en.md)\n- [中文基准测试](.\u002Fdocs\u002Fbenchmark-zh.md)\n- [一项评估](.\u002Fexamples\u002Fbenchmarks\u002Feval_naive_graphrag_on_multi_hop.ipynb)笔记本，针对一个[多跳 RAG 任务](https:\u002F\u002Fgithub.com\u002Fyixuantt\u002FMultiHop-RAG)\n\n\n\n## 使用过 `nano-graphrag` 的项目\n\n- [Medical Graph RAG](https:\u002F\u002Fgithub.com\u002FMedicineToken\u002FMedical-Graph-RAG)：用于医疗数据的图谱 RAG\n- [LightRAG](https:\u002F\u002Fgithub.com\u002FHKUDS\u002FLightRAG)：简单快速的检索增强生成\n- [fast-graphrag](https:\u002F\u002Fgithub.com\u002Fcirclemind-ai\u002Ffast-graphrag)：能够智能适应您的用例、数据和查询的 RAG\n- [HiRAG](https:\u002F\u002Fgithub.com\u002Fhhy-huang\u002FHiRAG)：基于层次化知识的检索增强生成\n\n> 如果您的项目使用了 `nano-graphrag`，欢迎提交 Pull Request，这将有助于其他人信任这个仓库❤️\n\n\n\n## 问题\n\n- `nano-graphrag` 尚未实现 `GraphRAG` 的 `covariates` 功能。\n- `nano-graphrag` 的全局搜索实现方式与原版不同。原版采用类似 MapReduce 的方式将所有社区的信息填充到上下文中，而 `nano-graphrag` 则只使用前 K 个重要且中心的社区（可通过 `QueryParam.global_max_consider_community` 控制，默认为 512 个社区）。","# nano-graphrag 快速上手指南\n\n`nano-graphrag` 是一个轻量、快速且易于定制的 GraphRAG（基于图谱的检索增强生成）实现。它保留了核心功能，但代码量仅约 1100 行，支持异步操作和多种后端组件。\n\n## 环境准备\n\n*   **操作系统**：Linux, macOS, Windows\n*   **Python 版本**：>= 3.9.11\n*   **前置依赖**：\n    *   需要配置大模型 API Key（默认支持 OpenAI）。\n    *   若使用其他模型（如 Ollama, DeepSeek, Amazon Bedrock），请确保相应服务已就绪。\n\n## 安装步骤\n\n推荐从源码安装以获取最新功能，也可直接通过 PyPI 安装。\n\n**方式一：从源码安装（推荐）**\n\n```shell\n# 克隆仓库\ngit clone https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag.git\ncd nano-graphrag\n\n# 安装依赖\npip install -e .\n```\n\n**方式二：从 PyPI 安装**\n\n```shell\npip install nano-graphrag\n```\n\n> **提示**：国内用户若下载缓慢，可添加 `-i https:\u002F\u002Fpypi.tuna.tsinghua.edu.cn\u002Fsimple` 使用清华镜像源。\n\n## 基本使用\n\n### 1. 配置 API Key\n\n在使用前，请在终端设置环境变量（以 OpenAI 为例）：\n\n```shell\nexport OPENAI_API_KEY=\"sk-...\"\n```\n\n*注：若使用 Azure OpenAI 或 Amazon Bedrock，需在代码中传递相应参数（见下文高级用法），或使用本地模型（如 Ollama）则无需此步。*\n\n### 2. 准备测试数据\n\n下载示例文本文件：\n\n```shell\ncurl https:\u002F\u002Fraw.githubusercontent.com\u002Fgusye1234\u002Fnano-graphrag\u002Fmain\u002Ftests\u002Fmock_data.txt > .\u002Fbook.txt\n```\n\n### 3. 运行代码\n\n创建一个 Python 文件（例如 `main.py`），填入以下代码即可体验全局和局部图谱搜索：\n\n```python\nfrom nano_graphrag import GraphRAG, QueryParam\n\n# 初始化 GraphRAG，指定工作目录\ngraph_func = GraphRAG(working_dir=\".\u002Fdickens\")\n\n# 插入数据\nwith open(\".\u002Fbook.txt\") as f:\n    graph_func.insert(f.read())\n\n# 执行全局图谱搜索 (Global Search)\nprint(graph_func.query(\"What are the top themes in this story?\"))\n\n# 执行局部图谱搜索 (Local Search，推荐，扩展性更好)\nprint(graph_func.query(\"What are the top themes in this story?\", param=QueryParam(mode=\"local\")))\n```\n\n**说明**：\n*   首次运行会自动构建知识图谱并保存在 `.\u002Fdickens` 目录。\n*   再次初始化相同 `working_dir` 时，会自动加载已有的上下文，无需重新计算。\n*   支持批量插入：`graph_func.insert([\"TEXT1\", \"TEXT2\", ...])`。\n*   支持增量插入：重复内容不会重复计算，但社区报告会重新生成。\n\n### 4. 异步支持\n\n所有同步方法均有对应的异步版本，只需在方法名前加 `a` 并使用 `await`：\n\n```python\nawait graph_func.ainsert(...)\nawait graph_func.aquery(...)\n```","某初创法律科技团队需要构建一个内部案例检索系统，以便律师能快速从数千份历史判决书中挖掘案件间的隐性关联和核心争议点。\n\n### 没有 nano-graphrag 时\n- **代码难以魔改**：官方 GraphRAG 实现过于庞大复杂，团队想针对法律术语优化图谱构建逻辑时，面对数万行代码无从下手，开发效率极低。\n- **资源消耗过大**：在处理中等规模数据集时，原有方案启动缓慢且内存占用高，导致在普通开发机上调试成本高昂。\n- **依赖环境沉重**：强绑定特定重型组件，难以灵活切换为团队已有的本地 Ollama 模型或轻量级向量库，部署灵活性差。\n- **黑盒问题难排查**：当检索结果不准确时，由于逻辑链路不透明，开发人员很难定位是图谱抽取错误还是检索路径偏差。\n\n### 使用 nano-graphrag 后\n- **核心逻辑透明可控**：借助其仅约 1100 行的精简代码，团队迅速理解了图谱构建流程，并成功植入了自定义的法律实体识别规则。\n- **运行轻快高效**：去除了冗余负担，系统在本地笔记本上即可流畅运行异步任务，大幅缩短了从数据插入到检索验证的迭代周期。\n- **组件灵活插拔**：利用其便携性，团队轻松将后端切换为 Faiss 和本地大模型，无需修改核心代码即实现了零成本私有化部署。\n- **调试直观清晰**：清晰的类型提示和模块化设计让问题定位变得简单，开发人员能快速调整参数以优化“局部检索”的准确度。\n\nnano-graphrag 通过极致的轻量化与可黑客性，让中小团队也能低成本拥有可深度定制的高质量图谱检索能力。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fgusye1234_nano-graphrag_c7e714aa.png","gusye1234","Gustavo Ye","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002Fgusye1234_710e08e0.jpg","GET REMEMBERED.\r\n\r\nBuilding Acontext.io\r\n\r\n@memodb-io.\r\n","memodb.io",null,"https:\u002F\u002Fgithub.com\u002Fgusye1234",[22],{"name":23,"color":24,"percentage":25},"Python","#3572A5",100,3758,403,"2026-04-06T01:38:16","MIT",2,"Linux, macOS, Windows","非必需。默认使用 OpenAI\u002FAzure\u002FBedrock 等云端 API；若使用本地模型（如 Ollama, transformers），取决于所选具体模型的硬件需求。","未说明",{"notes":35,"python":36,"dependencies":37},"该工具设计轻量（核心代码约 1100 行），默认依赖云端 LLM（需配置 OPENAI_API_KEY 等环境变量）。若需完全本地运行，可结合 Ollama 或 HuggingFace transformers 使用（参考示例脚本）。支持多种向量数据库（内置 nano-vectordb\u002Fhnswlib，或通过示例使用 Milvus\u002FFaiss）和图存储（内置 NetworkX 或 Neo4j）。",">=3.9.11",[38,39,40,41,42,43,44],"openai","tiktoken","networkx","nano-vectordb","hnswlib","tenacity","xxhash",[46,47,48],"语言模型","开发框架","Agent",[50,51,52,53,54,55],"gpt-4o","graphrag","learning-by-doing","gpt","llm","rag","ready","2026-03-27T02:49:30.150509","2026-04-06T18:54:44.170962",[60,65,70,75,80,85],{"id":61,"question_zh":62,"answer_zh":63,"source_url":64},19839,"如何处理生成社区报告时出现的 JSONDecodeError 错误？","该错误通常是因为 LLM 返回的响应格式不符合严格的 JSON 标准，或者在缓存机制中模型名称处理不当导致的。解决方案是检查缓存逻辑，确保使用统一的模型名称字符串（例如将具体的 'qwen-7b' 替换为通用的 'qwen'）作为缓存键。具体修改代码如下：\n1. 在计算哈希时：`args_hash = compute_args_hash(model, messages)`，确保传入的 model 是简化后的字符串。\n2. 在存储缓存时：`hashing_kv.upsert({args_hash: {\"return\": result, \"model\": model}})`，同样使用简化后的模型名。\n这样可以避免因模型全称包含特殊字符或长度不一致导致的解析失败。","https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fissues\u002F57",{"id":66,"question_zh":67,"answer_zh":68,"source_url":69},19840,"遇到 'maximum context length is 32768 tokens' 错误该如何解决？","此错误发生在输入给 LLM 的文本块超过模型最大上下文限制（如 32768 tokens）时。根本原因往往是代码在计算 token 长度时仅统计了部分字段（如 `key=lambda x: x[3]`），但在实际构建请求时却包含了所有字段（如 description, relations 等），导致实际长度超出预期。\n解决方案是修改 `_pack_single_community_describe()` 函数及相关调用处（位于 `_op.py` 和 `_utils.py`），确保在发送请求前对所有字段的总长度进行准确检测和截断，或者调整分块策略以减小单个社区的描述长度。建议参考 Issue 中的调试思路，对返回数据的每个字段都进行 token 计数校验。","https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fissues\u002F146",{"id":71,"question_zh":72,"answer_zh":73,"source_url":74},19841,"如何处理非 UTF-8 编码文件（如 GBK）导致的解码错误？","虽然官方 GraphRAG 要求 UTF-8 编码，但 nano-graphrag 在处理本地文件时可能会遇到系统默认编码（如 Windows 下的 GBK）问题。如果遇到 'gbk' codec errors，可以尝试以下方法：\n1. 确保输入文件已转换为 UTF-8 格式。\n2. 如果是通过 pip 安装的最新版本，请确认是否安装了必要的依赖，运行 `pip install future`。\n3. 建议直接从 GitHub 源码安装最新修复版本：`pip install git+https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag.git`，因为新版本可能已经在全局配置中增加了编码格式的自动检测或支持。","https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fissues\u002F50",{"id":76,"question_zh":77,"answer_zh":78,"source_url":79},19842,"如何配置并使用非 OpenAI 的大模型（如 Qwen, DeepSeek）？","nano-graphrag 支持替换默认的 LLM 和 Embedding 模型。要使用 Qwen、DeepSeek 等其他在线模型：\n1. 参考官方示例代码 `examples\u002Fusing_deepseek_as_llm.py` 或 `examples\u002Fusing_local_embedding_model.py`。\n2. 需要自定义 `best_model_func`、`cheap_model_func` 和 `embedding_func` 函数，将其指向新模型的 API 调用接口。\n3. 注意区分 Embedding 模型服务和大语言模型服务，两者都需要分别配置对应的函数来生成向量和文本回复。通过实例化 `GraphRAG` 时传入这些自定义函数即可生效。","https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fissues\u002F3",{"id":81,"question_zh":82,"answer_zh":83,"source_url":84},19843,"为什么查询与知识库无关的问题时仍然会返回结果？","这是 RAG（检索增强生成）系统的常见现象。当用户提问与知识库完全无关时，系统仍可能检索到一些实体或文本片段（例如日志显示的 'Using 20 entites...'），这是因为向量相似度检索可能会匹配到语义上看似相关但实际上无关的内容，或者阈值设置过低。\n优化建议：\n1. 调整检索阈值，过滤掉低相似度的匹配项。\n2. 优化 Prompt 提示词，明确指示模型在缺乏相关知识时应回答“不知道”或拒绝回答，而不是强行编造。\n3. 评估知识库的覆盖范围，确保存入的数据质量高且相关性强的内容占主导。","https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fissues\u002F6",{"id":86,"question_zh":87,"answer_zh":88,"source_url":64},19844,"何时应该分别使用 best_model_func、cheap_model_func 和 embedding_func？","这三个函数在 nano-graphrag 中承担不同的角色，以平衡成本和效果：\n1. `best_model_func`：用于关键任务，如生成高质量的社区报告、复杂的推理总结。应配置性能最强、准确率最高的大模型（如 GPT-4, Qwen-Max）。\n2. `cheap_model_func`：用于耗时较长但精度要求相对较低的任务，如初级的实体提取、关系抽取或大量数据的预处理。可配置成本较低、速度较快的模型（如 GPT-3.5, Qwen-Turbo）。\n3. `embedding_func`：专门用于将文本转换为向量以便进行相似度检索。必须配置专门的 Embedding 模型（如 text-embedding-3-small, bge-large-zh），不能用普通聊天模型替代。",[90,95,100,105],{"id":91,"version":92,"summary_zh":93,"released_at":94},117883,"v0.0.8","## 变更内容\n* 在 _llm.py 中添加 Azure OpenAI 作为选项，由 @SliverBulle 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F31 中完成\n* 添加 DSPy 用于实体抽取，由 @NumberChiffre 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F27 中完成\n* 修复：解决 graphml_fisualize.py 在数据过长时无法正常运行的问题，由 @akai-shuuichi 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F37 中完成\n* 功能：允许自定义分块方法，由 @rangehow 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F40 中完成\n* 支持自定义 HTML 路径和端口，由 @knightmarehs 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F52 中完成\n* 加快分块速度，并新增分隔符分块功能，由 @rangehow 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F48 中完成\n* 添加两个较为完整的示例，由 @morler 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F58 中完成\n* 将 DSPy 中的实体关系抽取转换为使用 CoT 模式，由 @NumberChiffre 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F44 中完成\n* 修复 Python 3.9 的联合类型问题，由 @NumberChiffre 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F60 中完成\n* 新特性：添加 Neo4j 图数据库后端，由 @gusye1234 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F61 中完成\n\n## 新贡献者\n* @SliverBulle 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F31 中完成了首次贡献\n* @akai-shuuichi 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F37 中完成了首次贡献\n* @rangehow 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F40 中完成了首次贡献\n* @knightmarehs 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F52 中完成了首次贡献\n* @morler 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F58 中完成了首次贡献\n\n**完整变更日志**：https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fcompare\u002Fv0.0.7...v0.0.8","2024-10-01T16:00:46",{"id":96,"version":97,"summary_zh":98,"released_at":99},117884,"v0.0.7","## 变更内容\n* 实体抽取失败可能是由于 `num_ctx` 设置过小导致的，@pimooook 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F23 中提供了一种解决方案。\n* @NumberChiffre 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F24 中为 NetworkXStorage 添加了单元测试。\n* 功能：@gusye1234 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F25 中为分块添加了朴素 RAG 实现。\n* CI：@gusye1234 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F26 中添加了代码覆盖率报告。\n* 测试：@gusye1234 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F28 中提高了覆盖率并添加了相关规则。\n* @handsomecaoyu 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F12 中添加了 Faiss 作为向量数据库的示例，并增加了可视化功能。\n* 文档：@gusye1234 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F30 中添加了对朴素 RAG 和图 RAG 的评估。\n\n## 新贡献者\n* @pimooook 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F23 中完成了首次贡献。\n* @gusye1234 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F25 中完成了首次贡献。\n* @handsomecaoyu 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F12 中完成了首次贡献。\n\n**完整变更日志**：https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fcompare\u002Fv0.0.6...v0.0.7","2024-09-09T07:13:55",{"id":101,"version":102,"summary_zh":103,"released_at":104},117885,"v0.0.6","修复 HNSWVectorStorage 本地查询的 bug\n\n**完整更新日志**: https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fcompare\u002Fv0.0.5...v0.0.6","2024-08-30T08:43:28",{"id":106,"version":107,"summary_zh":108,"released_at":109},117886,"v0.0.5","## 变更内容\n* @zzzcccxx 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F16 中修改了 nano_graphrag\u002Fgraphrag.py 第234行中错误的文件调用。\n* @wanderyum 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F17 中更新了 FAQ.md。\n* @NumberChiffre 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F18 中添加了 HNSW 向量存储。\n\n## 新贡献者\n* @zzzcccxx 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F16 中完成了首次贡献。\n* @wanderyum 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F17 中完成了首次贡献。\n* @NumberChiffre 在 https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fpull\u002F18 中完成了首次贡献。\n\n**完整变更日志**: https:\u002F\u002Fgithub.com\u002Fgusye1234\u002Fnano-graphrag\u002Fcompare\u002Fv0.0.3...v0.0.5","2024-08-28T11:53:24",[111,122,130,138,146,155],{"id":112,"name":113,"github_repo":114,"description_zh":115,"stars":116,"difficulty_score":117,"last_commit_at":118,"category_tags":119,"status":56},4358,"openclaw","openclaw\u002Fopenclaw","OpenClaw 是一款专为个人打造的本地化 AI 助手，旨在让你在自己的设备上拥有完全可控的智能伙伴。它打破了传统 AI 助手局限于特定网页或应用的束缚，能够直接接入你日常使用的各类通讯渠道，包括微信、WhatsApp、Telegram、Discord、iMessage 等数十种平台。无论你在哪个聊天软件中发送消息，OpenClaw 都能即时响应，甚至支持在 macOS、iOS 和 Android 设备上进行语音交互，并提供实时的画布渲染功能供你操控。\n\n这款工具主要解决了用户对数据隐私、响应速度以及“始终在线”体验的需求。通过将 AI 部署在本地，用户无需依赖云端服务即可享受快速、私密的智能辅助，真正实现了“你的数据，你做主”。其独特的技术亮点在于强大的网关架构，将控制平面与核心助手分离，确保跨平台通信的流畅性与扩展性。\n\nOpenClaw 非常适合希望构建个性化工作流的技术爱好者、开发者，以及注重隐私保护且不愿被单一生态绑定的普通用户。只要具备基础的终端操作能力（支持 macOS、Linux 及 Windows WSL2），即可通过简单的命令行引导完成部署。如果你渴望拥有一个懂你",349277,3,"2026-04-06T06:32:30",[48,47,120,121],"图像","数据工具",{"id":123,"name":124,"github_repo":125,"description_zh":126,"stars":127,"difficulty_score":117,"last_commit_at":128,"category_tags":129,"status":56},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,"2026-04-05T11:01:52",[47,120,48],{"id":131,"name":132,"github_repo":133,"description_zh":134,"stars":135,"difficulty_score":30,"last_commit_at":136,"category_tags":137,"status":56},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",140436,"2026-04-05T23:32:43",[47,48,46],{"id":139,"name":140,"github_repo":141,"description_zh":142,"stars":143,"difficulty_score":30,"last_commit_at":144,"category_tags":145,"status":56},2271,"ComfyUI","Comfy-Org\u002FComfyUI","ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎，专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式，采用直观的节点式流程图界面，让用户通过连接不同的功能模块即可构建个性化的生成管线。\n\n这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景，也能自由组合模型、调整参数并实时预览效果，轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性，不仅支持 Windows、macOS 和 Linux 全平台，还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构，并率先支持 SDXL、Flux、SD3 等前沿模型。\n\n无论是希望深入探索算法潜力的研究人员和开发者，还是追求极致创作自由度的设计师与资深 AI 绘画爱好者，ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",107662,"2026-04-03T11:11:01",[47,120,48],{"id":147,"name":148,"github_repo":149,"description_zh":150,"stars":151,"difficulty_score":117,"last_commit_at":152,"category_tags":153,"status":56},4292,"Deep-Live-Cam","hacksider\u002FDeep-Live-Cam","Deep-Live-Cam 是一款专注于实时换脸与视频生成的开源工具，用户仅需一张静态照片，即可通过“一键操作”实现摄像头画面的即时变脸或制作深度伪造视频。它有效解决了传统换脸技术流程繁琐、对硬件配置要求极高以及难以实时预览的痛点，让高质量的数字内容创作变得触手可及。\n\n这款工具不仅适合开发者和技术研究人员探索算法边界，更因其极简的操作逻辑（仅需三步：选脸、选摄像头、启动），广泛适用于普通用户、内容创作者、设计师及直播主播。无论是为了动画角色定制、服装展示模特替换，还是制作趣味短视频和直播互动，Deep-Live-Cam 都能提供流畅的支持。\n\n其核心技术亮点在于强大的实时处理能力，支持口型遮罩（Mouth Mask）以保留使用者原始的嘴部动作，确保表情自然精准；同时具备“人脸映射”功能，可同时对画面中的多个主体应用不同面孔。此外，项目内置了严格的内容安全过滤机制，自动拦截涉及裸露、暴力等不当素材，并倡导用户在获得授权及明确标注的前提下合规使用，体现了技术发展与伦理责任的平衡。",88924,"2026-04-06T03:28:53",[47,120,48,154],"视频",{"id":156,"name":157,"github_repo":158,"description_zh":159,"stars":160,"difficulty_score":30,"last_commit_at":161,"category_tags":162,"status":56},3704,"NextChat","ChatGPTNextWeb\u002FNextChat","NextChat 是一款轻量且极速的 AI 助手，旨在为用户提供流畅、跨平台的大模型交互体验。它完美解决了用户在多设备间切换时难以保持对话连续性，以及面对众多 AI 模型不知如何统一管理的痛点。无论是日常办公、学习辅助还是创意激发，NextChat 都能让用户随时随地通过网页、iOS、Android、Windows、MacOS 或 Linux 端无缝接入智能服务。\n\n这款工具非常适合普通用户、学生、职场人士以及需要私有化部署的企业团队使用。对于开发者而言，它也提供了便捷的自托管方案，支持一键部署到 Vercel 或 Zeabur 等平台。\n\nNextChat 的核心亮点在于其广泛的模型兼容性，原生支持 Claude、DeepSeek、GPT-4 及 Gemini Pro 等主流大模型，让用户在一个界面即可自由切换不同 AI 能力。此外，它还率先支持 MCP（Model Context Protocol）协议，增强了上下文处理能力。针对企业用户，NextChat 提供专业版解决方案，具备品牌定制、细粒度权限控制、内部知识库整合及安全审计等功能，满足公司对数据隐私和个性化管理的高标准要求。",87618,"2026-04-05T07:20:52",[47,46]]