次の方法で共有


チュートリアル: Azure Database for PostgreSQL と Azure OpenAI を使用してレコメンデーション システムを作成する

このハンズオン チュートリアルでは、Azure Database for PostgreSQL と Azure OpenAI を使用してレコメンダー アプリケーションを構築する方法について説明します。 推奨事項には、さまざまなドメインにアプリケーションがあります。 サービス プロバイダーは、顧客と環境から収集された以前の履歴とコンテキスト情報に基づいて、提供する製品とサービスに関する推奨事項を提供する傾向があります。

レコメンデーション システムをモデル化するには、さまざまな方法があります。 このチュートリアルでは、最も簡単な形式 (たとえば、以前の購入に対応する製品に基づく推奨事項) について説明します。 このチュートリアルでは、 セマンティック検索のチュートリアル で使用するレシピ データセットを使用します。 お勧めは、顧客が過去に気に入った、または検索したレシピに基づくレシピです。

[前提条件]

  1. OpenAI アカウントを作成し、 Azure OpenAI へのアクセスを要求します。
  2. 目的のサブスクリプションでの権利を Azure OpenAI に与えます。
  3. Azure OpenAI リソースを作成し、モデルをデプロイするためのアクセス許可を付与します。
  4. Azure OpenAI リソースとモデルを作成してデプロイします。 埋め込みモデル text-embedding-ada-002 をデプロイします。 埋め込みを作成する必要があるため、デプロイ名をコピーします。

azure_ai と pgvector の拡張機能を有効にする

Azure Database for PostgreSQL フレキシブル サーバー インスタンスで azure_aipgvector を有効にする前に、 それらを許可リストに追加する必要があります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 によって課される調整により、ステートメントが途中で失敗する可能性があります。 ステートメントが失敗した場合は、少なくとも 1 分間待ってから、コマンドをもう一度実行します。

利便性のため、データベースに検索機能を作成します。

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)