日本熟妇hd丰满老熟妇,中文字幕一区二区三区在线不卡 ,亚洲成片在线观看,免费女同在线一区二区

通過阿里云Milvus和通義千問快速構建基于專屬知識庫的問答系統

更新時間:

本文展示了如何使用阿里云向量檢索Milvus和靈積(Dashscope)提供的通用千問大模型能力,快速構建一個基于專屬知識庫的問答系統。在示例中,我們通過接入靈積的通義千問API及文本嵌入(Embedding)API來實現LLM大模型的相關功能。

前提條件

使用限制

請確保您的運行環境中已安裝Python 3.8或以上版本,以便順利安裝并使用DashScope。

操作流程

準備工作

  1. 安裝相關的依賴庫。

    pip3 install pymilvus tqdm dashscope
  2. 下載所需的知識庫。

    本文示例使用了公開數據集CEC-Corpus。CEC-Corpus數據集包含332篇針對各類突發事件的新聞報道,語料和標注數據,這里我們只需要提取原始的新聞稿文本,并將其向量化后入庫。

    git clone https://github.com/shijiebei2009/CEC-Corpus.git

步驟一:知識庫向量化

  1. 創建embedding.py文件,內容如下所示。

    import os
    import time
    from tqdm import tqdm
    import dashscope
    from dashscope import TextEmbedding
    from pymilvus import connections, FieldSchema, CollectionSchema, DataType, Collection, utility
    
    
    def prepareData(path, batch_size=25):
        batch_docs = []
        for file in os.listdir(path):
            with open(path + '/' + file, 'r', encoding='utf-8') as f:
                batch_docs.append(f.read())
                if len(batch_docs) == batch_size:
                    yield batch_docs
                    batch_docs = []
    
        if batch_docs:
            yield batch_docs
    
    
    def getEmbedding(news):
        model = TextEmbedding.call(
            model=TextEmbedding.Models.text_embedding_v1,
            input=news
        )
        embeddings = [record['embedding'] for record in model.output['embeddings']]
        return embeddings if isinstance(news, list) else embeddings[0]
    
    
    if __name__ == '__main__':
    
        current_path = os.path.abspath(os.path.dirname(__file__))   # 當前目錄
        root_path = os.path.abspath(os.path.join(current_path, '..'))   # 上級目錄
        data_path = f'{root_path}/CEC-Corpus/raw corpus/allSourceText'  # 數據下載git clone https://github.com/shijiebei2009/CEC-Corpus.git
    
        # 配置Dashscope API KEY
        dashscope.api_key = '<YOUR_DASHSCOPE_API_KEY>'
    
        # 配置Milvus參數
        COLLECTION_NAME = 'CEC_Corpus'
        DIMENSION = 1536
        MILVUS_HOST = 'c-97a7d8038fb8****.milvus.aliyuncs.com'
        MILVUS_PORT = '19530'
        USER = 'root'
        PASSWORD = '<password>'
    
        connections.connect(host=MILVUS_HOST, port=MILVUS_PORT, user=USER, password=PASSWORD)
    
        # Remove collection if it already exists
        if utility.has_collection(COLLECTION_NAME):
            utility.drop_collection(COLLECTION_NAME)
    
        # Create collection which includes the id, title, and embedding.
        fields = [
            FieldSchema(name='id', dtype=DataType.INT64, descrition='Ids', is_primary=True, auto_id=False),
            FieldSchema(name='text', dtype=DataType.VARCHAR, description='Text', max_length=4096),
            FieldSchema(name='embedding', dtype=DataType.FLOAT_VECTOR, description='Embedding vectors', dim=DIMENSION)
        ]
        schema = CollectionSchema(fields=fields, description='CEC Corpus Collection')
        collection = Collection(name=COLLECTION_NAME, schema=schema)
    
        # Create an index for the collection.
        index_params = {
            'index_type': 'IVF_FLAT',
            'metric_type': 'L2',
            'params': {'nlist': 1024}
        }
        collection.create_index(field_name="embedding", index_params=index_params)
    
        id = 0
        for news in tqdm(list(prepareData(data_path))):
            ids = [id + i for i, _ in enumerate(news)]
            id += len(news)
    
            vectors = getEmbedding(news)
            # insert Milvus Collection
            for id, vector, doc in zip(ids, vectors, news):
                insert_doc = (doc[:498] + '..') if len(doc) > 500 else doc
                ins = [[id], [insert_doc], [vector]]  # Insert the title id, the text, and the text embedding vector
                collection.insert(ins)
                time.sleep(2)
    

    本文示例涉及以下參數,請您根據實際環境替換。

    參數

    說明

    data_path

    存放CEC-Corpus數據的路徑。

    COLLECTION_NAME

    設置Miluvs Collection名稱,您可以自定義。

    dashscope_api_key

    模型服務靈積的密鑰。您可以在模型服務靈積控制臺的API-KEY管理頁面查看。

    DIMENSION

    向量維度。固定值為1536。

    MILVUS_HOST

    Milvus實例的公網地址。您可以在Milvus實例的實例詳情頁面查看。

    MILVUS_PORT

    Milvus實例的Proxy Port。您可以在Milvus實例的實例詳情頁面查看。默認為19530。

    USER

    配置為創建Milvus實例時,您自定義的用戶。

    PASSWORD

    配置為創建Milvus實例時,您自定義用戶的密碼。

  2. 在Attu中您可以看到已經創建的Collection,具體操作請參見Attu工具管理

    image

在本文示例中,我們將Embedding向量和新聞報道文稿一起存入Milvus中,同時構建索引類型采用了IVF_FLAT,在向量檢索時,同時可以召回原始文稿。

步驟二:向量檢索與知識問答

數據寫入完成后,即可進行快速的向量檢索。在通過提問搜索到相關的知識點后,我們可以按照特定的模板將“提問 + 知識點”作為prompt向LLM發起提問。在這里我們所使用的LLM是通義千問,這是阿里巴巴自主研發的超大規模語言模型,能夠在用戶自然語言輸入的基礎上,通過自然語言理解和語義分析,理解用戶意圖。通過提供盡可能清晰詳細的指令(prompt),可以獲得更符合預期的結果。這些能力都可以通過通義千問來獲得。

本文示例設計的提問模板格式為:請基于我提供的內容回答問題。內容是{___},我的問題是{___},當然您也可以自行設計合適的模板。

創建answer.py文件,內容如下所示。

import os
import dashscope
from dashscope import Generation
from pymilvus import connections, FieldSchema, CollectionSchema, DataType, Collection
from dashscope import TextEmbedding


def getEmbedding(news):
    model = TextEmbedding.call(
        model=TextEmbedding.Models.text_embedding_v1,
        input=news
    )
    embeddings = [record['embedding'] for record in model.output['embeddings']]
    return embeddings if isinstance(news, list) else embeddings[0]

def getAnswer(query, context):
    prompt = f'''請基于```內的報道內容,回答我的問題。
	      ```
	      {context}
	      ```
	      我的問題是:{query}。
    '''

    rsp = Generation.call(model='qwen-turbo', prompt=prompt)
    return rsp.output.text


def search(text):
    # Search parameters for the index
    search_params = {
        "metric_type": "L2"
    }

    results = collection.search(
        data=[getEmbedding(text)],  # Embeded search value
        anns_field="embedding",  # Search across embeddings
        param=search_params,
        limit=1,  # Limit to five results per search
        output_fields=['text']  # Include title field in result
    )

    ret = []
    for hit in results[0]:
        ret.append(hit.entity.get('text'))
    return ret


if __name__ == '__main__':

    current_path = os.path.abspath(os.path.dirname(__file__))   # 當前目錄
    root_path = os.path.abspath(os.path.join(current_path, '..'))   # 上級目錄
    data_path = f'{root_path}/CEC-Corpus/raw corpus/allSourceText'

    # 配置Dashscope API KEY
    dashscope.api_key = '<YOUR_DASHSCOPE_API_KEY>'

    # 配置Milvus參數
    COLLECTION_NAME = 'CEC_Corpus'
    DIMENSION = 1536
    MILVUS_HOST = 'c-97a7d8038fb8****.milvus.aliyuncs.com'
    MILVUS_PORT = '19530'
    USER = 'root'
    PASSWORD = '<password>'

    connections.connect(host=MILVUS_HOST, port=MILVUS_PORT, user=USER, password=PASSWORD)

    fields = [
        FieldSchema(name='id', dtype=DataType.INT64, descrition='Ids', is_primary=True, auto_id=False),
        FieldSchema(name='text', dtype=DataType.VARCHAR, description='Text', max_length=4096),
        FieldSchema(name='embedding', dtype=DataType.FLOAT_VECTOR, description='Embedding vectors', dim=DIMENSION)
    ]
    schema = CollectionSchema(fields=fields, description='CEC Corpus Collection')
    collection = Collection(name=COLLECTION_NAME, schema=schema)

    # Load the collection into memory for searching
    collection.load()

    question = '北京中央電視臺工地發生大火,發生在哪里?出動了多少輛消防車?人員傷亡情況如何?'
    context = search(question)
    answer = getAnswer(question, context)
    print(answer)

運行完成后,針對北京中央電視臺工地發生大火,發生在哪里?出動了多少輛消防車?人員傷亡情況如何?的提問,會得到以下結果。

火災發生在北京市朝陽區東三環中央電視臺新址園區在建的附屬文化中心大樓工地。出動了54輛消防車。目前尚無人員傷亡報告。

相關文檔