使用 LangChain 實作語意搜尋

    在本指南中,您將使用 OpenAI 的文字嵌入來測量文件屬性之間的相似度。然後,您將使用 LangChain 框架無縫整合 Meilisearch 並建立具有語意搜尋的應用程式。

    需求

    本指南假設您對 Python 和 LangChain 有基本的了解。即使是 LangChain 的初學者,也會發現本教學課程容易上手。

    在 Meilisearch Cloud 上,透過您專案的「設定」頁面啟用向量儲存功能。

    A section of the project overview interface titled "Experimental features". There are two options: "Score details" and "Vector store". "Vector store" is turned on.

    如果您使用的是自託管的 Meilisearch 執行個體,請使用 API 路由啟用向量儲存。

    建立應用程式

    為您的應用程式建立一個資料夾,其中包含一個空的 setup.py 檔案。

    在撰寫任何程式碼之前,請安裝必要的依賴項

    pip install langchain openai meilisearch python-dotenv
    

    首先,建立一個 .env 來儲存您的憑證

    # .env
    
    MEILI_HTTP_ADDR="your Meilisearch host"
    MEILI_API_KEY="your Meilisearch API key"
    OPENAI_API_KEY="your OpenAI API key"
    

    現在您已經有了可用的環境變數,請建立一個包含一些樣板程式碼的 setup.py 檔案

    # setup.py
    
    import os
    from dotenv import load_dotenv # remove if not using dotenv
    from langchain.vectorstores import Meilisearch
    from langchain.embeddings.openai import OpenAIEmbeddings
    from langchain.document_loaders import JSONLoader
    
    load_dotenv() # remove if not using dotenv
    
    # exit if missing env vars
    if "MEILI_HTTP_ADDR" not in os.environ:
        raise Exception("Missing MEILI_HTTP_ADDR env var")
    if "MEILI_API_KEY" not in os.environ:
        raise Exception("Missing MEILI_API_KEY env var")
    if "OPENAI_API_KEY" not in os.environ:
        raise Exception("Missing OPENAI_API_KEY env var")
    
    # Setup code will go here 👇
    

    匯入文件和嵌入

    現在專案已準備就緒,請匯入一些文件到 Meilisearch 中。首先,下載這個小的電影資料集

    movies-lite.json

    然後,更新 setup.py 檔案以載入 JSON 並將其儲存在 Meilisearch 中。您還將使用 OpenAI 文字搜尋模型來產生向量嵌入。

    要使用向量搜尋,我們需要設定嵌入器的索引設定。在這種情況下,您使用的是 userProvided 來源,這需要您在 dimensions 欄位中指定向量的大小。OpenAIEmbeddings() 使用的預設模型是 text-embedding-ada-002,其維度為 1,536。

    # setup.py
    
    # previous code
    
    # Load documents
    loader = JSONLoader(
        file_path="./movies-lite.json",
        jq_schema=".[] | {id: .id, overview: .overview, title: .title}",
        text_content=False,
    )
    documents = loader.load()
    print("Loaded {} documents".format(len(documents)))
    
    # Store documents in Meilisearch
    embeddings = OpenAIEmbeddings()
    embedders = { 
            "custom": {
                "source": "userProvided",
                "dimensions": 1536
            }
        }
    embedder_name = "custom" 
    vector_store = Meilisearch.from_documents(documents=documents, embedding=embeddings, embedders=embedders, embedder_name=embedder_name)
    
    print("Started importing documents")
    

    您的 Meilisearch 執行個體現在將包含您的文件。Meilisearch 會以非同步方式執行文件匯入等任務,因此您可能需要稍等一下才能取得文件。請參閱非同步操作說明,以取得有關任務如何運作的詳細資訊。

    您的資料庫現在已填入電影資料集中的資料。建立一個新的 search.py 檔案來進行語意搜尋查詢:使用相似度搜尋來搜尋文件。

    # search.py
    
    import os
    from dotenv import load_dotenv
    from langchain.vectorstores import Meilisearch
    from langchain.embeddings.openai import OpenAIEmbeddings
    import meilisearch
    
    load_dotenv()
    
    # You can use the same code as `setup.py` to check for missing env vars
    
    # Create the vector store
    client = meilisearch.Client(
        url=os.environ.get("MEILI_HTTP_ADDR"),
        api_key=os.environ.get("MEILI_API_KEY"),
    )
    embeddings = OpenAIEmbeddings()
    vector_store = Meilisearch(client=client, embedding=embeddings)
    
    # Make similarity search
    embedder_name = "custom"
    query = "superhero fighting evil in a city at night"
    results = vector_store.similarity_search(
        query=query,
        embedder_name=embedder_name,
        k=3,
    )
    
    # Display results
    for result in results:
        print(result.page_content)
    

    執行 search.py。如果一切正常,您應該會看到類似這樣的輸出

    {"id": 155, "title": "The Dark Knight", "overview": "Batman raises the stakes in his war on crime. With the help of Lt. Jim Gordon and District Attorney Harvey Dent, Batman sets out to dismantle the remaining criminal organizations that plague the streets. The partnership proves to be effective, but they soon find themselves prey to a reign of chaos unleashed by a rising criminal mastermind known to the terrified citizens of Gotham as the Joker."}
    {"id": 314, "title": "Catwoman", "overview": "Liquidated after discovering a corporate conspiracy, mild-mannered graphic artist Patience Phillips washes up on an island, where she's resurrected and endowed with the prowess of a cat -- and she's eager to use her new skills ... as a vigilante. Before you can say \"cat and mouse,\" handsome gumshoe Tom Lone is on her tail."}
    {"id": 268, "title": "Batman", "overview": "Batman must face his most ruthless nemesis when a deformed madman calling himself \"The Joker\" seizes control of Gotham's criminal underworld."}
    

    恭喜 🎉 您已成功使用 Meilisearch 作為 LangChain 向量儲存庫進行相似度搜尋。

    更進一步

    使用 Meilisearch 作為 LangChain 向量儲存庫可讓您載入文件並以不同的方式搜尋它們

    如需其他資訊,請參閱

    Meilisearch Python SDK 文件

    最後,如果您想要在不使用 LangChain 或其混合搜尋功能的情況下使用 Meilisearch 的向量搜尋功能,請參閱專用教學課程