LangChain(4)检索增强 Retrieval Augmentation

这篇具有很好参考价值的文章主要介绍了LangChain(4)检索增强 Retrieval Augmentation。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Large Language Models (LLMs) 的能力或者知识来自两方面:模型在训练时候的输入;模型训练好后以提示词方式输入到模型中的知识source knowledge。检索增强就是指后期输入到模型中的附加信息。

文本分段

按顺序安装包:

!pip install -qU \
    datasets==2.12.0 \
    apache_beam \
    mwparserfromhell
 
 !pip install -qU \
  langchain==0.0.162 \
  openai==0.27.7 \
  tiktoken==0.4.0 \
  "pinecone-client[grpc]"==2.2.2
from datasets import load_dataset
# 下载维基百科资料
data = load_dataset("wikipedia", "20220301.simple", split='train[:10000]')

# 分词工具
import tiktoken
tiktoken.encoding_for_model('gpt-3.5-turbo')

import tiktoken
tokenizer = tiktoken.get_encoding('cl100k_base')
# 计算分词后的token数 create the length function
def tiktoken_len(text):
    tokens = tokenizer.encode(
        text,
        disallowed_special=()
    )
    return len(tokens)

# 使用 RecursiveCharacterTextSplitter 将整段文本分割,限定每个片段的最大token数
from langchain.text_splitter import RecursiveCharacterTextSplitter
text_splitter = RecursiveCharacterTextSplitter(
    chunk_size=400,
    chunk_overlap=20,
    length_function=tiktoken_len, #计量token数
    separators=["\n\n", "\n", " ", ""]
)

# 使用方式
chunks = text_splitter.split_text(data[6]['text'])[:3]
# 计算token数
tiktoken_len(chunks[0])

构建 Embedding

import os
# 设置OPENAI_API_KEY  get openai api key from platform.openai.com
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY') or 'OPENAI_API_KEY'

from langchain.embeddings.openai import OpenAIEmbeddings
# 向量化的模型
model_name = 'text-embedding-ada-002'

embed = OpenAIEmbeddings(
    model=model_name,
    openai_api_key=OPENAI_API_KEY
)

# 测试文本
texts = [
    'this is the first chunk of text',
    'then another second chunk of text is here']

res = embed.embed_documents(texts)
print(len(res), len(res[0]))
>>>2 1536 # 向量长度为 1536

存储向量

使用 Pinecone 存储向量。

index_name = 'langchain-retrieval-augmentation'

import pinecone

# find API key in console at app.pinecone.io
PINECONE_API_KEY = os.getenv('PINECONE_API_KEY') or 'PINECONE_API_KEY'
# find ENV (cloud region) next to API key in console
PINECONE_ENVIRONMENT = os.getenv('PINECONE_ENVIRONMENT') or 'PINECONE_ENVIRONMENT'

pinecone.init(
    api_key=YOUR_API_KEY,
    environment=YOUR_ENV
)

if index_name not in pinecone.list_indexes():
    # we create a new index
    pinecone.create_index(
        name=index_name,
        metric='cosine',
        dimension=len(res[0])  # 1536 dim of text-embedding-ada-002
        )

# 连接库索引
index = pinecone.GRPCIndex(index_name)
print(index.describe_index_stats()) # 库索引统计信息

>>>{'dimension': 1536,
 'index_fullness': 0.1,
 'namespaces': {'': {'vector_count': 27437}},
 'total_vector_count': 27437}

按批将数据插入索引库中

from tqdm.auto import tqdm
from uuid import uuid4
# 批量大小
batch_limit = 100

texts = []
metadatas = []

for i, record in enumerate(tqdm(data)):
    # 维基百科中文本原始信息 first get metadata fields for this record
    metadata = {
        'wiki-id': str(record['id']),
        'source': record['url'],
        'title': record['title']
    }
    # 文本分段 now we create chunks from the record text
    record_texts = text_splitter.split_text(record['text'])
    # 为每一个分段文本创建元信息:j第几个片段 text片段文本 其它几个维基百科字段:wiki-id、source、title  create individual metadata dicts for each chunk
    record_metadatas = [{"chunk": j, "text": text, **metadata} for j, text in enumerate(record_texts)]
    # append these to current batches
    texts.extend(record_texts)
    metadatas.extend(record_metadatas)
    # if we have reached the batch_limit we can add texts
    if len(texts) >= batch_limit:
        ids = [str(uuid4()) for _ in range(len(texts))]
        embeds = embed.embed_documents(texts)
        index.upsert(vectors=zip(ids, embeds, metadatas))
        texts = []
        metadatas = []

if len(texts) > 0:
    ids = [str(uuid4()) for _ in range(len(texts))]
    embeds = embed.embed_documents(texts)
    index.upsert(vectors=zip(ids, embeds, metadatas))

向量查询

from langchain.vectorstores import Pinecone

text_field = "text" # 需要查询出来的字段
# 向量化的模型
model_name = 'text-embedding-ada-002'
embed = OpenAIEmbeddings(
    model=model_name,
    openai_api_key=OPENAI_API_KEY
)

# switch back to normal index for langchain
index = pinecone.Index(index_name)

vectorstore = Pinecone(
    index, embed.embed_query, text_field
)

# 查询信息
query = "who was Benito Mussolini?"
vectorstore.similarity_search(
    query,  # our search query
    k=3  # return 3 most relevant docs
)

检索信息结合LLM

from langchain.chains import RetrievalQA

# completion llm
llm = ChatOpenAI(
    openai_api_key=OPENAI_API_KEY,
    model_name='gpt-3.5-turbo',
    temperature=0.0
)

qa = RetrievalQA.from_chain_type(
    llm=llm,
    chain_type="stuff",
    retriever=vectorstore.as_retriever()
)

print(qa.run(query))

>>>'Benito Mussolini was an Italian politician and journalist who served as the Prime Minister of Italy from 1922 until 1943.'

有时 LLM 回答不着边,没有完全按照提供的信息回答,可以通过 RetrievalQAWithSourcesChain 使得回答更可信,模型会返回参考的来源信息

from langchain.chains import RetrievalQAWithSourcesChain

qa_with_sources = RetrievalQAWithSourcesChain.from_chain_type(
    llm=llm,
    chain_type="stuff",
    retriever=vectorstore.as_retriever()
)
print(qa_with_sources(query))

>>>{'question': 'who was Benito Mussolini?',
 'answer': 'Benito Mussolini was an Italian politician and journalist who was the Prime Minister of Italy from 1922 until 1943.', 
 'sources': 'https://simple.wikipedia.org/wiki/Benito%20Mussolini, https://simple.wikipedia.org/wiki/Fascism'}

参考:
Fixing Hallucination with Knowledge Bases
Retrieval Augmentation文章来源地址https://www.toymoban.com/news/detail-594342.html

到了这里,关于LangChain(4)检索增强 Retrieval Augmentation的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 数据增强(Data Augmentation)

    最近写论文需要插入很多图片,为了蒙混过关,找了很多很多数据增强的手段,增强论文的丰富性,大家不要学我哈,反正我把技巧放这儿了!!!哈哈哈哈哈哈哈哈哈 大家都知道在深度学习网络训练中,模型的样本越充足训练出来的网络模型泛化性越强,鲁棒性越高。最好

    2024年02月08日
    浏览(28)
  • 【深度学习每日小知识】Data Augmentation 数据增强

    数据增强是通过对原始数据进行各种转换和修改来人为生成附加数据的过程。这样做是为了增加机器学习模型中训练数据的大小和多样性。 数据增强的主要目标是解决过拟合问题。当模型使用小样本进行训练并过度关注拟合特定数据集中发现的模式时,就会发生过度拟合。因

    2024年01月23日
    浏览(29)
  • 【搜索引擎】Document indexing and retrieval: 文档索引与检索

    作者:禅与计算机程序设计艺术 搜索引擎作为互联网信息获取的一种重要手段之一,无论是在PC、移动端还是电脑上使用,都可以快速找到想要的信息。而对于文档信息的搜索引擎索引构建,则是一个更加复杂的问题。 文档索引与检索(Document Indexing and Retrieval, DIR)的目标是建

    2024年02月08日
    浏览(34)
  • Public Key Retrieval is not allowed 不允许公钥检索

    Public Key Retrieval is not allowed解决方法 AllowPublicKeyRetrieval=True可能允许恶意代理执行MITM攻击以获取明文密码,因此它在默认情况下为False,必须显式启用。 在配置mysql的url时 加上  附 完整 url

    2024年02月15日
    浏览(47)
  • GPT学习笔记-Enterprise Knowledge Retrieval(企业知识检索)--私有知识库的集成

    openai-cookbook/apps/enterprise-knowledge-retrieval at main · openai/openai-cookbook · GitHub 终于看到对于我解决现有问题的例子代码,对于企业私有知识库的集成。 我对\\\"Retrieval\\\"重新理解了一下,源自动词\\\"retrieve\\\",其基本含义是“取回”,“恢复”,或“检索”。在不同的上下文中,\\\"retriev

    2024年02月11日
    浏览(34)
  • Elasticsearch:使用 Open AI 和 Langchain 的 RAG - Retrieval Augmented Generation (一)

    最近看了一个同事的几个视频。他总结的很好。在使用 LangChain 时,根据 LangChain 的官方文档 https://integrations.langchain.com/vectorstores,目前有三种方法可以进行使用:ElasticVectorSearch,ElasticsearchStore 及 ElasticKnnSearch。 我们从上面的 小红心 来看,Elasticsearch 无疑是最受欢迎的向量

    2024年02月03日
    浏览(31)
  • Elasticsearch:使用 Open AI 和 Langchain 的 RAG - Retrieval Augmented Generation (四)

    这篇博客是之前文章: Elasticsearch:使用 Open AI 和 Langchain 的 RAG - Retrieval Augmented Generation (一) Elasticsearch:使用 Open AI 和 Langchain 的 RAG - Retrieval Augmented Generation (二) Elasticsearch:使用 Open AI 和 Langchain 的 RAG - Retrieval Augmented Generation (三) 的续篇。在这篇文章中,我们将学

    2024年02月05日
    浏览(34)
  • Elasticsearch:使用 Open AI 和 Langchain 的 RAG - Retrieval Augmented Generation (三)

    这是继之前文章: Elasticsearch:使用 Open AI 和 Langchain 的 RAG - Retrieval Augmented Generation (一) Elasticsearch:使用 Open AI 和 Langchain 的 RAG - Retrieval Augmented Generation (二) 的续篇。在今天的文章中,我将详述如何使用 ElasticsearchStore。这也是被推荐的使用方法。如果你还没有设置好

    2024年02月08日
    浏览(30)
  • 跨模态检索论文阅读:Dissecting Deep Metric Learning Losses for Image-Text Retrieval(GOAL)

    Dissecting Deep Metric Learning Losses for Image-Text Retrieval 剖析图像文本检索中的深度度量学习损失 2022.10 视觉语义嵌入(VSE)是图像-文本检索中的一种流行的应用方法,它通过学习图像和语言模式之间的联合嵌入空间来保留语义的相似性。三元组损失与硬负值的挖掘已经成为大多数

    2024年02月09日
    浏览(25)
  • 跨模态检索论文阅读:Learnable Pillar-based Re-ranking for Image-Text Retrieval(LeadRR)基于可学习支柱的图像文本检索重排

    图像-文本检索旨在弥合模态鸿沟,根据语义相似性检索跨模态内容。之前的工作通常侧重于成对关系(即一个数据样本是否与另一个样本匹配),但忽略了高阶邻接关系(即多个数据样本之间的匹配结构)。重新排序是一种流行的后处理方法,它揭示了在单模态检索任务中捕

    2024年01月16日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包