共用方式為


教學課程:使用 Azure Cache for Redis 做為語意快取

在本教學課程中,您會使用 Azure Cache for Redis 做為語意快取,並搭配以 AI 為基礎的大型語言模型 (LLM)。 您可以使用 Azure OpenAI 服務來產生對查詢的 LLM 回應,並使用 Azure Cache for Redis 來快取這些回應,以提供更快的回應並降低成本。

因為 Azure Cache for Redis 提供內建向量搜尋功能,因此您也可以執行語意快取。 您可以針對相同的查詢以及針對意義類似 (即使文字不相同也一樣) 的查詢傳回快取的回應。

在本教學課程中,您會了解如何:

  • 建立針對語意快取設定的 Azure Cache for Redis 執行個體
  • 使用 LangChain 其他熱門 Python 程式庫。
  • 使用 Azure OpenAI 服務從 AI 模型產生文字並快取結果。
  • 查看搭配 LLM 使用快取而獲得的效能。

重要

本教學課程將逐步引導您建立 Jupyter Notebook。 您可遵循本教學課程並使用 Python 程式碼檔案 (.py),取得相似結果,但您將必須將本教學課程中的所有程式碼區塊新增至 .py 檔案並執行一次來查看結果。 換言之,Jupyter Notebook 會在執行儲存格時提供中繼結果,但這並非在使用 Python 程式碼檔案時預期會發生的行為。

重要

如果您要改為遵循完成的 Jupyter Notebook,請下載名為 semanticcache.ipynb 的 Jupyter Notebook 檔案,並將其儲存至新的 semanticcache 資料夾。

必要條件

建立 Azure Cache for Redis 執行個體

請遵循快速入門:建立 Redis Enterprise 快取指南。 在 [進階] 頁面上,確認您已新增 RediSearch 模組,並選擇 Enterprise 叢集原則。 所有其他設定都可符合快速入門中所述的預設值。

需要幾分鐘的時間,才能建立快取。 您可以同時繼續下一個步驟。

Screenshot showing the Enterprise tier Basics tab filled out.

設定開發環境

  1. 在名為 semanticcache 的本機電腦上,在您通常儲存專案的位置中建立資料夾。

  2. 在資料夾中建立新的 Python 檔案 (tutorial.py) 或 Jupyter Notebook (tutorial.ipynb)。

  3. 安裝必要 Python 套件:

    pip install openai langchain redis tiktoken
    

建立 Azure OpenAI 模型

請確定您已將兩個模型部署到您的 Azure OpenAI 資源:

  • 提供文字回應的 LLM。 本教學課程使用 GPT-3.5-turbo-instruct 模型。

  • 內嵌模型可將查詢轉換成向量,以便將這些查詢與過去的查詢進行比較。 本教學課程使用 text-embedding-ada-002 (第 2 版) 模型。

如需詳細指示,請參閱部署模型。 記錄您針對每個模型部署選擇的名稱。

匯入程式庫並設定連線資訊

若要成功對 Azure OpenAI 進行呼叫,您需要端點金鑰。 您也需要端點金鑰,才能連線至 Azure Cache for Redis。

  1. 在 Azure 入口網站中前往 Azure OpenAI 資源。

  2. 在 Azure OpenAI 資源的資源管理區段中,找到端點和金鑰。 複製您的端點和存取金鑰,因為您需要這兩者才能驗證 API 呼叫。 範例端點為:https://docs-test-001.openai.azure.com。 您可以使用 KEY1KEY2

  3. 在 Azure 入口網站中,移至 Azure Cache for Redis 資源的 [概觀] 頁面。 複製您的端點。

  4. 在 [設定] 區段中,找到 [存取金鑰]。 複製您的存取金鑰。 您可以使用 PrimarySecondary

  5. 將下列程式碼新增至新的程式碼儲存格:

       # Code cell 2
    
    import openai
    import redis
    import os
    import langchain
    from langchain.llms import AzureOpenAI
    from langchain.embeddings import AzureOpenAIEmbeddings
    from langchain.globals import set_llm_cache
    from langchain.cache import RedisSemanticCache
    import time
    
    
    AZURE_ENDPOINT=<your-openai-endpoint>
    API_KEY=<your-openai-key>
    API_VERSION="2023-05-15"
    LLM_DEPLOYMENT_NAME=<your-llm-model-name>
    LLM_MODEL_NAME="gpt-35-turbo-instruct"
    EMBEDDINGS_DEPLOYMENT_NAME=<your-embeddings-model-name>
    EMBEDDINGS_MODEL_NAME="text-embedding-ada-002"
    
    REDIS_ENDPOINT = <your-redis-endpoint>
    REDIS_PASSWORD = <your-redis-password>
    
    
  6. 使用 Azure OpenAI 部署中的金鑰和端點值來更新 API_KEYRESOURCE_ENDPOINT 的值。

  7. LLM_DEPLOYMENT_NAMEEMBEDDINGS_DEPLOYMENT_NAME 設定為部署在 Azure OpenAI 服務中的兩個模型名稱。

  8. 使用 Azure Cache for Redis 執行個體中的端點和金鑰值以更新 REDIS_ENDPOINTREDIS_PASSWORD

    重要

    強烈建議使用環境變數或祕密管理員 (例如 Azure Key Vault) 以傳入 API 金鑰、端點和部署名稱資訊。 為了簡單起見,會以純文字在此設定這些變數。

  9. 執行程式碼儲存格 2。

初始化 AI 模型

接下來,您會初始化 LLM 和內嵌模型

  1. 將下列程式碼新增至新的程式碼儲存格:

       # Code cell 3
    
    llm = AzureOpenAI(
        deployment_name=LLM_DEPLOYMENT_NAME,
        model_name="gpt-35-turbo-instruct",
        openai_api_key=API_KEY,
        azure_endpoint=AZURE_ENDPOINT,
        openai_api_version=API_VERSION,
    )
    embeddings = AzureOpenAIEmbeddings(
        azure_deployment=EMBEDDINGS_DEPLOYMENT_NAME,
        model="text-embedding-ada-002",
        openai_api_key=API_KEY,
        azure_endpoint=AZURE_ENDPOINT,
        openai_api_version=API_VERSION
    )
    
  2. 執行程式碼儲存格 3。

將 Redis 設定為語意快取

接下來,將 Redis 指定為 LLM 的語意快取。

  1. 將下列程式碼新增至新的程式碼儲存格:

       # Code cell 4
    
    redis_url = "rediss://:" + REDIS_PASSWORD + "@"+ REDIS_ENDPOINT
    set_llm_cache(RedisSemanticCache(redis_url = redis_url, embedding=embeddings, score_threshold=0.05))
    

    重要

    score_threshold 參數的值會決定傳回快取結果所需兩個查詢的相似程度。 數字越低,查詢就必須越類似。 您可以琢磨此值來微調應用程式。

  2. 執行程式碼儲存格 4。

從 LLM 查詢並取得回應

最後,查詢 LLM 以取得 AI 產生的回應。 如果您使用 Jupyter Notebook,則可以在儲存格頂端新增 %%time,以輸出執行程式碼所花費的時間量。

  1. 將下列程式碼新增至新的程式碼儲存格並執行:

    # Code cell 5
    %%time
    response = llm("Please write a poem about cute kittens.")
    print(response)
    

    您應該會看到輸出,而輸出類似如下:

    Fluffy balls of fur,
    With eyes so bright and pure,
    Kittens are a true delight,
    Bringing joy into our sight.
    
    With tiny paws and playful hearts,
    They chase and pounce, a work of art,
    Their innocence and curiosity,
    Fills our hearts with such serenity.
    
    Their soft meows and gentle purrs,
    Are like music to our ears,
    They curl up in our laps,
    And take the stress away in a snap.
    
    Their whiskers twitch, they're always ready,
    To explore and be adventurous and steady,
    With their tails held high,
    They're a sight to make us sigh.
    
    Their tiny faces, oh so sweet,
    With button noses and paw-sized feet,
    They're the epitome of cuteness,
    ...
    Cute kittens, a true blessing,
    In our hearts, they'll always be reigning.
    CPU times: total: 0 ns
    Wall time: 2.67 s
    

    Wall time 會顯示 2.67 秒的值。 這是查詢 LLM 以及 LLM 產生回應所需的真實世界時間。

  2. 再次執行儲存格 5。 您應該會看到完全相同的輸出,但真實時間較小:

    Fluffy balls of fur,
    With eyes so bright and pure,
    Kittens are a true delight,
    Bringing joy into our sight.
    
    With tiny paws and playful hearts,
    They chase and pounce, a work of art,
    Their innocence and curiosity,
    Fills our hearts with such serenity.
    
    Their soft meows and gentle purrs,
    Are like music to our ears,
    They curl up in our laps,
    And take the stress away in a snap.
    
    Their whiskers twitch, they're always ready,
    To explore and be adventurous and steady,
    With their tails held high,
    They're a sight to make us sigh.
    
    Their tiny faces, oh so sweet,
    With button noses and paw-sized feet,
    They're the epitome of cuteness,
    ...
    Cute kittens, a true blessing,
    In our hearts, they'll always be reigning.
    CPU times: total: 0 ns
    Wall time: 575 ms
    

    真實時間似乎以五的倍數縮短,而降至 575 毫秒。

  3. 將查詢從 Please write a poem about cute kittens 變更為 Write a poem about cute kittens,然後再次執行儲存格 5。 您應該會看到完全相同的輸出和較原始查詢降低的真實時間。 即使查詢已變更,查詢的語意意義仍維持不變,因此會傳回相同的快取輸出。 這是語意快取的優點!

變更相似度臨界值

  1. 嘗試以不同的意義執行類似的查詢,例如 Please write a poem about cute puppies。 請注意,快取的結果也會在這裡傳回。 puppies 這個字組的語意意義就足夠接近傳回快取結果的 kittens 字組。

  2. 您可以修改相似度臨界值,以判斷語意快取何時應傳回快取的結果,以及何時應從 LLM 傳回新的輸出。 在程式碼儲存格 4 中,將 score_threshold0.05 變更為 0.01

    # Code cell 4
    
    redis_url = "rediss://:" + REDIS_PASSWORD + "@"+ REDIS_ENDPOINT
    set_llm_cache(RedisSemanticCache(redis_url = redis_url, embedding=embeddings, score_threshold=0.01))
    
  3. 再次嘗試查詢 Please write a poem about cute puppies。 您應該會收到小狗特定的新輸出:

    Oh, little balls of fluff and fur
    With wagging tails and tiny paws
    Puppies, oh puppies, so pure
    The epitome of cuteness, no flaws
    
    With big round eyes that melt our hearts
    And floppy ears that bounce with glee
    Their playful antics, like works of art
    They bring joy to all they see
    
    Their soft, warm bodies, so cuddly
    As they curl up in our laps
    Their gentle kisses, so lovingly
    Like tiny, wet, puppy taps
    
    Their clumsy steps and wobbly walks
    As they explore the world anew
    Their curiosity, like a ticking clock
    Always eager to learn and pursue
    
    Their little barks and yips so sweet
    Fill our days with endless delight
    Their unconditional love, so complete
    ...
    For they bring us love and laughter, year after year
    Our cute little pups, in every way.
    CPU times: total: 15.6 ms
    Wall time: 4.3 s
    

    您可能需要根據應用程式來微調相似度臨界值,以確保在判斷要快取的查詢時,使用正確的敏感度。

清除資源

如果您想要繼續使用在本文中建立的資源,請保留資源群組。

否則,若您已完成資源,則可刪除建立的 Azure 資源群組,以避免衍生費用。

重要

刪除資源群組是無法回復的動作。 當您刪除資源群組時,其中包含的所有資源都將永久刪除。 請確定您不會不小心刪除錯誤的資源群組或資源。 如果您是在包含需保留資源的現有資源群組內部建立資源,則可以個別刪除每個資源,而不必刪除整個資源群組。

刪除資源群組

  1. 登入 Azure 入口網站,然後選取 [資源群組]

  2. 選取您想要刪除的資源群組。

    如果有許多資源群組,請使用 [篩選任何欄位...] 方塊,並輸入您針對本文所建立資源群組的名稱。 選取結果清單中的資源群組。

    Screenshot showing a list of resource groups to delete in the working pane.

  3. 選取 [刪除資源群組]

  4. 系統將會要求您確認是否刪除資源群組。 輸入您的資源群組名稱以進行確認,然後選取 [刪除]

    Screenshot showing a form that requires the resource name to confirm deletion.

不久後,系統便會刪除該資源群組及其所有的資源。