0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
会员中心
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

如何手撸一个自有知识库的RAG系统

京东云 来源:jf_75140285 作者:jf_75140285 2024-06-17 14:59 次阅读

RAG通常指的是"Retrieval-Augmented Generation",即“检索增强的生成”。这是一种结合了检索(Retrieval)和生成(Generation)的机器学习模型,通常用于自然语言处理任务,如文本生成、问答系统等。

我们通过一下几个步骤来完成一个基于京东云官网文档的RAG系统

数据收集

建立知识库

向量检索

提示词与模型

数据收集

数据的收集再整个RAG实施过程中无疑是最耗人工的,涉及到收集、清洗、格式化、切分等过程。这里我们使用京东云的官方文档作为知识库的基础。文档格式大概这样:

{
    "content": "DDoS IP高防结合Web应用防火墙方案说明n=======================nnnDDoS IP高防+Web应用防火墙提供三层到七层安全防护体系,应用场景包括游戏、金融、电商、互联网、政企等京东云内和云外的各类型用户。nnn部署架构n====nnn[!["部署架构"]("https://jdcloud-portal.oss.cn-north-1.jcloudcs.com/cn/image/Advanced%20Anti-DDoS/Best-Practice02.png")]("https://jdcloud-portal.oss.cn-north-1.jcloudcs.com/cn/image/Advanced%20Anti-DDoS/Best-Practice02.png")  nnDDoS IP高防+Web应用防火墙的最佳部署架构如下:nnn* 京东云的安全调度中心,通过DNS解析,将用户域名解析到DDoS IP高防CNAME。n* 用户正常访问流量和DDoS攻击流量经过DDoS IP高防清洗,回源至Web应用防火墙。n* 攻击者恶意请求被Web应用防火墙过滤后返回用户源站。n* Web应用防火墙可以保护任何公网的服务器,包括但不限于京东云,其他厂商的云,IDC等nnn方案优势n====nnn1. 用户源站在DDoS IP高防和Web应用防火墙之后,起到隐藏源站IP的作用。n2. CNAME接入,配置简单,减少运维人员工作。nnn",
    "title": "DDoS IP高防结合Web应用防火墙方案说明",
    "product": "DDoS IP高防",
    "url": "https://docs.jdcloud.com/cn/anti-ddos-pro/anti-ddos-pro-and-waf"
}

每条数据是一个包含四个字段的json,这四个字段分别是"content":文档内容;"title":文档标题;"product":相关产品;"url":文档在线地址

向量数据库的选择与Retriever实现

向量数据库是RAG系统的记忆中心。目前市面上开源的向量数据库很多,那个向量库比较好也是见仁见智。本项目中笔者选择则了clickhouse作为向量数据库。选择ck主要有一下几个方面的考虑:

ck再langchain社区的集成实现比较好,入库比较平滑

向量查询支持sql,学习成本较低,上手容易

京东云有相关产品且有专业团队支持,用着放心

文档向量化及入库过程

为了简化文档向量化和检索过程,我们使用了longchain的Retriever工具集
首先将文档向量化,代码如下:

from libs.jd_doc_json_loader import JD_DOC_Loader
from langchain_community.document_loaders import DirectoryLoader

root_dir = "/root/jd_docs"
loader = DirectoryLoader(
    '/root/jd_docs', glob="**/*.json", loader_cls=JD_DOC_Loader)
docs = loader.load()

langchain 社区里并没有提供针对特定格式的装载器,为此,我们自定义了JD_DOC_Loader来实现加载过程

import json
import logging
from pathlib import Path
from typing import Iterator, Optional, Union

from langchain_core.documents import Document

from langchain_community.document_loaders.base import BaseLoader
from langchain_community.document_loaders.helpers import detect_file_encodings

logger = logging.getLogger(__name__)


class JD_DOC_Loader(BaseLoader):
    """Load text file.


    Args:
        file_path: Path to the file to load.

        encoding: File encoding to use. If `None`, the file will be loaded
        with the default system encoding.

        autodetect_encoding: Whether to try to autodetect the file encoding
            if the specified encoding fails.
    """

    def __init__(
        self,
        file_path: Union[str, Path],
        encoding: Optional[str] = None,
        autodetect_encoding: bool = False,
    ):
        """Initialize with file path."""
        self.file_path = file_path
        self.encoding = encoding
        self.autodetect_encoding = autodetect_encoding

    def lazy_load(self) -> Iterator[Document]:
        """Load from file path."""
        text = ""
        from_url = ""
        try:
            with open(self.file_path, encoding=self.encoding) as f:
                doc_data = json.load(f)
                text = doc_data["content"]
                title = doc_data["title"]
                product = doc_data["product"]
                from_url = doc_data["url"]

                # text = f.read()
        except UnicodeDecodeError as e:
            if self.autodetect_encoding:
                detected_encodings = detect_file_encodings(self.file_path)
                for encoding in detected_encodings:
                    logger.debug(f"Trying encoding: {encoding.encoding}")
                    try:
                        with open(self.file_path, encoding=encoding.encoding) as f:
                            text = f.read()
                        break
                    except UnicodeDecodeError:
                        continue
            else:
                raise RuntimeError(f"Error loading {self.file_path}") from e
        except Exception as e:
            raise RuntimeError(f"Error loading {self.file_path}") from e
        # metadata = {"source": str(self.file_path)}
        metadata = {"source": from_url, "title": title, "product": product}
        yield Document(page_content=text, metadata=metadata)

以上代码功能主要是解析json文件,填充Document的page_content字段和metadata字段。

接下来使用langchain 的 clickhouse 向量工具集进行文档入库

import langchain_community.vectorstores.clickhouse as clickhouse
from langchain.embeddings import HuggingFaceEmbeddings

model_kwargs = {"device": "cuda"}
embeddings = HuggingFaceEmbeddings(
    model_name="/root/models/moka-ai-m3e-large", model_kwargs=model_kwargs)

settings = clickhouse.ClickhouseSettings(
    table="jd_docs_m3e_with_url", username="default", password="xxxxxx", host="10.0.1.94")

docsearch = clickhouse.Clickhouse.from_documents(
    docs, embeddings, config=settings)

入库成功后,进行一下检验

import langchain_community.vectorstores.clickhouse as clickhouse
from langchain.embeddings import HuggingFaceEmbeddings

model_kwargs = {"device": "cuda"}~~~~
embeddings = HuggingFaceEmbeddings(
    model_name="/root/models/moka-ai-m3e-large", model_kwargs=model_kwargs)

settings = clickhouse.ClickhouseSettings(
    table="jd_docs_m3e_with_url_splited", username="default", password="xxxx", host="10.0.1.94")
ck_db = clickhouse.Clickhouse(embeddings, config=settings)
ck_retriever = ck_db.as_retriever(
    search_type="similarity_score_threshold", search_kwargs={'score_threshold': 0.9})
ck_retriever.get_relevant_documents("如何创建mysql rds")

有了知识库以后,可以构建一个简单的restful 服务,我们这里使用fastapi做这个事儿

from fastapi import FastAPI
from pydantic import BaseModel
from singleton_decorator import singleton
from langchain_community.embeddings import HuggingFaceEmbeddings
import langchain_community.vectorstores.clickhouse as clickhouse
import uvicorn
import json

app = FastAPI()
app = FastAPI(docs_url=None)
app.host = "0.0.0.0"

model_kwargs = {"device": "cuda"}
embeddings = HuggingFaceEmbeddings(
    model_name="/root/models/moka-ai-m3e-large", model_kwargs=model_kwargs)
settings = clickhouse.ClickhouseSettings(
    table="jd_docs_m3e_with_url_splited", username="default", password="xxxx", host="10.0.1.94")
ck_db = clickhouse.Clickhouse(embeddings, config=settings)
ck_retriever = ck_db.as_retriever(
    search_type="similarity", search_kwargs={"k": 3})


class question(BaseModel):
    content: str


@app.get("/")
async def root():
    return {"ok"}


@app.post("/retriever")
async def retriver(question: question):
    global ck_retriever
    result = ck_retriever.invoke(question.content)
    return result


if __name__ == '__main__':
    uvicorn.run(app='retriever_api:app', host="0.0.0.0",
                port=8000, reload=True)

返回结构大概这样:

[
  {
    "page_content": "云缓存 Redis--Redis迁移解决方案n###RedisSyncer 操作步骤n####数据校验n```nwget   https://github.com/TraceNature/rediscompare/releases/download/v1.0.0/rediscompare-1.0.0-linux-amd64.tar.gznrediscompare compare single2single --saddr "10.0.1.101:6479" --spassword "redistest0102" --taddr "10.0.1.102:6479" --tpassword  "redistest0102" --comparetimes 3nn```  n**Github 地址:** [https://github.com/TraceNature/redissyncer-server]("https://github.com/TraceNature/redissyncer-server")",
    "metadata": {
      "product": "云缓存 Redis",
      "source": "https://docs.jdcloud.com/cn/jcs-for-redis/doc-2",
      "title": "Redis迁移解决方案"
    },
    "type": "Document"
  },
  {
    "page_content": "云缓存 Redis--Redis迁移解决方案n###RedisSyncer 操作步骤n####数据校验n```nwget   https://github.com/TraceNature/rediscompare/releases/download/v1.0.0/rediscompare-1.0.0-linux-amd64.tar.gznrediscompare compare single2single --saddr "10.0.1.101:6479" --spassword "redistest0102" --taddr "10.0.1.102:6479" --tpassword  "redistest0102" --comparetimes 3nn```  n**Github 地址:** [https://github.com/TraceNature/redissyncer-server]("https://github.com/TraceNature/redissyncer-server")",
    "metadata": {
      "product": "云缓存 Redis",
      "source": "https://docs.jdcloud.com/cn/jcs-for-redis/doc-2",
      "title": "Redis迁移解决方案"
    },
    "type": "Document"
  },
  {
    "page_content": "云缓存 Redis--Redis迁移解决方案n###RedisSyncer 操作步骤n####数据校验n```nwget   https://github.com/TraceNature/rediscompare/releases/download/v1.0.0/rediscompare-1.0.0-linux-amd64.tar.gznrediscompare compare single2single --saddr "10.0.1.101:6479" --spassword "redistest0102" --taddr "10.0.1.102:6479" --tpassword  "redistest0102" --comparetimes 3nn```  n**Github 地址:** [https://github.com/TraceNature/redissyncer-server]("https://github.com/TraceNature/redissyncer-server")",
    "metadata": {
      "product": "云缓存 Redis",
      "source": "https://docs.jdcloud.com/cn/jcs-for-redis/doc-2",
      "title": "Redis迁移解决方案"
    },
    "type": "Document"
  }
]

返回一个向量距离最小的list

结合模型和prompt,回答问题

为了节约算力资源,我们选择qwen 1.8B模型,一张v100卡刚好可以容纳一个qwen模型和一个m3e-large embedding 模型

answer 服务

from fastapi import FastAPI
from pydantic import BaseModel
from langchain_community.llms import VLLM
from transformers import AutoTokenizer
from langchain.prompts import PromptTemplate
import requests
import uvicorn
import json
import logging

app = FastAPI()
app = FastAPI(docs_url=None)
app.host = "0.0.0.0"

logger = logging.getLogger()
logger.setLevel(logging.INFO)
to_console = logging.StreamHandler()
logger.addHandler(to_console)


# load model
# model_name = "/root/models/Llama3-Chinese-8B-Instruct"
model_name = "/root/models/Qwen1.5-1.8B-Chat"
tokenizer = AutoTokenizer.from_pretrained(model_name)
llm_llama3 = VLLM(
    model=model_name,
    tokenizer=tokenizer,
    task="text-generation",
    temperature=0.2,
    do_sample=True,
    repetition_penalty=1.1,
    return_full_text=False,
    max_new_tokens=900,
)

# prompt
prompt_template = """
你是一个云技术专家
使用以下检索到的Context回答问题。
如果不知道答案,就说不知道。
用中文回答问题。
Question: {question}
Context: {context}
Answer: 
"""

prompt = PromptTemplate(
    input_variables=["context", "question"],
    template=prompt_template,
)


def get_context_list(q: str):
    url = "http://10.0.0.7:8000/retriever"
    payload = {"content": q}
    res = requests.post(url, json=payload)
    return res.text


class question(BaseModel):
    content: str


@app.get("/")
async def root():
    return {"ok"}


@app.post("/answer")
async def answer(q: question):
    logger.info("invoke!!!")
    global prompt
    global llm_llama3
    context_list_str = get_context_list(q.content)

    context_list = json.loads(context_list_str)
    context = ""
    source_list = []

    for context_json in context_list:
        context = context+context_json["page_content"]
        source_list.append(context_json["metadata"]["source"])
    p = prompt.format(context=context, question=q.content)
    answer = llm_llama3(p)
    result = {
        "answer": answer,
        "sources": source_list
    }
    return result


if __name__ == '__main__':
    uvicorn.run(app='retriever_api:app', host="0.0.0.0",
                port=8888, reload=True)

代码通过使用Retriever接口查找与问题相似的文档,作为context组合prompt推送给模型生成答案。
主要服务就绪后可以开始画一张脸了,使用gradio做个简易对话界面

gradio 服务

import json
import gradio as gr
import requests


def greet(name, intensity):
    return "Hello, " + name + "!" * int(intensity)


def answer(question):
    url = "http://127.0.0.1:8888/answer"
    payload = {"content": question}
    res = requests.post(url, json=payload)
    res_json = json.loads(res.text)
    return [res_json["answer"], res_json["sources"]]


demo = gr.Interface(
    fn=answer,
    # inputs=["text", "slider"],
    inputs=[gr.Textbox(label="question", lines=5)],
    # outputs=[gr.TextArea(label="answer", lines=5),
    #          gr.JSON(label="urls", value=list)]
    outputs=[gr.Markdown(label="answer"),
             gr.JSON(label="urls", value=list)]
)


demo.launch(server_name="0.0.0.0")


审核编辑 黄宇
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • SQL
    SQL
    +关注

    关注

    1

    文章

    742

    浏览量

    43672
  • 数据库
    +关注

    关注

    7

    文章

    3650

    浏览量

    63761
收藏 人收藏

    评论

    相关推荐

    Java开发者LLM实战——使用LangChain4j构建本地RAG系统

    1、引言 由于目前比较火的chatGPT是预训练模型,而训练大模型是需要较长时间(参数越多学习时间越长,保守估计般是几个月,不差钱的可以多用点GPU缩短这个时间),这就导致了它所学习的
    的头像 发表于 07-02 10:32 367次阅读
    Java开发者LLM实战——使用LangChain4j构建本地<b class='flag-5'>RAG</b><b class='flag-5'>系统</b>

    什么是RAGRAG学习和实践经验

    高级的RAG能很大程度优化原始RAG的问题,在索引、检索和生成上都有更多精细的优化,主要的优化点会集中在索引、向量模型优化、检索后处理等模块进行优化
    的头像 发表于 04-24 09:17 343次阅读
    什么是<b class='flag-5'>RAG</b>,<b class='flag-5'>RAG</b>学习和实践经验

    英特尔集成显卡+ChatGLM3大语言模型的企业本地AI知识库部署

    在当今的企业环境中,信息的快速获取和处理对于企业的成功至关重要。为了满足这需求,我们可以将RAG技术与企业本地知识库相结合,以提供实时的、自动生成的信息处理和决策支持。
    的头像 发表于 03-29 11:07 448次阅读
    英特尔集成显卡+ChatGLM3大语言模型的企业本地AI<b class='flag-5'>知识库</b>部署

    利用知识图谱与Llama-Index技术构建大模型驱动的RAG系统(下)

    对于语言模型(LLM)幻觉,知识图谱被证明优于向量数据知识图谱提供更准确、多样化、有趣、逻辑和致的信息,减少了LLM中出现幻觉的可能性。
    的头像 发表于 02-22 14:13 656次阅读
    利用<b class='flag-5'>知识</b>图谱与Llama-Index技术构建大模型驱动的<b class='flag-5'>RAG</b><b class='flag-5'>系统</b>(下)

    阿里云推出企业级大模型RAG系统

    在国际AI大数据峰会上,阿里云重磅推出了企业级大模型检索增强生成(RAG)解决方案。这解决方案旨在为企业提供更强大、更智能的大模型应用工具,帮助企业更有效地利用大数据和人工智能技术。
    的头像 发表于 02-05 09:54 702次阅读

    深入了解RAG技术

    这是任何RAG流程的最后步——基于我们仔细检索的所有上下文和初始用户查询生成答案。最简单的方法可能是将所有获取到的上下文(超过某个相关性阈值的)连同查询次性输入给LLM。
    的头像 发表于 01-17 11:36 1474次阅读
    深入了解<b class='flag-5'>RAG</b>技术

    搜索出生的百川智能大模型RAG爬坑之路总结

    今天对百川的RAG方法进行解读,百川智能具有深厚的搜索背景,来看看他们是怎么爬RAG的坑的吧~
    的头像 发表于 01-05 15:02 1097次阅读
    搜索出生的百川智能大模型<b class='flag-5'>RAG</b>爬坑之路总结

    如何利用OpenVINO加速LangChain中LLM任务

    RAG)任务,LangChain 可以根据问题从已有的知识库中进行检索,并将原始的检索结果和问题并包装为Prompt提示送入 LLM 中,以此获得更加贴近问题需求的答案。
    的头像 发表于 12-05 09:58 553次阅读

    如何基于亚马逊云科技LLM相关工具打造知识库

    背景 本篇将为大家阐述亚马逊云科技大语言模型下沉到具体行业进行场景以及实施案例的介绍,是亚马逊云科技官方《基于智能搜索和大模型打造企业下知识库》系列的第四篇博客。感兴趣的小伙伴可以进入官网深入
    的头像 发表于 11-23 17:53 690次阅读
    如何基于亚马逊云科技LLM相关工具打造<b class='flag-5'>知识库</b>

    了解亚马逊云科技搭建智能搜索大语言模型增强方案的快速部署流程

    背景 知识库需求在各行各业中普遍存在,例如制造业中历史故障知识库、游戏社区平台的内容知识库、电商的商品推荐知识库和医疗健康领域的挂号推荐知识库
    的头像 发表于 11-10 11:08 497次阅读
    了解亚马逊云科技搭建智能搜索大语言模型增强方案的快速部署流程

    借助亚马逊云科技大语言模型等多种服务打造下代企业知识库

    背景 知识库需求在各行各业中普遍存在,例如制造业中历史故障知识库、游戏社区平台的内容知识库、电商的商品推荐知识库和医疗健康领域的挂号推荐知识库
    的头像 发表于 11-02 11:22 479次阅读
    借助亚马逊云科技大语言模型等多种服务打造下<b class='flag-5'>一</b>代企业<b class='flag-5'>知识库</b>

    如何用个人数据知识库构建RAG聊天机器人?

    所有机器学习(ML)项目的第步都是收集所需的数据。本项目中,我们使用网页抓取技术来收集知识库数据。
    的头像 发表于 10-26 15:43 871次阅读
    如何用个人数据<b class='flag-5'>知识库</b>构建<b class='flag-5'>RAG</b>聊天机器人?

    如何使用Rust创建基于ChatGPT的RAG助手

    经常会出现些幻觉,“本正经”地为我们提供些错误答案,没有办法为我们提供专业的意见或指导。那我们如何让 ChatGPT 具备某个专业领域的知识,提升回答的正确率,从而让 Chat
    的头像 发表于 10-24 17:34 738次阅读
    如何使用Rust创建<b class='flag-5'>一</b><b class='flag-5'>个</b>基于ChatGPT的<b class='flag-5'>RAG</b>助手

    大模型外挂知识库优化-大模型辅助向量召回

    用LLM根据用户query生成k“假答案”。(大模型生成答案采用sample模式,保证生成的k答案不样,不懂LLM生成答案原理的同学可以看我这篇文章。此时的回答内容很可能是存在知识
    的头像 发表于 09-08 16:50 1382次阅读
    大模型外挂<b class='flag-5'>知识库</b>优化-大模型辅助向量召回

    中科驭数成为证券基金行业信息技术应用创新知识库首批合作厂商!

    7月20日,证券基金行业信息技术应用 创新中心与中国信息通信研究院携手合作,正式上线了行业信息技术应用创新知识库, 旨在做好对行业信息技术应用创新工作的支撑,加强产业侧和行业机构之间的紧密联系,加强
    的头像 发表于 07-21 18:50 384次阅读
    中科驭数成为证券基金行业信息技术应用创新<b class='flag-5'>知识库</b>首批合作厂商!