LightRAG 简单使用教程

GitHub - HKUDS/LightRAG: "LightRAG: Simple and Fast Retrieval-Augmented Generation"

安装

官方给了两种方法:

  1. 源码安装
  2. pip安装
# 源码安装

cd LightRAG
pip install -e .

# pip 安装
pip install lightrag-hku

官方推荐源码安装,但我在自己电脑上出现过安装依赖失败的情况,在服务器上没有出现这样的问题,我自己建议pip安装。但源码还需要下载,其中有很多example

├── examples
│   ├── batch_eval.py
│   ├── generate_query.py
│   ├── graph_visual_with_html.py
│   ├── graph_visual_with_neo4j.py
│   ├── lightrag_api_openai_compatible_demo.py
│   ├── lightrag_api_oracle_demo..py
│   ├── lightrag_azure_openai_demo.py
│   ├── lightrag_bedrock_demo.py
│   ├── lightrag_lmdeploy_demo.py
│   ├── lightrag_ollama_demo.py
│   ├── lightrag_openai_compatible_demo.py
│   ├── lightrag_openai_demo.py
│   ├── lightrag_oracle_demo.py
│   ├── lightrag_siliconcloud_demo.py
│   └── vram_management_demo.py

LightRAG提供了很多不同调用大模型的方式,之后再说。

测试文件

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

官方文档中的测试文件是一本小说,名为A Christmas Carol by Charles Dickens。下载时会出现下载失败,注意检查下文件内容,还有文件格式,会出现下载为utf16的文件,后续代码读取会报错,可以

  1. 改下lightrag中读取文件的代码
  2. 直接在vscode右下角改下编码格式,改成utf8

使用

官方给了多种大模型调用方法,主要有

  1. gpt
  2. ollama
  3. openai
  4. huggingface

接下来以GPT为例,讲下它构造图谱的回答问题的流程。

GPT

# 源文件 examples/lightrag_openai_demo.py
import os
from lightrag import LightRAG, QueryParam
from lightrag.llm import gpt_4o_mini_complete, gpt_4o_complete

#########
# Uncomment the below two lines if running in a jupyter notebook to handle the async nature of rag.insert()
# import nest_asyncio
# nest_asyncio.apply()
#########

WORKING_DIR = "./dickens"


if not os.path.exists(WORKING_DIR):
    os.mkdir(WORKING_DIR)

rag = LightRAG(
    working_dir=WORKING_DIR,
    llm_model_func=gpt_4o_mini_complete  # Use gpt_4o_mini_complete LLM model
    # llm_model_func=gpt_4o_complete  # Optionally, use a stronger model
)

with open("./book.txt") as f:
    rag.insert(f.read())

# Perform naive search
print(rag.query("What are the top themes in this story?", param=QueryParam(mode="naive")))

# Perform local search
print(rag.query("What are the top themes in this story?", param=QueryParam(mode="local")))

# Perform global search
print(rag.query("What are the top themes in this story?", param=QueryParam(mode="global")))

# Perform hybrid search
print(rag.query("What are the top themes in this story?", param=QueryParam(mode="hybrid")))

代码封装的很好了

1.首先创建一个文件夹,用于保存文件(log, kv_cache文件,文本块、实体、关系这类的图谱数据)。下表是已经构造后的文件夹,初始为空。

dickens/
├── graph_chunk_entity_relation.graphml
├── kv_store_full_docs.json
├── kv_store_llm_response_cache.json
├── kv_store_text_chunks.json
├── lightrag.log
├── vdb_chunks.json
├── vdb_entities.json
└── vdb_relationships.json

2.之后将文件夹路径,调用LLM的函数,调用embedding的函数作为参数传给LightRAG类,这两个函数都可以改为其他类别。

3.读取文件,rag.insert(f.read())直接把文本转换为图谱,过程会有点长,无需手动保存,文件会自动保存到上面的文件夹路径。

4.问答,它提供了多种维度的问答方式,含义就不说了

  1. naive
  2. local
  3. global
  4. hybrid

Ollama

# 源文件 examples/lightrag_ollama_demo.py
from lightrag.llm import ollama_model_complete, ollama_embedding

rag = LightRAG(
    working_dir=WORKING_DIR,
    llm_model_func=ollama_model_complete,
    llm_model_name="gemma2:2b",
    llm_model_max_async=4,
    llm_model_max_token_size=32768,
    llm_model_kwargs={"host": "http://localhost:11434", "options": {"num_ctx": 32768}},
    embedding_func=EmbeddingFunc(
        embedding_dim=768,
        max_token_size=8192,
        func=lambda texts: ollama_embedding(
            texts, embed_model="nomic-embed-text", host="http://localhost:11434"
        ),
    ),
)

我只展示了和gpt不同的地方,主要是换了LLM和embedding的调用方式,但我在个人电脑上使用ollama很慢,主要在LLM调用方面,半小时完成了不到20个chunk的图谱提取,embedding速度还行。综合来说,不建议在自己电脑不行的情况下用ollama。

Openai

# 源文件 examples/lightrag_openai_compatible_demo.py
async def llm_model_func(
    prompt, system_prompt=None, history_messages=[], **kwargs
) -> str:
    return await openai_complete_if_cache(
        "solar-mini",
        prompt,
        system_prompt=system_prompt,
        history_messages=history_messages,
        api_key=os.getenv("UPSTAGE_API_KEY"),
        base_url="https://api.upstage.ai/v1/solar",
        **kwargs,
    )


async def embedding_func(texts: list[str]) -> np.ndarray:
    return await openai_embedding(
        texts,
        model="solar-embed
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值