Skip to main content
Open In ColabOpen on GitHub

vectara

Vectara 是值得信赖的 AI 助手和代理平台,专注于企业级安全和任务关键型应用的就绪性。 Vectara 无服务器 RAG 即服务通过易于使用的 API 提供了 RAG 的所有组件,包括:

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

更多信息:

本 Notebook 展示了如何使用 Vectara 的 聊天 功能,该功能可自动存储对话历史记录,并确保后续问题能够考虑该历史记录。

设置

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

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

开始使用

开始使用,请执行以下步骤:

  1. 如果您还没有账号,请 注册 免费试用 Vectara。
  2. 在您的账号中,您可以创建一个或多个语料库。每个语料库代表一个区域,用于在输入文档被摄取时存储文本数据。要创建语料库,请使用 “创建语料库” 按钮。然后,您为语料库提供一个名称和描述。您还可以选择定义过滤属性并应用一些高级选项。如果点击您创建的语料库,您可以在顶部看到其名称和语料库 ID。
  3. 接下来,您需要创建 API 密钥来访问语料库。在语料库视图中点击 “访问控制” 选项卡,然后点击 “创建 API 密钥” 按钮。为您密钥命名,并选择您想要查询专用还是查询+索引的密钥。点击“创建”,您现在就拥有一个有效的 API 密钥。请妥善保管此密钥。

要将 LangChain 与 Vectara 结合使用,您需要这两个值:corpus_keyapi_key。 您可以通过两种方式将 VECTARA_API_KEY 提供给 LangChain:

实例化

  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 (
CorpusConfig,
GenerationConfig,
MmrReranker,
SearchConfig,
VectaraQueryConfig,
)

Vectara Chat 详解

在 LangChain 大多数用于创建聊天机器人的场景中,必须集成一个特殊的 memory(记忆)组件,该组件负责维护聊天会话的历史记录,并利用这些历史记录来确保聊天机器人了解对话的上下文。

使用 Vectara Chat,所有这些操作都由 Vectara 在后端自动执行。您可以查阅 Chat 文档了解更多关于其内部实现方式的细节,但在 LangChain 中,您只需在 Vectara 向量存储中启用该功能即可。

让我们看一个例子。首先,我们加载 SOTU 文档(请记住,文本提取和分块都在 Vectara 平台自动完成):

from langchain_community.document_loaders import TextLoader

loader = TextLoader("../document_loaders/example_data/state_of_the_union.txt")
documents = loader.load()

corpus_key = os.getenv("VECTARA_CORPUS_KEY")
vectara = Vectara.from_documents(documents, embedding=None, corpus_key=corpus_key)
API Reference:TextLoader

现在,我们使用 as_chat 方法创建一个 Chat Runnable:

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 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 and noting her experience as a former top litigator in private practice [1].'

以下是使用一些聊天记录提问的示例

bot.invoke("Did he mention who she suceeded?")["answer"]
'Yes, the president mentioned that Ketanji Brown Jackson succeeded Justice Breyer [1].'

流式聊天

当然,聊天机器人界面也支持流式输出。 只需使用 stream 方法代替 invoke 方法:

output = {}
curr_key = None
for chunk in bot.stream("what did he said about the covid?"):
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
The president acknowledged the significant impact of COVID-19 on the nation, expressing understanding of the public's fatigue and frustration. He emphasized the need to view COVID-19 not as a partisan issue but as a serious disease, urging unity among Americans. The president highlighted the progress made, noting that severe cases have decreased significantly, and mentioned new CDC guidelines allowing most Americans to be mask-free. He also pointed out the efforts to vaccinate the nation and provide economic relief, and the ongoing commitment to vaccinate the world [2], [3], [5].

链式调用

为了实现更多功能,你可以使用链式调用。

from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai.chat_models import ChatOpenAI

llm = ChatOpenAI(temperature=0)

prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are a helpful assistant that explains the stuff to a five year old. Vectara is providing the answer.",
),
("human", "{vectara_response}"),
]
)


def get_vectara_response(question: dict) -> str:
"""
Calls Vectara as_chat and returns the answer string. This encapsulates
the Vectara call.
"""
try:
response = bot.invoke(question["question"])
return response["answer"]
except Exception as e:
return "I'm sorry, I couldn't get an answer from Vectara."


# Create the chain
chain = get_vectara_response | prompt | llm | StrOutputParser()


# Invoke the chain
result = chain.invoke({"question": "what did he say about the covid?"})
print(result)
So, the president talked about how the COVID-19 sickness has affected a lot of people in the country. He said that it's important for everyone to work together to fight the sickness, no matter what political party they are in. The president also mentioned that they are working hard to give vaccines to people to help protect them from getting sick. They are also giving money and help to people who need it, like food, housing, and cheaper health insurance. The president also said that they are sending vaccines to many other countries to help people all around the world stay healthy.

API 参考

您可以在 Chat 文档中查看详细信息。