【RAG探索第3讲】LlamaIndex的API调用与本地部署实战

原文链接:【RAG探索第3讲】LlamaIndex的API调用与本地部署实战

今天是2024年7月5日,星期五,天气晴,北京。 RAG的文章也看不少了,今天给大家带来一个llamaindex的实战。分为两个部分,调用ChatGLM的API来用llamaindex和本地部署qwen1.5使用llamaindex。

  1. LlamaIndex框架调用ChatGLM4 API实现RAG检索
    概述
    LlamaIndex 是一个“数据框架”,可帮助您构建 LLM 应用程序。它提供以下工具:
    (1)提供数据连接器来获取您现有的数据源和数据格式(API、PDF、文档、SQL 等)。
    (2)提供构建数据(索引、图表)的方法,以便这些数据可以轻松地与 LLM 一起使用。
    (3)为您的数据提供高级检索/查询接口:输入任何 LLM 输入提示,获取检索到的上下文和知识增强输出。
    (4)允许轻松与外部应用程序框架集成(例如 LangChain、Flask、Docker、ChatGPT 等)。
    LlamaIndex官网:https://github.com/run-llama/llama_index

在这里插入图片描述
智谱API的获取
官网:https://open.bigmodel.cn
在这里插入图片描述
点击右上角的开发工作台

在这里插入图片描述
点击查看API key

在这里插入图片描述
可在上端开发文档中的接口指南了解该API的使用(这里采用的是langchain框架调用API接口)

在这里插入图片描述
2.实践
本次运行需要通过HuggingFace连接嵌入模型,推荐在本地部署。
(1)创建test.py文件,将以下代码粘进去

from langchain_openai import ChatOpenAI
import jwt
import time
from langchain_core.messages import HumanMessage
from llama_index.core import GPTVectorStoreIndex, SimpleDirectoryReader

from llama_index.embeddings.huggingface import HuggingFaceEmbedding
zhipuai_api_key = "你的智谱API"

def generate_token(apikey: str, exp_seconds: int):
    try:
        id, secret = apikey.split(".")
    except Exception as e:
        raise Exception("invalid apikey", e)

    payload = {
        "api_key": id,
        "exp": int(round(time.time() * 1000)) + exp_seconds * 1000,
        "timestamp": int(round(time.time() * 1000)),
    }

    return jwt.encode(
        payload,
        secret,
        algorithm="HS256",
        headers={"alg": "HS256", "sign_type": "SIGN"},
    )

class ChatZhiPuAI(ChatOpenAI):
    def __init__(self, model_name):
        super().__init__(model_name=model_name, openai_api_key=generate_token(zhipuai_api_key, 10),
                         openai_api_base="https://open.bigmodel.cn/api/paas/v4")

    def invoke(self, question):
        messages = [
            HumanMessage(content=question),
        ]
        return super().invoke(messages)

# 加载数据,需确认数据目录的正确性
documents = SimpleDirectoryReader('data').load_data()
#输出加载后的数据
print("documents:",documents)
# 实例化BAAI/bge-small-en-v1.5模型
baai_embedding = HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5")

# 使用 BAAI/bge-small-en-v1.5 模型初始化GPTVectorStoreIndex
index = GPTVectorStoreIndex.from_documents(documents, embed_model=baai_embedding)

chatglm = ChatZhiPuAI(model_name="glm-4")
query_engine = index.as_query_engine(llm=chatglm)
response = query_engine.query("你的问题")
print(response)

(2)在test的同等目录下创建一个data文件夹用于存放加载的数据,作者这里在data文件夹中放入的是.txt文件用于导入。
(3)运行即可以下为展示结果
数据信息:

在这里插入图片描述
输出信息:

在这里插入图片描述
由此可见,运行成功,输出信息来源于输入的数据。
3. 遇到的Bug以及解决办法
(1)

ImportError: cannot import name 'LangSmithParams' from 'langchain_core.language_models.chat_models' 

经查询:是langchain-openai包损坏,本人出现Bug是包的版本是0.1.13
解决办法: 卸载当前包 pip unstall langchain-openai,安装0.1.7即pip install langchain-openai==0.1.7
参考链接:https://github.com/langchain-ai/langchain/issues/22333
(2)

ModuleNotFoundError: No module named 'llama_index.llms.fireworks'

解决办法:安装该包:pip install llama_index.llms.fireworks
安装失败的话换源试试,本人这里采用的是清华源

但是呢,肯定会有很多人想问,如果我不想用API,或者由于某些原因没办法获得足够的API该怎么办呢?下面提供一种不需要使用官方API,直接部署就可以使用的方法,并以qwen1.5为例子进行展示。

本地部署llamaindex+qwen1.5
本地部署Qwen1.5使用LlamaIndex框架实现RAG

  1. 介绍
    LlamaIndex官网:https://github.com/run-llama/llama_index
    LlamaIndex官网提供了调用OpenAI和Llama的API构建向量存储索引。
  2. 实践
    (1)依赖包
pip install llama-index
pip install llama-index-llms-huggingface
pip install llama-index-embeddings-huggingface
pip install llama-index ipywidgets

(2)下载Qwen1.5以及嵌入模型
嵌入模型:

git clone https://www.modelscope.cn/AI-ModelScope/bge-small-zh-v1.5.git

Qwen1.5:

git clone https://www.modelscope.cn/qwen/Qwen1.5-4B-Chat.git

(3)创建data文件夹并在文件夹内放入相应的数据。本文采取txt格式,信息来自百度百科。

在这里插入图片描述
(4)创建demo.py文件夹并将下列代码粘如

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from llama_index.llms.huggingface import HuggingFaceLLM
from llama_index.core import PromptTemplate
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.core import SimpleDirectoryReader
from llama_index.core import VectorStoreIndex
from llama_index.core import Settings
import os
# os.environ["HF_ENDPOINT"] = "https://hf-mirror.com"
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'

# Model names (make sure you have access on HF)
LLAMA2_13B_CHAT = "/home/data/aaa/llamaindex/Qwen1.5-7B-Chat"

selected_model = LLAMA2_13B_CHAT

SYSTEM_PROMPT = """You are an AI assistant that answers questions in a friendly manner, based on the given source documents. Here are some rules you always follow:
- Generate human readable output, avoid creating output with gibberish text.
- Generate only the requested output, don't include any other language before or after the requested output.
- Never say thank you, that you are happy to help, that you are an AI agent, etc. Just answer directly.
- Generate professional language typically used in business documents in North America.
- Never generate offensive or foul language.
"""

query_wrapper_prompt = PromptTemplate(
    "[INST]<<SYS>>\n" + SYSTEM_PROMPT + "<</SYS>>\n\n{query_str}[/INST] "
)

# Load model and tokenizer with device map
device = "cuda" if torch.cuda.is_available() else "cpu"

tokenizer = AutoTokenizer.from_pretrained(selected_model)
model = AutoModelForCausalLM.from_pretrained(selected_model, device_map="auto")

llm = HuggingFaceLLM(
    context_window=4096,
    max_new_tokens=128,  # Further reduce the number of new tokens generated
    generate_kwargs={
        "temperature": 0,  # Adjusted temperature for more varied responses
        "do_sample": True,  # Enable sampling for more varied responses
    },
    query_wrapper_prompt=query_wrapper_prompt,
    tokenizer_name=selected_model,
    model_name=selected_model,
    device_map="auto"
)

embed_model = HuggingFaceEmbedding(model_name="/home/data/aaa/llamaindex/bge-small-zh-v1.5")

Settings.llm = llm
Settings.embed_model = embed_model

# Load documents
documents = SimpleDirectoryReader("/home/data/aaa/llamaindex/data").load_data()

print("载入的数据-------------")
# print(documents)
print("---------------------")

index = VectorStoreIndex.from_documents(documents)

# Set Logging to DEBUG for more detailed outputs
query_engine = index.as_query_engine()

# Function to clear cache
def clear_cache():
    if torch.cuda.is_available():
        torch.cuda.empty_cache()

clear_cache()

response = query_engine.query("问题?")

print("回答---------------")
print(response)

clear_cache()

注:记得修改模型和数据路径
(4)输出结果
在这里插入图片描述
在这里插入图片描述

总结

本讲内容介绍了LlamaIndex框架的两种使用方法:通过API调用和本地部署,具体包括以下几个方面:

  1. LlamaIndex框架调用ChatGLM4 API实现RAG检索 LlamaIndex是一个帮助构建LLM应用程序的数据框架,提供数据连接器、数据构建方法、高级检索接口以及与外部应用集成的功能。
    获取智谱API的步骤及代码示例,包括API key的生成、数据加载和模型实例化。
    遇到的常见错误及解决方法,如包版本问题和模块缺失问题。
  2. 本地部署LlamaIndex+Qwen1.5实现RAG 提供了本地部署所需的依赖包和下载模型的步骤。
    通过创建示例代码文件,实现了LlamaIndex与Qwen1.5模型的结合,展示了从数据加载到查询响应的完整流程。
    强调了修改模型和数据路径的重要性,并展示了运行结果。

合著作者:USTB-zmh

相关阅读
【RAG探索第3讲】LlamaIndex的API调用与本地部署实战
【RAG探索第2讲】大模型与知识图谱的融合之路:优势互补与协同发展
【RAG探索第1讲】通过大模型读取外部文档的创新探索与自适应策略
大模型名词扫盲贴
RAG实战-QAnything
提升大型语言模型性能的新方法:Query Rewriting技术解析
一文带你学会关键词提取算法—TextRank 和 FastTextRank实践

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-10 19:54:05       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-10 19:54:05       71 阅读
  3. 在Django里面运行非项目文件

    2024-07-10 19:54:05       58 阅读
  4. Python语言-面向对象

    2024-07-10 19:54:05       69 阅读

热门阅读

  1. 【debug】keras使用基础问题

    2024-07-10 19:54:05       18 阅读
  2. Qt 绘图详解

    2024-07-10 19:54:05       23 阅读
  3. MySQL篇七:复合查询

    2024-07-10 19:54:05       26 阅读
  4. [GDOUCTF 2023]Tea writeup

    2024-07-10 19:54:05       27 阅读
  5. 软件开发C#(Sharp)总结(续)

    2024-07-10 19:54:05       17 阅读
  6. CSS 样式链接的多方面应用与最佳实践

    2024-07-10 19:54:05       22 阅读
  7. 西门子7MB2335-0AL00-3AA1

    2024-07-10 19:54:05       19 阅读