RAG (Retrieval Augmented Generation)简介

文章介绍了RAG(RetrievalAugmentedGeneration)方法,如何利用通用大模型和企业自身的知识库,通过入库、查询和合成,降低中小企业的AI应用成本。高级优化如QueryExpansion和Cross-encodingDeRank也在文中提及。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 背景

目前大模型很多,绝大部分大模型都是通用型大模型,也就是说使用的是标准的数据,比如wikipedia,百度百科,。。。。 中小型企业一般都有自己的知识库,而这些知识库的数据没有在通用型的大模型中被用到或者说训练到。如果中小型企业要适合自己本身业务需要的大模型,当然理想的方法是重新训练数据,而这些数据有其自身业务场景的数据。 现实是自身训练无论是人力成本,数据成本,计算成本都是不可行的。那么一种基于通用大模型,并外挂本地知识库的人工智能方法RAG(Retrieval Augmented Generation)就运用而生。通过这种方法,中小型企业可以用很少的人力,物力,在不改动通用大模型的情况下,就能结合自身需要,为自己的业务场景服务。

2. 框架图和简单介绍

接下来,我们就来介绍RAG。我们先看标准的RAG流程或框架图,然后在下面的文字中介绍两种优化的RAG,我们还会给出处于研究中或朦胧状态的新的RAG的出处或文献参考。本文是基于下面的LLM或RAG课程的总结。【1】【2】【3】。

2.1 入库

那么现在,让我们先看标准的RAG流程或框架图:先是第一步入库,入库就是把原始分本分割,然后每个分割后的短文本,进行分词(chunk),然后向量映射(embedding),最后入库。

                                                        RAG 第一步入库

                                                            图 1

图1 是RAG的第一步,文本入库。库可以是一般数据库,文件系统都可以,我们这里用向量数据库作为例子。像目前的智能客服机器人,一般就是使用向量数据库。

2.1.1 分本分割

其中,文本分割是因为背景提示窗口大小的限制,一般只有几千个Token。Token是指最小的单词,字符和词组的向量。

​​​​​​​

                                                          图 2

我们的原始文件很长,但提示窗口一般只容纳几千个Token,所以,要将文本分割,这个就是文本分割。图2中,我们将一篇长文分割成4篇小文。

2.2 RAG 查询

入库成功以后,就是查询,然后就是augmented,augmented在这里是指将查询和向量数据库查出的结果合成作为一个新的提示,然后查询LLM(大语言模型)。 

 ​​​​​​​​​​​​​​​​​​​​​

                                                                     图 3                                   

从图3中,我们看出框架图组件有向量数据库(Vector Database)和大模型。向量数据库存储着中小企业的业务场景的本地知识库,用户先从向量数据库,就是本地知识库查询,然后将查询的结果作为大模型的输入,进行查询。

2.2.1 提示查询

当我们开始查询时,我们先查询本地知识库,就是向量数据库,然后向量数据库抽取数据,回复提问。就是图3中的第1,2,3步骤。

2.2.2 合成答复和查询

当向量数据库回复后,我们将查询向量数据库的问题和向量数据库的回答合成一个提示,再查询大语言模型。就是图3中的4,5步骤。

2.2.3 大模型回复/completion

合成后的提示输入到大模型中,得到回复/completion,就完成了一次RAG。 

3. 高级/优化的RAG

A. Query expansion

待下文发表

B. Cross-encoding DeRank

待下文发表

4. 处于朦胧时期的高级RAG

                                                图 4

5. 参考资料

[1]. coursera.org:Generative AI with large language model

[2]. deepLearning.ai:Advanced Retrieval for AI with Chroma

[3]. deep learning.ai:   Building and Evaluating Advanced RAG Applications

[4] 领英LLM的一些专栏

沈建军于上海 2024年2月14日周三

2)2024年2月15日小修改

### Retrieval Augmented Generation in NLP Models and Applications #### Definition and Concept Retrieval Augmented Generation (RAG) is a method that integrates retrieval-based and generation-based approaches, particularly useful for tasks requiring the reproduction of specific information. This technique leverages content pertinent to solving an input task as context, enabling more accurate knowledge retrieval which subsequently aids in generating better responses through iterative refinement processes [^1]. In addition, RAG significantly reduces model hallucination by grounding generated outputs on factual data retrieved from external sources or databases [^2]. #### General Process The general process of applying RAG within Natural Language Processing (NLP) involves several key steps: - **Contextual Information Collection**: Gathering relevant documents or pieces of text related to the query. - **Knowledge Retrieval**: Using these collected contexts to find precise facts or statements needed for response formulation. - **Response Generation**: Generating coherent answers based on both the original prompt and the retrieved information. This approach ensures that the final output not only addresses user queries accurately but also remains grounded in verified facts rather than potentially unreliable internal representations learned during training [^1]. #### Implementation Example Below demonstrates how one might implement a simple version of this concept using Python code snippets alongside popular libraries like Hugging Face Transformers for natural language understanding and FAISS for efficient similarity search among large document collections. ```python from transformers import pipeline import faiss import numpy as np def create_index(documents): """Creates an index structure suitable for fast nearest neighbor searches.""" embeddings = get_embeddings_for_documents(documents) dimensionality = len(embeddings[0]) # Initialize Faiss Index Flat L2 distance metric index = faiss.IndexFlatL2(dimensionality) # Add vectors into our searchable space index.add(np.array(embeddings).astype('float32')) return index def retrieve_relevant_contexts(query_embedding, index, top_k=5): """Finds most similar items given a query vector against indexed dataset""" distances, indices = index.search(np.array([query_embedding]).astype('float32'), k=top_k) return [(distances[i], idx) for i,idx in enumerate(indices.flatten())] # Assume `get_embeddings` function exists elsewhere... index = create_index(corpus_of_texts) qa_pipeline = pipeline("question-answering") for doc_id, score in retrieve_relevant_contexts(user_query_vector, index): answer = qa_pipeline(question=user_input, context=corpus_of_texts[doc_id]['text']) print(f"Answer found with relevance {score}: ",answer['answer']) ``` --related questions-- 1. What are some common challenges faced when implementing RAG systems? 2. Can you provide examples where RAG has been successfully applied outside traditional QA settings? 3. How does Graph Retrieval-Augmented Generation differ from standard RAG methods described here? 4. In what ways can integrating knowledge graphs enhance performance in RAG frameworks?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值