文档

通过阿里云Milvus和LangChain快速构建LLM问答系统

更新时间:

本文介绍如何通过整合阿里云Milvus、阿里云DashScope Embedding模型与阿里云PAI(EAS)模型服务,构建一个由LLM(大型语言模型)驱动的问题解答应用,并着重演示了如何搭建基于这些技术的RAG对话系统。

前提条件

使用限制

  • Milvus实例和PAI(EAS)须在相同地域下。

  • 请确保您的运行环境中已安装Python 3.8或以上版本,以便顺利安装并使用DashScope。

方案架构

该方案架构如下图所示,主要包含以下几个处理过程:

  • 知识库预处理:用户可借助LangChain SDK对文本进行分割,作为Embedding模型的输入数据。

  • 知识库存储:选定的Embedding模型(DashScope)负责将输入文本转换为向量,并将这些向量存入阿里云Milvus的向量数据库中。

  • 向量相似性检索:Embedding模型处理用户的查询输入,并将其向量化。随后,利用阿里云Milvus的索引功能来识别出相应的Retrieved文档集。

  • RAG(Retrieval-Augmented Generation)对话验证:用户使用LangChain SDK,并将相似性检索的结果作为上下文,将问题导入到LLM模型(本例中用的是阿里云PAI EAS),以产生最终的回答。此外,结果可以通过将问题直接查询LLM模型得到的答案进行核实。

image

操作流程

  1. 部署对话模型推理服务。

    1. 进入PAI-EAS 模型在线服务页面。

      1. 登录PAI控制台

      2. 在左侧导航栏单击工作空间列表,在工作空间列表页面中单击待操作的工作空间名称,进入对应工作空间内。

      3. 在工作空间页面的左侧导航栏选择模型部署>模型在线服务(EAS),进入PAI-EAS 模型在线服务页面。image.png

    2. PAI-EAS 模型在线服务页面,单击部署服务,在弹出对话框中,选择自定义部署,然后单击确定

    3. 部署服务页面,配置以下关键参数,其余参数可使用默认配置,更多参数详情请参见阿里云大模型RAG对话系统最佳实践

      参数

      描述

      服务名称

      您可以自定义。

      部署方式

      选择镜像部署AI-Web应用

      镜像选择

      PAI平台镜像列表中选择chat-llm-webui,镜像版本选择最新版本即可。

      运行命令

      使用通义千问-7b模型进行部署,对应命令如下所示。

      python webui/webui_server.py --port=8000 --model-path=Qwen/Qwen-7B-Chat

      专有网络配置

      在VPC下拉列表中,选择创建Milvus实例时的VPC、交换机和安全组。您可以在Milvus实例的实例详情页面查看。

    4. 单击部署,等待一段时间即可完成模型部署。

      服务状态运行中时,表明服务部署成功。

    5. 获取VPC地址调用的服务访问地址和Token。

      1. 单击服务名称,进入服务详情页面。

      2. 基本信息区域,单击查看调用信息

      3. 调用信息对话框的VPC地址调用页签,获取服务访问地址和Token,并保存到本地。

  2. (可选)在ECS控制台创建并启动一个开通公网的ECS实例,详情请参见通过控制台使用ECS实例(快捷版)

    该ECS实例用于运行Python文件。您也可以在本地机器执行Python文件,具体请根据您的实际情况做出合适的选择。

  3. 执行以下命令,安装相关依赖库。

    pip3 install pymilvus langchain dashscope beautifulsoup4
    
  4. 创建并执行Python文件,内容如下所示。

    from langchain_community.document_loaders import WebBaseLoader
    from langchain.text_splitter import RecursiveCharacterTextSplitter
    from langchain.vectorstores.milvus import Milvus
    from langchain.schema.runnable import RunnablePassthrough
    from langchain.prompts import PromptTemplate
    from langchain_community.embeddings import DashScopeEmbeddings
    from langchain_community.llms.pai_eas_endpoint import PaiEasEndpoint
    
    # 设置Miluvs Collection名称
    COLLECTION_NAME = 'doc_qa_db'
    
    # 设置向量维度
    DIMENSION = 768
    
    loader = WebBaseLoader([
        'https://milvus.io/docs/overview.md',
        'https://milvus.io/docs/release_notes.md',
        'https://milvus.io/docs/architecture_overview.md',
        'https://milvus.io/docs/four_layers.md',
        'https://milvus.io/docs/main_components.md',
        'https://milvus.io/docs/data_processing.md',
        'https://milvus.io/docs/bitset.md',
        'https://milvus.io/docs/boolean.md',
        'https://milvus.io/docs/consistency.md',
        'https://milvus.io/docs/coordinator_ha.md',
        'https://milvus.io/docs/replica.md',
        'https://milvus.io/docs/knowhere.md',
        'https://milvus.io/docs/schema.md',
        'https://milvus.io/docs/dynamic_schema.md',
        'https://milvus.io/docs/json_data_type.md',
        'https://milvus.io/docs/metric.md',
        'https://milvus.io/docs/partition_key.md',
        'https://milvus.io/docs/multi_tenancy.md',
        'https://milvus.io/docs/timestamp.md',
        'https://milvus.io/docs/users_and_roles.md',
        'https://milvus.io/docs/index.md',
        'https://milvus.io/docs/disk_index.md',
        'https://milvus.io/docs/scalar_index.md',
        'https://milvus.io/docs/performance_faq.md',
        'https://milvus.io/docs/product_faq.md',
        'https://milvus.io/docs/operational_faq.md',
        'https://milvus.io/docs/troubleshooting.md',
    ])
    
    docs = loader.load()
    
    text_splitter = RecursiveCharacterTextSplitter(chunk_size=1024, chunk_overlap=0)
    
    # 使用LangChain将输入文档安照chunk_size切分
    all_splits = text_splitter.split_documents(docs)
    
    # 设置embedding模型为DashScope(可以替换成自己模型)
    
    embeddings = DashScopeEmbeddings(
        model="text-xxxx", dashscope_api_key="your_api_key"
    )
    
    # 创建connection,host为阿里云Milvus的访问域名。
    
    connection_args = {"host": "c-xxxx.milvus.aliyuncs.com", "port": "19530", "user": "your_user", "password": "your_password"}
    # 创建Collection
    vector_store = Milvus(
        embedding_function=embeddings,
        connection_args=connection_args,
        collection_name=COLLECTION_NAME,
        drop_old=True,
    ).from_documents(
        all_splits,
        embedding=embeddings,
        collection_name=COLLECTION_NAME,
        connection_args=connection_args,
    )
    
    # 利用Milvus向量数据库进行相似性检索。
    
    query = "What are the main components of Milvus?"
    docs = vector_store.similarity_search(query)
    print(len(docs))
    
    # 声明LLM 模型为PAI EAS(可以替换成自己模型)。
    
    llm = PaiEasEndpoint(
        eas_service_url="your_pai_eas_url",
        eas_service_token="your_token",
    )
    
    # 将上述相似性检索的结果作为retriever,提出问题输入到LLM之后,获取检索增强之后的回答。
    
    retriever = vector_store.as_retriever()
    
    template = """Use the following pieces of context to answer the question at the end.
    If you don't know the answer, just say that you don't know, don't try to make up an answer.
    Use three sentences maximum and keep the answer as concise as possible.
    Always say "thanks for asking!" at the end of the answer.
    {context}
    Question: {question}
    Helpful Answer:"""
    rag_prompt = PromptTemplate.from_template(template)
    
    rag_chain = (
        {"context": retriever, "question": RunnablePassthrough()}
        | rag_prompt
        | llm
    )
    
    print(rag_chain.invoke("Explain IVF_FLAT in Milvus."))
    

    以下参数请根据实际环境替换。

    参数

    说明

    COLLECTION_NAME

    设置Miluvs Collection名称,您可以自定义。

    model

    模型服务灵积的模型名称。您可以在模型服务灵积控制台的API-KEY管理页面查看。

    本文示例使用的设置Embedding模型为DashScope,您也可以替换成您实际使用的模型。

    dashscope_api_key

    模型服务灵积的密钥。您可以在模型服务灵积控制台的API-KEY管理页面查看。

    connection_args

    • "host":Milvus实例的公网地址。您可以在Milvus实例的实例详情页面查看。

    • "port":Milvus实例的Proxy Port。您可以在Milvus实例的实例详情页面查看。

    • "user":配置为创建Milvus实例时,您自定义的用户。

    • "password":配置为创建Milvus实例时,您自定义用户的密码。

    eas_service_url

    配置为步骤1中获取的服务访问地址。本文示例声明LLM模型为PAI(EAS),您也可以替换成您实际使用的模型。

    eas_service_token

    配置为步骤1中获取的服务Token。

    脚本执行完成后,会返回如下类似信息。

    4
    IVF_FLAT is a type of index in Milvus that divides vector data into nlist cluster units and compares distances between the target input vector and the center of each cluster. It uses a smaller number of clusters than IVF_FLAT, which means it may have slightly higher query time but also requires less memory. The encoded data stored in each unit is consistent with the original data.

相关文档

  • 本页导读 (1)
文档反馈