链载Ai

标题: GraphRAG Ollama,构建本地精准全局问答系统! [打印本页]

作者: 链载Ai    时间: 昨天 10:51
标题: GraphRAG Ollama,构建本地精准全局问答系统!
01

引言

ingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;letter-spacing: 0.544px;text-wrap: wrap;visibility: visible;color: rgb(163, 163, 163) !important;">

RAG 是目前大语言模型相关最知名的工具之一,从外部知识库中检索事实,以便为大型语言模型(LLM)提供最准确、最新的信息。但 RAG 并不完美,在更好的使用 RAG 方面仍存在许多挑战。例如当针对整个文本文档提出一个全局的问题时,RAG会失败,因为RAG本质是一个查询聚焦摘要任务,需要先基于index做检索,而且不是一个明确的检索全文任务。同时受限于大语言模型的上下文窗口限制,不可避免中间信息和关联信息丢失的问题。


为了解决这些问题,微软提出了Graph RAG方法,使用 LLM 在两个阶段构建基于图的文本索引:首先从源文档中推导出实体知识图,然后为所有密切相关的实体组预生成社区摘要。给定一个问题,每个社区摘要用于生成部分响应,然后对所有部分响应进行总结以提供最终响应。对于一类关于 100万个标记范围的数据集的全局理解问题,Graph RAG证明了图 RAG 在生成答案的全面性和多样性方面相对于简单的 RAG 基线有了显着改进。


但是,Graph RAG使用大语言模型从源文件抽取图entity和总结,并建设图索引,对token的消耗非常大,小编给大家算了一笔账,如果使用GPT-4o,一篇5万字左右的文档,Graph RAG的示例代码构建图的文本索引消耗27万左右 tokens,单次问答消耗约1万tokens,做个测试预计消费2-4美元,这也太贵了!

02

最佳实践

ingFang SC", "Hiragino Sans GB", "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;letter-spacing: 0.544px;text-wrap: wrap;visibility: visible;color: rgb(163, 163, 163) !important;">

为了让更多的人更加容易体验Graph RAG,本文在魔搭社区的免费Notebook算力中,体验使用本地模型+Ollama+GraphRAG。


参考项目:

https://github.com/TheAiSingularity/graphrag-local-ollama


代码解析

该项目主要修改了文件路径/graphrag-local-ollama/graphrag/llm/openai/openai_embeddings_llm.py文件,将embedding的调用方式从OpenAI格式改为Ollama格式,大家也可以clone官方代码做如下修改,或者使用如Text-embedding-inference之类的支持OpenAI embedding API格式的库。

class OpenAIEmbeddingsLLM(BaseLLM[EmbeddingInput, EmbeddingOutput]):_client: OpenAIClientTypes_configuration: OpenAIConfiguration
def __init__(self, client: OpenAIClientTypes, configuration: OpenAIConfiguration):self._client = clientself._configuration = configuration
async def _execute_llm(self, input: EmbeddingInput, **kwargs: Unpack[LLMInput]) -> EmbeddingOutput | None:args = {"model": self._configuration.model,**(kwargs.get("model_parameters") or {}),}embedding_list = []for inp in input:embedding = ollama.embeddings(model="nomic-embed-text", prompt=inp)embedding_list.append(embedding["embedding"])return embedding_list


模型配置

安装Ollama

#直接从modelscope下载ollama安装包modelscopedownload--model=modelscope/ollama-linux--local_dir./ollama-linux#运行ollama安装脚本cdollama-linuxsudochmod777./ollama-modelscope-install.sh./ollama-modelscope-install.sh


embedding模型使用Ollama自带的nomic-embed-text

ollamapullnomic-embed-text#embedding


LLM使用ModelScope的Mistral-7B-Instruct-v0.3


模型链接:

https://modelscope.cn/models/LLM-Research/Mistral-7B-Instruct-v0.3-GGUF

modelscopedownload--model=LLM-Research/Mistral-7B-Instruct-v0.3-GGUF--local_dir.Mistral-7B-Instruct-v0.3.fp16.gguf


创建ModelFile

FROM /mnt/workspace/Mistral-7B-Instruct-v0.3.fp16.ggufPARAMETER stop "[INST]"PARAMETER stop "[/INST]"

TEMPLATE """{{- if .Messages }}{{- range $index, $_ := .Messages }}{{- if eq .Role "user" }}{{- if and (eq (len (slice $.Messages $index)) 1) $.Tools }}[AVAILABLE_TOOLS] {{ $.Tools }}[/AVAILABLE_TOOLS]{{- end }}[INST] {{ if and $.System (eq (len (slice $.Messages $index)) 1) }}{{ $.System }}
{{ end }}{{ .Content }}[/INST]{{- else if eq .Role "assistant" }}{{- if .Content }} {{ .Content }}{{- else if .ToolCalls }}[TOOL_CALLS] [{{- range .ToolCalls }}{"name": "{{ .Function.Name }}", "arguments": {{ .Function.Arguments }}}{{- end }}]{{- end }}</s>{{- else if eq .Role "tool" }}[TOOL_RESULTS] {"content": {{ .Content }}} [/TOOL_RESULTS]{{- end }}{{- end }}{{- else }}[INST] {{ if .System }}{{ .System }}
{{ end }}{{ .Prompt }}[/INST]{{- end }} {{ .Response }}{{- if .Response }}</s>{{- end }}"""


创建模型

ollamacreatemymistral--file./ModelFile


cloneGraphrag(ollama版本)repo并安装

gitclonehttps://github.com/TheAiSingularity/graphrag-local-ollama.gitcdgraphrag-local-ollama/pipinstall-e.


创建输入文件夹

将实验数据复制保存在./ragtest中,也可以增加自己的数据,目前仅支持.txt格式

mkdir-p./ragtest/inputcpinput/*./ragtest/input

初始化

初始化ragtest文件夹,并存入配置文件

python-mgraphrag.index--init--root./ragtestmvsettings.yaml./ragtest

可以将配置文件中的模型文件和embedding模型按照需求做对应的修改,如:


运行索引并创建图:

这部分对LLM有蛮大的要求,如果LLM的输出json格式不稳定,创建图的过程将被中断,在过程中,我们也尝试了多个模型,mistral的json输出稳定性比较好。

python-mgraphrag.index--root./ragtest


运行query,目前仅支持全局方式

python-mgraphrag.query--root./ragtest--methodglobal"Whatismachinelearning?"

同时,使用如下python代码,生成可视化的graphml文件

from pygraphml import GraphMLParser
parser = GraphMLParser()g = parser.parse("./graphrag-local-ollama/ragtest/output/***/artifacts/summarized_graph.graphml")
g.show()






欢迎光临 链载Ai (https://www.lianzai.com/) Powered by Discuz! X3.5