GraphRag本地测试

news2024/9/21 18:34:13

测试环境:win10 python3.11.9

graphRAG的安装还是很简单的,直接pip

pip install graphrag

但要注意,官方说了需要 python3.10-3.12

安装完成后,建立一个文件夹,存放你的知识数据,目前graphRAG仅支持txt和csv

mkdir -p ./ragtest/input

然后准备一份数据,放到 /ragtest/input 下,我找了一份中文数据,为了演示,截取了部分文本

要初始化您的工作区,让我们首先运行命令graphrag.index --init。由于我们在上一步中已经配置了一个名为 .ragtest1` 的目录,因此我们可以运行以下命令:

python -m graphrag.index --init --root ./ragtest

执行完后,目录中结构如下

这将在目录中创建两个文件:.env和。settings.yaml./ragtest

  • .env包含运行 GraphRAG 管道所需的环境变量。如果检查文件,您将看到已定义的单个环境变量。 GRAPHRAG_API_KEY=<API_KEY>这是 OpenAI API 或 Azure OpenAI 端点的 API 密钥。您可以将其替换为您自己的 API 密钥。

  • settings.yaml包含管道的设置。您可以修改此文件以更改管道的设置。

OpenAI API免费key获取GitHub - chatanywhere/GPT_API_free: Free ChatGPT API Key,免费ChatGPT API,支持GPT4 API(免费),ChatGPT国内可用免费转发API,直连无需代理。可以搭配ChatBox等软件/插件使用,极大降低接口使用成本。国内即可无限制畅快聊天。

我们需要修改 settings.yaml,你可以直接复制我的如下,切记你本机安装了Ollama并且安装了下边两个模型

quentinz/bge-large-zh-v1.5:latestgemma2:9b

Ollama的安装到官网下载安装: Ollama

# 拉取quantinz模型
ollama pull quentinz/bge-base-zh-v1.5:latest

# 拉取gemma模型
ollama run gemma2:9b

# 展示模型列表
ollama list

安装如上命令拉取模型。

那么你可以复制如下内容到  settings.yaml

encoding_model: cl100k_base
skip_workflows: []
llm:
  api_key: ollama
  type: openai_chat # or azure_openai_chat
  model: gemma2:9b # 你ollama中的本地llm模型,可以换成其他的,只要你安装了就可以
  model_supports_json: true # recommended if this is available for your model.
  max_tokens: 2048
  # request_timeout: 180.0
  api_base: http://localhost:11434/v1 # 接口注意是v1
  # api_version: 2024-02-15-preview
  # organization: <organization_id>
  # deployment_name: <azure_model_deployment_name>
  # tokens_per_minute: 150_000 # set a leaky bucket throttle
  # requests_per_minute: 10_000 # set a leaky bucket throttle
  # max_retries: 10
  # max_retry_wait: 10.0
  # sleep_on_rate_limit_recommendation: true # whether to sleep when azure suggests wait-times
  concurrent_requests: 1 # the number of parallel inflight requests that may be made

parallelization:
  stagger: 0.3
  # num_threads: 50 # the number of threads to use for parallel processing

async_mode: threaded # or asyncio

embeddings:
  ## parallelization: override the global parallelization settings for embeddings
  async_mode: threaded # or asyncio
  llm:
    api_key: ollama
    type: openai_embedding # or azure_openai_embedding
    model: quentinz/bge-large-zh-v1.5:latest #你ollama中的本地embeding模型,可以换成其他的,只要你安装了就可以
    api_base: http://localhost:11434/api # 注意是 api
    # api_version: 2024-02-15-preview
    # organization: <organization_id>
    # deployment_name: <azure_model_deployment_name>
    # tokens_per_minute: 150_000 # set a leaky bucket throttle
    # requests_per_minute: 10_000 # set a leaky bucket throttle
    # max_retries: 10
    # max_retry_wait: 10.0
    # sleep_on_rate_limit_recommendation: true # whether to sleep when azure suggests wait-times
    concurrent_requests: 1 # the number of parallel inflight requests that may be made
    # batch_size: 16 # the number of documents to send in a single request
    # batch_max_tokens: 8191 # the maximum number of tokens to send in a single request
    # target: required # or optional
  


chunks:
  size: 300
  overlap: 100
  group_by_columns: [id] # by default, we don't allow chunks to cross documents
    
input:
  type: file # or blob
  file_type: text # or csv
  base_dir: "input"
  file_encoding: utf-8
  file_pattern: ".*\\.txt$"

cache:
  type: file # or blob
  base_dir: "cache"
  # connection_string: <azure_blob_storage_connection_string>
  # container_name: <azure_blob_storage_container_name>

storage:
  type: file # or blob
  base_dir: "output/${timestamp}/artifacts"
  # connection_string: <azure_blob_storage_connection_string>
  # container_name: <azure_blob_storage_container_name>

reporting:
  type: file # or console, blob
  base_dir: "output/${timestamp}/reports"
  # connection_string: <azure_blob_storage_connection_string>
  # container_name: <azure_blob_storage_container_name>

entity_extraction:
  ## llm: override the global llm settings for this task
  ## parallelization: override the global parallelization settings for this task
  ## async_mode: override the global async_mode settings for this task
  prompt: "prompts/entity_extraction.txt"
  entity_types: [organization,person,geo,event]
  max_gleanings: 0

summarize_descriptions:
  ## llm: override the global llm settings for this task
  ## parallelization: override the global parallelization settings for this task
  ## async_mode: override the global async_mode settings for this task
  prompt: "prompts/summarize_descriptions.txt"
  max_length: 500

claim_extraction:
  ## llm: override the global llm settings for this task
  ## parallelization: override the global parallelization settings for this task
  ## async_mode: override the global async_mode settings for this task
  # enabled: true
  prompt: "prompts/claim_extraction.txt"
  description: "Any claims or facts that could be relevant to information discovery."
  max_gleanings: 0

community_report:
  ## llm: override the global llm settings for this task
  ## parallelization: override the global parallelization settings for this task
  ## async_mode: override the global async_mode settings for this task
  prompt: "prompts/community_report.txt"
  max_length: 2000
  max_input_length: 8000

cluster_graph:
  max_cluster_size: 10

embed_graph:
  enabled: false # if true, will generate node2vec embeddings for nodes
  # num_walks: 10
  # walk_length: 40
  # window_size: 2
  # iterations: 3
  # random_seed: 597832

umap:
  enabled: false # if true, will generate UMAP embeddings for nodes

snapshots:
  graphml: false
  raw_entities: false
  top_level_nodes: false

local_search:
  # text_unit_prop: 0.5
  # community_prop: 0.1
  # conversation_history_max_turns: 5
  # top_k_mapped_entities: 10
  # top_k_relationships: 10
  max_tokens: 5000

global_search:
  max_tokens: 5000
  # data_max_tokens: 12000
  # map_max_tokens: 1000
  # reduce_max_tokens: 2000
  # concurrency: 32

最后我们将运行管道!

python -m graphrag.index --root ./ragtest

此时开始构建 索引和知识图谱,需要一定的时间

源码修改:

接下来,你还需要修改 两处源码,保证 进行local和global查询时不报错

1、修改 

"C:\Users\Administrator\AppData\Roaming\Python\Python310\site-packages\graphrag\llm\openai\openai_embeddings_llm.py"

修改这个源码,需要你找到对应路径哈

# Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License

"""The EmbeddingsLLM class."""

from typing_extensions import Unpack

from graphrag.llm.base import BaseLLM
from graphrag.llm.types import (
    EmbeddingInput,
    EmbeddingOutput,
    LLMInput,
)

from .openai_configuration import OpenAIConfiguration
from .types import OpenAIClientTypes
import ollama


class OpenAIEmbeddingsLLM(BaseLLM[EmbeddingInput, EmbeddingOutput]):
    """A text-embedding generator LLM."""

    _client: OpenAIClientTypes
    _configuration: OpenAIConfiguration

    def __init__(self, client: OpenAIClientTypes, configuration: OpenAIConfiguration):
        self.client = client
        self.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="quentinz/bge-large-zh-v1.5:latest",prompt=inp)
            embedding_list.append(embedding["embedding"])
        return embedding_list
        # embedding = await self.client.embeddings.create(
        #     input=input,
        #     **args,
        # )
        # return [d.embedding for d in embedding.data]

复制我的这个替换就可以,注意里边的 

embedding = ollama.embeddings(model="quentinz/bge-large-zh-v1.5:latest",prompt=inp)

这一句中的  model 要修改成和 你在settings中的embeding模型一致

2、修改

"C:\Users\Administrator\AppData\Roaming\Python\Python310\site-packages\graphrag\query\llm\oai\embedding.py"

修改这个源码,复制下边的直接替换这个文件

# Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License

"""OpenAI Embedding model implementation."""

import asyncio
from collections.abc import Callable
from typing import Any

import numpy as np
import tiktoken
from tenacity import (
    AsyncRetrying,
    RetryError,
    Retrying,
    retry_if_exception_type,
    stop_after_attempt,
    wait_exponential_jitter,
)

from graphrag.query.llm.base import BaseTextEmbedding
from graphrag.query.llm.oai.base import OpenAILLMImpl
from graphrag.query.llm.oai.typing import (
    OPENAI_RETRY_ERROR_TYPES,
    OpenaiApiType,
)
from graphrag.query.llm.text_utils import chunk_text
from graphrag.query.progress import StatusReporter

from langchain_community.embeddings import OllamaEmbeddings



class OpenAIEmbedding(BaseTextEmbedding, OpenAILLMImpl):
    """Wrapper for OpenAI Embedding models."""

    def __init__(
        self,
        api_key: str | None = None,
        azure_ad_token_provider: Callable | None = None,
        model: str = "text-embedding-3-small",
        deployment_name: str | None = None,
        api_base: str | None = None,
        api_version: str | None = None,
        api_type: OpenaiApiType = OpenaiApiType.OpenAI,
        organization: str | None = None,
        encoding_name: str = "cl100k_base",
        max_tokens: int = 8191,
        max_retries: int = 10,
        request_timeout: float = 180.0,
        retry_error_types: tuple[type[BaseException]] = OPENAI_RETRY_ERROR_TYPES,  # type: ignore
        reporter: StatusReporter | None = None,
    ):
        OpenAILLMImpl.__init__(
            self=self,
            api_key=api_key,
            azure_ad_token_provider=azure_ad_token_provider,
            deployment_name=deployment_name,
            api_base=api_base,
            api_version=api_version,
            api_type=api_type,  # type: ignore
            organization=organization,
            max_retries=max_retries,
            request_timeout=request_timeout,
            reporter=reporter,
        )

        self.model = model
        self.encoding_name = encoding_name
        self.max_tokens = max_tokens
        self.token_encoder = tiktoken.get_encoding(self.encoding_name)
        self.retry_error_types = retry_error_types

    def embed(self, text: str, **kwargs: Any) -> list[float]:
        """
        Embed text using OpenAI Embedding's sync function.

        For text longer than max_tokens, chunk texts into max_tokens, embed each chunk, then combine using weighted average.
        Please refer to: https://github.com/openai/openai-cookbook/blob/main/examples/Embedding_long_inputs.ipynb
        """
        token_chunks = chunk_text(
            text=text, token_encoder=self.token_encoder, max_tokens=self.max_tokens
        )
        chunk_embeddings = []
        chunk_lens = []
        for chunk in token_chunks:
            try:
                embedding, chunk_len = self._embed_with_retry(chunk, **kwargs)
                chunk_embeddings.append(embedding)
                chunk_lens.append(chunk_len)
            # TODO: catch a more specific exception
            except Exception as e:  # noqa BLE001
                self._reporter.error(
                    message="Error embedding chunk",
                    details={self.__class__.__name__: str(e)},
                )

                continue
        chunk_embeddings = np.average(chunk_embeddings, axis=0, weights=chunk_lens)
        chunk_embeddings = chunk_embeddings / np.linalg.norm(chunk_embeddings)
        return chunk_embeddings.tolist()

    async def aembed(self, text: str, **kwargs: Any) -> list[float]:
        """
        Embed text using OpenAI Embedding's async function.

        For text longer than max_tokens, chunk texts into max_tokens, embed each chunk, then combine using weighted average.
        """
        token_chunks = chunk_text(
            text=text, token_encoder=self.token_encoder, max_tokens=self.max_tokens
        )
        chunk_embeddings = []
        chunk_lens = []
        embedding_results = await asyncio.gather(*[
            self._aembed_with_retry(chunk, **kwargs) for chunk in token_chunks
        ])
        embedding_results = [result for result in embedding_results if result[0]]
        chunk_embeddings = [result[0] for result in embedding_results]
        chunk_lens = [result[1] for result in embedding_results]
        chunk_embeddings = np.average(chunk_embeddings, axis=0, weights=chunk_lens)  # type: ignore
        chunk_embeddings = chunk_embeddings / np.linalg.norm(chunk_embeddings)
        return chunk_embeddings.tolist()

    def _embed_with_retry(
        self, text: str | tuple, **kwargs: Any
    ) -> tuple[list[float], int]:
        try:
            retryer = Retrying(
                stop=stop_after_attempt(self.max_retries),
                wait=wait_exponential_jitter(max=10),
                reraise=True,
                retry=retry_if_exception_type(self.retry_error_types),
            )
            for attempt in retryer:
                with attempt:
                    embedding = (
                        OllamaEmbeddings(
                            model=self.model,
                        ).embed_query(text)
                        or []
                    )
                    return (embedding, len(text))
        except RetryError as e:
            self._reporter.error(
                message="Error at embed_with_retry()",
                details={self.__class__.__name__: str(e)},
            )
            return ([], 0)
        else:
            # TODO: why not just throw in this case?
            return ([], 0)

    async def _aembed_with_retry(
        self, text: str | tuple, **kwargs: Any
    ) -> tuple[list[float], int]:
        try:
            retryer = AsyncRetrying(
                stop=stop_after_attempt(self.max_retries),
                wait=wait_exponential_jitter(max=10),
                reraise=True,
                retry=retry_if_exception_type(self.retry_error_types),
            )
            async for attempt in retryer:
                with attempt:
                    embedding = (
                        await OllamaEmbeddings(
                            model=self.model,
                        ).embed_query(text) or [] )
                    return (embedding, len(text))
        except RetryError as e:
            self._reporter.error(
                message="Error at embed_with_retry()",
                details={self.__class__.__name__: str(e)},
            )
            return ([], 0)
        else:
            # TODO: why not just throw in this case?
            return ([], 0)

好了,坑你算是跳过去了,哈哈

测试效果

1、local查询

python -m graphrag.query --root ./ragtest1 --method local "人卫社的网址"

按这个格式执行,结果如下

图片

这个也被解析到了知识图谱中了,还可以吧,我数据比较小,你们可以试试大一点的数据

2、global查询

python -m graphrag.query --root ./ragtest1 --method global "人卫社的网址"

图片

也查到了,哈哈,初步还可以吧

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1977296.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Mysql错误:InnoDB: page_cleaner

今天一大早就收到同事昨晚发过来的信息&#xff1a;某省份的充电桩在昨晚22点到23点期间大量挂单即充电不能结算。首先想到的就是订单服务挂了&#xff0c;可查了数据一切正常。所以继续早跑&#xff0c;等上班回公司再查查原因。 来到公司查看了昨晚的项目日记情况&#xff0c…

使用Markdown画图

大部分 Markdown 编辑器的画图功能都是基于 mermaid 的&#xff0c;因此我们先介绍下它。 ‍ 什么是 mermaid ​ ‍ mermaid 是一个开源的项目&#xff0c;旨在通过纯文本的形式来画图&#xff0c;支持流程图&#xff0c;时序图&#xff0c;甘特图&#xff0c;类图&#x…

Arduino PID库 (1)– 简介

Arduino PID库 &#xff08;1&#xff09;– 简介 pid内容索引-CSDN博客pid术语及整定原则参考&#xff1a;手把手教你看懂并理解Arduino PID控制库——引子)库的改进QuickPID-sTune库 原文地址 随着新的Arduino PID库的发布&#xff0c;最后一个库虽然很可靠&#xff0c;但…

浅谈AC自动机算法(c++)

文章目录 自动机一些简单的自动机&#xff1a; AC 自动机字典树构建失配指针构建指针 [HNOI2006] 最短母串问题题目描述输入格式输出格式样例 #1样例输入 #1样例输出 #1 提示思路AC代码 「一本通 2.4 例 1」Keywords SearchAC代码 自动机 自动机是什么&#xff1f; 自动机的作…

Linux小组件:gcc

gcc 是C语言的编译器&#xff0c;在Linux下我们也用这个编译C语言 安装gcc sudo apt install build-essential 查看gcc版本信息 gcc --version 有时候会出现代码编译不过去的问题&#xff0c;通常可能是gcc的编译标准太低&#xff0c;不支持某些写法 比如在很多旧的编译标…

rk3588 部署yolov8.rknn

本文从步骤来记录在rk3588芯片上部署yolov8模型 主机&#xff1a;windows10 VMware Workstation 16 Pro 硬件&#xff1a;RK3588 EVB板 模型&#xff1a; RK3588.rknn 软件开发环境&#xff1a; c cmake step1: 主机上执行&#xff1a; 将rknn_model_zoo 工程文件下载…

spring:标签property

标签property对应于bean类公开的JavaBean setter方法。标签property的属性中&#xff0c;name为属性名&#xff0c;type为“”引号里面的类型&#xff0c;use为是否必须出现。 1.ref引用一个已经存在的对象,value创建一个新的对象 2.value可以赋一些简单类型的值&#xff0c;…

【MySQL】常用数据类型

目录 数据类型 数据类型分类 数值类型 tinyint类型 bit类型 小数类型 float decimal 字符串类型 char varchar 日期和时间类型 enum和set 数据类型 数据类型分类 数值类型 tinyint类型 tinyint类型只占用一个字节类似于编程语言中的字符char。有带符号和无符号两…

【系统架构设计师】二十四、安全架构设计理论与实践②

目录 三、系统安全体系架构规划框架 3.1 信息系统安全体系规划 3.2 信息系统安全规划框架 3.2.1 信息系统安全规划依托企业信息化战略规划 3.2.2 信息系统安全规划需要围绕技术安全、管理安全、组织安全考虑 3.2.3 信息系统安全规划以信息系统与信息资源的安全保护为核心…

Java——多线程(6/9):线程池、处理Runnable、Callable任务(认识线程池-线程池的工作原理,ThreadPoolExecutor构造器)

目录 认识线程池 介绍 线程池的工作原理 如何创建线程池 介绍 ThreadPoolExecutor构造器 代码实例 线程池的注意事项 线程池处理Runnable任务 ExecutorService的常用方法 代码实例 新任务拒绝策略 线程池处理Callable任务 ExecutorService的常用方法 代码实例…

二叉树的前序遍历 - 力扣(LeetCode)C语言

144. 二叉树的前序遍历 - 力扣&#xff08;LeetCode&#xff09;(点击前面链接即可查看题目) 一、题目 给你二叉树的根节点 root &#xff0c;返回它节点值的 前序 遍历。 示例 1&#xff1a; 输入&#xff1a;root [1,null,2,3] 输出&#xff1a;[1,2,3]示例 2&#xff1a; …

Datawhale AI 夏令营——AI+逻辑推理——Task4

# Datawhale AI 夏令营 夏令营手册&#xff1a;从零入门 AI 逻辑推理 比赛&#xff1a;第二届世界科学智能大赛逻辑推理赛道&#xff1a;复杂推理能力评估 代码运行平台&#xff1a;魔搭社区 赛题任务 本次任务主要采用大语言模型解决推理任务&#xff0c;如何使用大语言模…

Python3 第六十一课 -- 实例三十

目录 一. 堆排序 二. 计数排序 一. 堆排序 堆排序&#xff08;Heapsort&#xff09;是指利用堆这种数据结构所设计的一种排序算法。堆积是一个近似完全二叉树的结构&#xff0c;并同时满足堆积的性质&#xff1a;即子结点的键值或索引总是小于&#xff08;或者大于&#xff…

Yolov8在RK3588上进行自定义目标检测(二)

best.pt转best.onnx Yolov8在RK3588上进行自定义目标检测(一)已经进行了配置文件修改。接下来可以直接进行模型的转换。 下面是两种转换方法&#xff1a; 1.命令行 yolo export modelbest.pt formatrknn 2.转换脚本 convert_to_onnx.py from ultralytics import YOLOmode…

数据求均值背后的原理 - 最小二乘法

1. 背景 对采集数据求均值是一种常见简单有效的数据处理手段&#xff0c;比如用直尺去测量物体的长度一般情况会多次测量然后计算平均值然后将平均值作为物体的长度&#xff0c;又如我们需要测量某电源的电压也会采取类似的方法&#xff0c;可以说对数据求均值在我们工作生活中…

【时时三省】unity test 测试框架 介绍(适用于C语言进行测试的)

1&#xff0c;关于 unity test 测试框架的介绍 unity test 是 ThrowTheSwitch.org 的一个主要工程。它是专注于为嵌入式工具链而生的C语言单元测试框架。它可以适用于大工程或者小工程都可以。它的核心文件是一个.c文件和两个头文件。 备注&#xff1a; 下载源码地址&#xff…

btslab靶场-通过xss获取他人cookie并利用

目录 安装 通过xss获取cookie cookie利用 安装 下载btslab靶场链接&#xff1a;https://pan.baidu.com/s/1I9ZgzlZEWdobINGQUhy7Jw?pwd8888 提取码&#xff1a;8888 用phpEnv或者phpStudy部署好靶场环境&#xff08;这里就省略了&#xff09; 通过xss获取cookie 先访问…

Apache和nginx!!!!

⼀、Apache 概念 1、概述 最早的 web 服务程序&#xff0c;基于 http 协议提供⽹⻚浏览服务。 2、特点 模块化设置、开放源代码、跨平台应⽤、⽀持多种 web 编程语 ⾔、运⾏稳定。 3、⼯作模式 &#xff08;1&#xff09;Prefork&#xff1a;使⽤进程处理请求&#xff0…

操作系统|day2.进程、线程、协程

文章目录 进程概念特点并行和并发进程之间的通信进程的状态进程的调度基本准则调度方式具体算法 特殊进程 线程概念线程状态转换线程状态线程调度线程同步多线程通信 线程池种类工作流程五种状态拒绝策略参数队列大小 协程概念优势 进程 概念 进程就是正在运行的程序,它会占用…

进阶SpringBoot之 yaml 语法

SpringBoot 使用一个全局的配置文件&#xff0c;名字固定 application.properties 语法结构&#xff1a;keyvalue application.yml 语法结构&#xff1a;key&#xff1a;&#xff08;空格&#xff09;value 配置文件的作用是可以修改 SpringBoot 自动配置的默认值 在 res…