共用方式為


教學課程:使用適用於 PostgreSQL 和 Azure OpenAI 的 Azure 資料庫建立建議系統

本實際作教學課程說明如何使用適用於PostgreSQL的 Azure 資料庫和 Azure OpenAI 來建置推薦應用程式。 建議具有在不同領域的應用。 服務提供者通常會根據先前從客戶和環境收集的歷程記錄和內容資訊,提供其所提供的產品和服務建議。

有各種方式可建立建議系統的模型。 本教學課程會探索最簡單的形式:基於與 (比方說) 先前所購買產品對應的建議。 本教學課程使用 語意搜尋 教學課程所使用的配方數據集。 建議是根據客戶過去喜歡或搜尋的食譜來推薦食譜。

先決條件

  1. 建立 OpenAI 帳戶並 要求存取 Azure OpenAI
  2. 在所需的訂用帳戶中授與 Azure OpenAI 的存取權。
  3. 授與建立 Azure OpenAI 資源及部署模型的權限。
  4. 建立及部署 Azure OpenAI 資源和模型。 部署嵌入模型 text-embedding-ada-002。 複製部署名稱,因為您需要它來建立內嵌。

啟用 azure_ai 和 pgvector 延伸模組

在您可以啟用 azure_aipgvector 於 Azure 資料庫的 PostgreSQL 彈性伺服器執行個體上之前,必須先將它們新增至允許清單。 請執行 SHOW azure.extensions;,以確定它們已正確新增。

然後,您可以連線到目標資料庫並執行 CREATE EXTENSION 命令來安裝擴充功能。 針對您想要讓擴充功能可供使用的每個資料庫,分別重複命令。

CREATE EXTENSION azure_ai;
CREATE EXTENSION vector;

設定 OpenAI 端點和金鑰

在 Azure AI 服務中,在 [資源管理>金鑰和端點] 下,您可以找到 Azure AI 資源的端點和金鑰。 使用端點和其中一個金鑰來啟用 azure_ai 延伸模組以叫用模型部署:

select azure_ai.set_setting('azure_openai.endpoint','https://<endpoint>.openai.azure.com');
select azure_ai.set_setting('azure_openai.subscription_key', '<API Key>');

下載數據

Kaggle 下載資料。

建立資料表

線上到您的伺服器並建立 test 資料庫。 在該資料庫中,使用下列命令來建立您要匯入資料的數據表:

CREATE TABLE public.recipes(
    rid integer NOT NULL,
    recipe_name text,
    prep_time text,
    cook_time text,
    total_time text,
    servings integer,
    yield text,
    ingredients text,
    directions text,
    rating real,
    url text,
    cuisine_path text,
    nutrition text,
    timing text,
    img_src text,
    PRIMARY KEY (rid)
);

匯入資料

在用戶端視窗上設定下列環境變數,將編碼設定為UTF-8。 此步驟是必要的,因為這個特定數據集使用 Windows-1252 編碼。

Rem on Windows
Set PGCLIENTENCODING=utf-8;
# on Unix based operating systems
export PGCLIENTENCODING=utf-8

將數據匯入您建立的數據表。 請注意,此數據集包含標頭數據列。

psql -d <database> -h <host> -U <user> -c "\copy recipes FROM <local recipe data file> DELIMITER ',' CSV HEADER"

新增資料行以儲存內嵌

將內嵌資料列新增至資料表:

ALTER TABLE recipes ADD COLUMN embedding vector(1536);

產生內嵌

使用 azure_ai 擴充功能為您的數據生成嵌入向量。 下列範例會向量化幾個欄位,並串連。

WITH ro AS (
    SELECT ro.rid
    FROM
        recipes ro
    WHERE
        ro.embedding is null
        LIMIT 500
)
UPDATE
    recipes r
SET
    embedding = azure_openai.create_embeddings('text-embedding-ada-002', r.recipe_name||' '||r.cuisine_path||' '||r.ingredients||' '||r.nutrition||' '||r.directions)
FROM
    ro
WHERE
    r.rid = ro.rid;

重複命令,直到沒有其他要處理的數據列為止。

秘訣

使用 LIMIT 值來試試看。 使用高參數值時,語句可能會因 Azure OpenAI 採取的節流措施而中途失敗。 如果語句失敗,請至少等候一分鐘,然後再次執行命令。

為了方便起見,請在資料庫中建立搜尋函式:

create function
    recommend_recipe(sampleRecipeId int, numResults int)
returns table(
            out_recipeName text,
            out_nutrition text,
            out_similarityScore real)
as $$
declare
    queryEmbedding vector(1536);
    sampleRecipeText text;
begin
    sampleRecipeText := (select
                            recipe_name||' '||cuisine_path||' '||ingredients||' '||nutrition||' '||directions
                        from
                            recipes where rid = sampleRecipeId);

    queryEmbedding := (azure_openai.create_embeddings('text-embedding-ada-002',sampleRecipeText));

    return query
    select
        distinct r.recipe_name,
        r.nutrition,
        (r.embedding <=> queryEmbedding)::real as score
    from
        recipes r
    order by score asc limit numResults; -- cosine distance
end $$
language plpgsql;

現在只要叫用函式便可搜尋建議:

select out_recipename, out_similarityscore from recommend_recipe(1, 20); -- search for 20 recipe recommendations that closest to recipeId 1

並探索結果:

            out_recipename             | out_similarityscore
---------------------------------------+---------------------
 Apple Pie by Grandma Ople             |                   0
 Easy Apple Pie                        |          0.05137232
 Grandma's Iron Skillet Apple Pie      |         0.054287136
 Old Fashioned Apple Pie               |         0.058492836
 Apple Hand Pies                       |          0.06449003
 Apple Crumb Pie                       |          0.07290977
 Old-Fashioned Apple Dumplings         |         0.078374185
 Fried Apple Pies                      |          0.07918481
 Apple Pie Filling                     |         0.084320426
 Apple Turnovers                       |          0.08576391
 Dutch Apple Pie with Oatmeal Streusel |          0.08779895
 Apple Crisp - Perfect and Easy        |          0.09170883
 Delicious Cinnamon Baked Apples       |          0.09384012
 Easy Apple Crisp with Pie Filling     |          0.09477234
 Jump Rope Pie                         |          0.09503954
 Easy Apple Strudel                    |         0.095167875
 Apricot Pie                           |          0.09634114
 Easy Apple Crisp with Oat Topping     |          0.09708358
 Baked Apples                          |          0.09826993
 Pear Pie                              |         0.099974394
(20 rows)