手把手系列!使用 Zilliz Cloud 和 AWS Bedrock 搭建 RAG 應用

檢索增強生成(Retrieval Augemented Generation, RAG)是一種 AI 框架,它通過結合信息檢索和自然語言處理(NLP)能力從而增強文本生成。具體而言,RAG 系統中的語言模型通過一種檢索機制查詢和搜索知識庫或外部數據庫,將最新信息結合到生成的響應中,從而使得最終輸出結果更準確、包含更多上下文。

Zilliz Cloud(https://zilliz.com.cn/cloud)基於 Milvus(https://milvus.io/)向量數據庫構建,提供存儲和處理大規模向量化數據的解決方案,可用於高效管理、分析和檢索數據。開發人員可以利用 Zilliz Cloud 的向量數據庫功能來存儲和搜索海量 Embedding 向量,進一步增強 RAG 應用中的檢索模塊能力。

AWS Bedrock 雲服務(https://aws.amazon.com/cn/bedrock/),提供多種預訓練基礎模型,可用於部署和擴展 NLP 解決方案。開發人員可以通過 AWS Bedrock 將語言生成、理解和翻譯的模型集成到 AI 應用中。此外,AWS Bedrock 還可以針對文本生成相關和具備豐富上下文的響應,從而進一步增加 RAG 應用的能力。

01.使用 Zilliz Cloud 和 AWS Bedrock 搭建 RAG 應用

我們將通過以下示例代碼(https://colab.research.google.com/github/milvus-io/bootcamp/blob/master/bootcamp/RAG/bedrock_langchain_zilliz_rag.ipynb#scrollTo=fHn0m6Y0ytIP),演示如何使用 Zilliz Cloud 與 AWS Bedrock 搭建 RAG 應用。基本流程如圖 1 所示:

圖1. 使用 Zilliz Cloud 與 AWS Bedrock 搭建 RAG 應用的基本流程

#download the packages then import them
! pip install --upgrade --quiet  langchain langchain-core langchain-text-splitters langchain-community langchain-aws bs4 boto3

# For example
import bs4
import boto3

連接至 AWS Bedrock 和 Zilliz Cloud

接着,設置連接 AWS 和 Zilliz Cloud 服務所需的環境變量。您需要提供 AWS 服務地域、訪問密鑰和 Zilliz Cloud 的 Endpoint URI 和 API 密鑰以連接至 AWS Bedrock 和 Zilliz Cloud 服務。

# Set the AWS region and access key environment variables
REGION_NAME = "us-east-1"
AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")

# Set ZILLIZ cloud environment variables
ZILLIZ_CLOUD_URI = os.getenv("ZILLIZ_CLOUD_URI")
ZILLIZ_CLOUD_API_KEY = os.getenv("ZILLIZ_CLOUD_API_KEY")

通過上述提供的訪問憑證,我們創建了一個 boto3 客戶端(https://boto3.amazonaws.com/v1/documentation/api/latest/index.html),用於連接到 AWS Bedrock Runtime 服務並集成 AWS Bedrock 中的語言模型。接着,我們初始化一個 ChatBedrock 實例(https://python.langchain.com/v0.1/docs/integrations/chat/bedrock/),連接到客戶端,並指定使用的語言模型。本教程中我們使用 anthropic.claude-3-sonnet-20240229-v1:0的模型。這一步幫助我們設置了生成文本響應的基礎設施,同時還配置了模型的 temperature 參數,從而控制生成響應的多樣性。BedrockEmbeddings 實例可用於將文本等非結構化數據(https://zilliz.com.cn/glossary/%E9%9D%9E%E7%BB%93%E6%9E%84%E5%8C%96%E6%95%B0%E6%8D%AE)轉化爲向量。

# Create a boto3 client with the specified credentials
client = boto3.client(
    "bedrock-runtime",
    region_name=REGION_NAME,
    aws_access_key_id=AWS_ACCESS_KEY_ID,
    aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
)

# Initialize the ChatBedrock instance for language model operations
llm = ChatBedrock(
    client=client,
    model_id="anthropic.claude-3-sonnet-20240229-v1:0",
    region_name=REGION_NAME,
    model_kwargs={"temperature": 0.1},
)

# Initialize the BedrockEmbeddings instance for handling text embeddings
embeddings = BedrockEmbeddings(client=client, region_name=REGION_NAME)

收集和處理信息

Embedding 模型初始化成功後,下一步是從外部來源加載數據。創建WebBaseLoader 實例(https://python.langchain.com/v0.1/docs/integrations/document_loaders/web_base/)以從指定的網絡來源抓取內容。

本教程中,我們將從 AI agent 相關文章中加載內容。加載器使用 BeautifulSoup(https://www.crummy.com/software/BeautifulSoup/bs4/doc/)的 SoupStrainer 解析網頁的特定部分——即帶有 "post-content"、"post-title" 和 "post-header" 的部分,從而確保只檢索相關內容。然後,加載器從指定的網絡來源檢索文檔,提供了一系列的相關內容以便後續處理。接着,我們使用 RecursiveCharacterTextSplitter 實例(https://python.langchain.com/v0.1/docs/modules/data_connection/document_transformers/recursive_text_splitter/)將檢索到的文檔分割成更小的文本塊。這樣可以使內容變得更方便管理,也可以將這些文本塊傳入到其他組件中,例如文本 Embedding 或語言生成模塊。

# Create a WebBaseLoader instance to load documents from web sources
loader = WebBaseLoader(
    web_paths=("https://lilianweng.github.io/posts/2023-06-23-agent/",),
    bs_kwargs=dict(
        parse_only=bs4.SoupStrainer(
            class_=("post-content", "post-title", "post-header")
        )
    ),
)
# Load documents from web sources using the loader
documents = loader.load()
# Initialize a RecursiveCharacterTextSplitter for splitting text into chunks
text_splitter = RecursiveCharacterTextSplitter(chunk_size=2000, chunk_overlap=200)


# Split the documents into chunks using the text_splitter
docs = text_splitter.split_documents(documents)

生成響應

prompt 模板預先定義了每個響應的結構,可以引導 AI 儘可能使用統計信息和數字,並在缺乏相關知識時避免編造答案。

# Define the prompt template for generating AI responses
PROMPT_TEMPLATE = """
Human: You are a financial advisor AI system, and provides answers to questions by using fact based and statistical information when possible.
Use the following pieces of information to provide a concise answer to the question enclosed in <question> tags.
If you don't know the answer, just say that you don't know, don't try to make up an answer.
<context>
{context}
</context>

<question>
{question}
</question>

The response should be specific and use statistics or numbers when possible.

Assistant:"""
# Create a PromptTemplate instance with the defined template and input variables
prompt = PromptTemplate(
    template=PROMPT_TEMPLATE, input_variables=["context", "question"]
)

初始化 Zilliz vector store,並連接到 Zilliz Cloud 平臺。vector store 負責將文檔轉化成向量,以便後續快速高效地檢索文檔。然後檢索到的文檔經過格式化組織稱成連貫的文本,AI 將相關信息整合到響應中,最終提供高度準確度和相關的答案。

# Initialize Zilliz vector store from the loaded documents and embeddings
vectorstore = Zilliz.from_documents(
    documents=docs,
    embedding=embeddings,
    connection_args={
        "uri": ZILLIZ_CLOUD_URI,
        "token": ZILLIZ_CLOUD_API_KEY,
        "secure": True,
    },
    auto_id=True,
    drop_old=True,
)

# Create a retriever for document retrieval and generation
retriever = vectorstore.as_retriever()

# Define a function to format the retrieved documents
def format_docs(docs):
    return "\n\n".join(doc.page_content for doc in docs)

最後,我們創建一個完整的 RAG 鏈路用於生成 AI 響應。這個鏈路首先從 vector store 中檢索與用戶查詢相關的文檔,通過檢索和格式化,然後將它們傳遞給 prompt template(https://python.langchain.com/v0.1/docs/modules/model_io/prompts/)生成響應結構。然後將這種結構化輸入傳入語言模型,生成連貫的迴應,最終迴應被解析成字符串格式並呈現給用戶,提供準確、富含上下文的答案。

# Define the RAG (Retrieval-Augmented Generation) chain for AI response generation
rag_chain = (
    {"context": retriever | format_docs, "question": RunnablePassthrough()}
    | prompt
    | llm
    | StrOutputParser()
)

# rag_chain.get_graph().print_ascii()

# Invoke the RAG chain with a specific question and retrieve the response
res = rag_chain.invoke("What is self-reflection of an AI Agent?")
print(res)

以下爲示例響應結果:

Self-reflection is a vital capability that allows autonomous AI agents to improve iteratively by analyzing and refining their past actions, decisions, and mistakes. Some key aspects of self-reflection for AI agents include:
1. Evaluating the efficiency and effectiveness of past reasoning trajectories and action sequences to identify potential issues like inefficient planning or hallucinations (generating consecutive identical actions without progress).
2. Synthesizing observations and memories from past experiences into higher-level inferences or summaries to guide future behavior.

02.使用 Zilliz Cloud 和 AWS Bedrock 的優勢

如表 1 所示,Zilliz Cloud 可與 AWS Bedrock 無縫集成,增強 RAG 應用的效率、可擴展性和準確性。開發人員可以利用這兩個服務開發全面的解決方案,處理海量數據集、簡化 RAG 應用流程、提升 RAG 生成響應的準確性。

表1. 使用 Zilliz Cloud 和 AWS Bedrock 的優勢

03.總結

本文主要介紹瞭如何使用 Zilliz Cloud 和 AWS Bedrock 構建 RAG 應用。

基於 Milvus 構建的向量數據庫 Zilliz Cloud 可爲 Embedding 向量提供可擴展的存儲和檢索解決方案,而 AWS Bedrock 則提供了強大的預訓練模型用於語言生成。我們通過示例代碼展示瞭如何連接至 Zilliz Cloud 和 AWS Bedrock、從外部源加載數據、處理和拆分數據,並最終構建一個完整的 RAG 鏈路。本文搭建的 RAG 應用能夠最大限度地減少 LLM 產生幻覺和提供不準確響應的概率,充分發揮了現代 NLP 模型和向量數據庫之間的協同效果。我們希望通過本教程拋磚引玉,幫助大家在搭建 RAG 應用中採用類似的技術。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章