Skip to main content
Open In ColabOpen on GitHub

Vectara

Vectara 是可信赖的 AI 助手和代理平台,专注于为企业关键应用做好准备。 Vectara 无服务器 RAG-as-a-service 提供了所有 RAG 的组件,通过易于使用的 API 包括:

  1. 一种从文件(PDF、PPT、DOCX等)中提取文本的方法
  2. 基于机器学习的分块提供了一流的性能。
  3. The Boomerang 模型。
  4. 自己的内部向量数据库,其中存储了文本片段和嵌入向量。
  5. 一个自动将查询编码为嵌入向量的服务,并检索最相关的文本片段,包括对混合搜索的支持以及多种再排序选项如多语言相关性再排序器MMRUDF再排序器
  6. 基于检索到的文档(上下文),生成一个根据这些文档创建的生成性摘要,并包括引用。

对于更多信息,请参阅:

这个笔记本展示了如何在仅将 Vectara 用作向量存储(不涉及摘要)时使用基本的检索功能,包括:similarity_searchsimilarity_search_with_score 以及使用 LangChain 的 as_retriever 功能。

设置

要使用VectaraVectorStore,您首先需要安装合作伙伴包。

!uv pip install -U pip && uv pip install -qU langchain-vectara

Getting Started

要开始,请按照以下步骤操作:

  1. 如果您还没有,请注册免费试用Vectara。
  2. 在您的账户中,您可以创建一个或多个语料库。每个语料库代表一个存储从输入文档导入的文本数据的区域。要创建一个语料库,请使用"Create Corpus"按钮。然后您需要为语料库提供一个名称以及描述。可选地,您可以定义过滤属性并应用一些高级选项。如果您点击您创建的语料库,您可以在顶部看到其名称和语料库ID。
  3. 接下来,您需要创建API密钥以访问语料库。在语料库视图中点击"权限控制"标签页,然后点击"创建API密钥"按钮。给您的密钥命名,并选择您希望的查询仅限或查询+索引选项。点击"创建",现在您就有了一个有效的API密钥。请保密保存此密钥。

要使用LangChain与Vectara配合,您需要拥有这两个值:corpus_keyapi_key。 您可以以两种方式向LangChain提供VECTARA_API_KEY

  1. 在您的环境中包含以下两个变量:VECTARA_API_KEY

    例如,您可以使用os.environ和getpass按照如下方式设置这些变量:

import os
import getpass

os.environ["VECTARA_API_KEY"] = getpass.getpass("Vectara API Key:")
  1. 将它们添加到Vectara向量存储构造函数中:
vectara = Vectara(
vectara_api_key=vectara_api_key
)

在本笔记本中,我们假设它们已经提供在环境中。

import os

os.environ["VECTARA_API_KEY"] = "<VECTARA_API_KEY>"
os.environ["VECTARA_CORPUS_KEY"] = "VECTARA_CORPUS_KEY"

from langchain_vectara import Vectara
from langchain_vectara.vectorstores import (
ChainReranker,
CorpusConfig,
CustomerSpecificReranker,
File,
GenerationConfig,
MmrReranker,
SearchConfig,
VectaraQueryConfig,
)

vectara = Vectara(vectara_api_key=os.getenv("VECTARA_API_KEY"))

首先,我们将国情咨文文本加载到Vectara中。

请注意,我们使用的是add_files接口,不需要进行任何本地处理或分块操作 - Vectara会接收文件内容并执行所有必要的预处理、分块和将文件嵌入其知识库的过程。

在这种情况中它使用了一个.txt文件,但同样的方式也适用于许多其他文件类型

corpus_key = os.getenv("VECTARA_CORPUS_KEY")
file_obj = File(
file_path="../document_loaders/example_data/state_of_the_union.txt",
metadata={"source": "text_file"},
)
vectara.add_files([file_obj], corpus_key)
['state_of_the_union.txt']

Vectara RAG(检索增强生成)

我们现在创建一个VectaraQueryConfig对象来控制检索和总结的选项:

  • 我们启用摘要功能,指定希望LLM挑选出匹配度最高的7个片段,并用英文回答

使用此配置,让我们创建一个包含完整 Vectara RAG 管道的 LangChain Runnable 对象,使用 as_rag 方法:

generation_config = GenerationConfig(
max_used_search_results=7,
response_language="eng",
generation_preset_name="vectara-summary-ext-24-05-med-omni",
enable_factual_consistency_score=True,
)
search_config = SearchConfig(
corpora=[CorpusConfig(corpus_key=corpus_key)],
limit=25,
reranker=ChainReranker(
rerankers=[
CustomerSpecificReranker(reranker_id="rnk_272725719", limit=100),
MmrReranker(diversity_bias=0.2, limit=100),
]
),
)

config = VectaraQueryConfig(
search=search_config,
generation=generation_config,
)

query_str = "what did Biden say?"

rag = vectara.as_rag(config)
rag.invoke(query_str)["answer"]
"President Biden discussed several key issues in his recent statements. He emphasized the importance of keeping schools open and noted that with a high vaccination rate and reduced hospitalizations, most Americans can safely return to normal activities without masks [1]. He addressed the need to hold social media platforms accountable for their impact on children and called for stronger privacy protections and mental health services [2]. Biden also announced measures against Russia, including preventing its central bank from defending the Ruble and targeting Russian oligarchs' assets, as part of efforts to weaken Russia's economy and military [3]. Additionally, he highlighted the importance of protecting women's rights, specifically the right to choose as affirmed in Roe v. Wade [5]. Lastly, he advocated for funding the police with necessary resources and training to ensure community safety [6]."

我们也可以像这样使用流式接口:<br>

output = {}
curr_key = None
for chunk in rag.stream(query_str):
for key in chunk:
if key not in output:
output[key] = chunk[key]
else:
output[key] += chunk[key]
if key == "answer":
print(chunk[key], end="", flush=True)
curr_key = key
President Biden emphasized several key points in his statements. He highlighted the importance of keeping schools open and noted that with a high vaccination rate and reduced hospitalizations, most Americans can safely return to normal activities without masks [1]. He addressed the need to hold social media platforms accountable for their impact on children and called for stronger privacy protections and mental health services [2]. Biden also discussed measures against Russia, including preventing their central bank from defending the Ruble and targeting Russian oligarchs' assets [3]. Additionally, he reaffirmed the commitment to protect women's rights, particularly the right to choose as affirmed in Roe v. Wade [5]. Lastly, he advocated for funding the police to ensure community safety [6].

关于Vectara作为VectorStore的更多细节,请参阅这个笔记本

Vectara Chat

在大多数使用LangChain创建聊天机器人的情况下,必须集成一个特殊的memory组件来维护会话历史,并利用该历史确保聊天机器人了解对话历史。

使用 Vectara 聊天时,所有这些都会在后台自动由 Vectara 完成。

generation_config = GenerationConfig(
max_used_search_results=7,
response_language="eng",
generation_preset_name="vectara-summary-ext-24-05-med-omni",
enable_factual_consistency_score=True,
)
search_config = SearchConfig(
corpora=[CorpusConfig(corpus_key=corpus_key, limit=25)],
reranker=MmrReranker(diversity_bias=0.2),
)

config = VectaraQueryConfig(
search=search_config,
generation=generation_config,
)


bot = vectara.as_chat(config)

bot.invoke("What did the president say about Ketanji Brown Jackson?")["answer"]
'The president stated that nominating someone to serve on the United States Supreme Court is one of the most serious constitutional responsibilities he has. He nominated Circuit Court of Appeals Judge Ketanji Brown Jackson, describing her as one of the nation’s top legal minds who will continue Justice Breyer’s legacy of excellence [1].'

有关 Vectara 聊天的更多详细信息,请< a href=\"0\" >访问此笔记本。

Vectara作为自我查询检索器

Vectara 提供了智能查询重写选项,通过从自然语言查询中自动生成元数据过滤表达式来提升搜索精度。这一功能会分析用户查询,提取相关元数据过滤条件,并重新表述查询以聚焦于核心信息需求。如需了解更多详情,请参见此笔记本

Vectara 工具

Vectara 提供了可以与 Langchain 结合使用的多种工具。如需详细了解,请参阅 此笔记本