次の方法で共有


.NET AI ベクター検索アプリを構築する

このクイック スタートでは、 ベクター ストア でセマンティック検索を実行して、ユーザーのクエリに関連する結果を検索する .NET コンソール アプリを作成します。 ユーザー プロンプトの埋め込みを生成し、それらの埋め込みを使用してベクター データ ストアにクエリを実行する方法について説明します。

ベクター ストア (ベクター データベース) は、セマンティック検索、検索拡張生成 (RAG) などのタスクや、生成型 AI 応答を接地する必要があるその他のシナリオに不可欠です。 リレーショナル データベースとドキュメント データベースは構造化データと半構造化データ用に最適化されていますが、ベクター データベースは、埋め込みベクターとして表されるデータを効率的に格納、インデックス付け、管理できるように構築されています。 その結果、ベクター データベースで使用されるインデックス作成アルゴリズムと検索アルゴリズムは、アプリケーションの下流で使用できるデータを効率的に取得するように最適化されます。

ライブラリについて

アプリは Microsoft.Extensions.AI ライブラリと Microsoft.Extensions.VectorData ライブラリを使用するため、特定の SDK ではなく AI 抽象化を使用してコードを記述できます。 AI 抽象化は、最小限のアプリ変更で基になる AI モデルを変更できる疎結合コードを作成するのに役立ちます。

📦 Microsoft.Extensions.VectorData.Abstractions は、セマンティック カーネルおよびより広範な .NET エコシステムと連携して開発された .NET ライブラリであり、ベクター ストアと対話するための抽象化の統一されたレイヤーを提供します。 Microsoft.Extensions.VectorData.Abstractions の抽象化により、ライブラリの作成者と開発者に次の機能が提供されます。

  • ベクター ストアに対して create-read-update-delete (CRUD) 操作を実行します。
  • ベクター ストアでベクター検索とテキスト検索を使用します。

Microsoft.Extensions.VectorData.Abstractions ライブラリは現在プレビュー段階です。

前提条件

  • .NET 8.0 SDK 以降 - .NET 8.0 SDKをインストールします。
  • このサンプルを実行できるように、OpenAI API キー。

前提条件

アプリを作成する

次の手順を実行して、次の操作を実行できる .NET コンソール アプリを作成します。

  • データ セットの埋め込みを生成して、ベクター ストアを作成して設定します。
  • ユーザー プロンプトの埋め込みを生成します。
  • ユーザー プロンプトの埋め込みを使用してベクター ストアにクエリを実行します。
  • ベクター検索の関連する結果を表示します。
  1. コンピューター上の空のディレクトリで、dotnet new コマンドを使用して新しいコンソール アプリを作成します。

    dotnet new console -o VectorDataAI
    
  2. ディレクトリをアプリ フォルダーに変更します。

    cd VectorDataAI
    
  3. 必要なパッケージをインストールします。

    dotnet add package Azure.Identity
    dotnet add package Azure.AI.OpenAI
    dotnet add package Microsoft.Extensions.AI.OpenAI --prerelease
    dotnet add package Microsoft.Extensions.VectorData.Abstractions --prerelease
    dotnet add package Microsoft.SemanticKernel.Connectors.InMemory --prerelease
    dotnet add package Microsoft.Extensions.Configuration
    dotnet add package Microsoft.Extensions.Configuration.UserSecrets
    dotnet add package System.Linq.AsyncEnumerable
    

    次の一覧では、 VectorDataAI アプリの各パッケージについて説明します。

    dotnet add package Microsoft.Extensions.AI.OpenAI --prerelease
    dotnet add package Microsoft.Extensions.VectorData.Abstractions --prerelease
    dotnet add package Microsoft.SemanticKernel.Connectors.InMemory --prerelease
    dotnet add package Microsoft.Extensions.Configuration
    dotnet add package Microsoft.Extensions.Configuration.UserSecrets
    dotnet add package System.Linq.AsyncEnumerable
    

    次の一覧では、 VectorDataAI アプリの各パッケージについて説明します。

  4. Visual Studio Code (または任意のエディター) でアプリを開きます。

    code .
    

AI サービスを作成する

  1. Azure OpenAI サービスとモデルをプロビジョニングするには、 Azure OpenAI サービス リソースの作成とデプロイ に関する記事の手順を完了します。

  2. ターミナルまたはコマンド プロンプトから、プロジェクト ディレクトリのルートに移動します。

  3. 次のコマンドを実行して、サンプル アプリの Azure OpenAI エンドポイントとモデル名を構成します。

    dotnet user-secrets init
    dotnet user-secrets set AZURE_OPENAI_ENDPOINT <your-Azure-OpenAI-endpoint>
    dotnet user-secrets set AZURE_OPENAI_GPT_NAME <your-Azure-OpenAI-model-name>
    

アプリを設定する

  1. ターミナルまたはコマンド プロンプトから .NET プロジェクトのルートに移動します。

  2. 次のコマンドを実行して、OpenAI API キーをサンプル アプリのシークレットとして構成します。

    dotnet user-secrets init
    dotnet user-secrets set OpenAIKey <your-OpenAI-key>
    dotnet user-secrets set ModelName <your-OpenAI-model-name>
    

モデル名には、 text-embedding-3-smalltext-embedding-3-large などのテキスト埋め込みモデルを指定して、後のセクションでベクター検索用の埋め込みを生成する必要があります。 モデルの埋め込みの詳細については、「 埋め込み」を参照してください。

アプリ コードを追加する

  1. 次のプロパティを使用して、 CloudService という名前の新しいクラスをプロジェクトに追加します。

    using Microsoft.Extensions.VectorData;
    
    namespace VectorDataAI;
    
    internal class CloudService
    {
        [VectorStoreKey]
        public int Key { get; set; }
    
        [VectorStoreData]
        public string Name { get; set; }
    
        [VectorStoreData]
        public string Description { get; set; }
    
        [VectorStoreVector(
            Dimensions: 384,
            DistanceFunction = DistanceFunction.CosineSimilarity)]
        public ReadOnlyMemory<float> Vector { get; set; }
    }
    

    Microsoft.Extensions.VectorDataなどのVectorStoreKeyAttribute属性は、ベクター ストアで使用する場合の各プロパティの処理方法に影響します。 Vector プロパティは、ベクター検索のDescription値のセマンティック意味を表す生成された埋め込みを格納します。

  2. Program.cs ファイルに次のコードを追加して、クラウド サービスのコレクションを記述するデータ セットを作成します。

    List<CloudService> cloudServices =
    [
        new() {
                Key = 0,
                Name = "Azure App Service",
                Description = "Host .NET, Java, Node.js, and Python web applications and APIs in a fully managed Azure service. You only need to deploy your code to Azure. Azure takes care of all the infrastructure management like high availability, load balancing, and autoscaling."
        },
        new() {
                Key = 1,
                Name = "Azure Service Bus",
                Description = "A fully managed enterprise message broker supporting both point to point and publish-subscribe integrations. It's ideal for building decoupled applications, queue-based load leveling, or facilitating communication between microservices."
        },
        new() {
                Key = 2,
                Name = "Azure Blob Storage",
                Description = "Azure Blob Storage allows your applications to store and retrieve files in the cloud. Azure Storage is highly scalable to store massive amounts of data and data is stored redundantly to ensure high availability."
        },
        new() {
                Key = 3,
                Name = "Microsoft Entra ID",
                Description = "Manage user identities and control access to your apps, data, and resources."
        },
        new() {
                Key = 4,
                Name = "Azure Key Vault",
                Description = "Store and access application secrets like connection strings and API keys in an encrypted vault with restricted access to make sure your secrets and your application aren't compromised."
        },
        new() {
                Key = 5,
                Name = "Azure AI Search",
                Description = "Information retrieval at scale for traditional and conversational search applications, with security and options for AI enrichment and vectorization."
        }
    ];
    
  3. 埋め込み AI モデルに要求を送信する IEmbeddingGenerator 実装を作成して構成します。

    // Load the configuration values.
    IConfigurationRoot config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
    string endpoint = config["AZURE_OPENAI_ENDPOINT"];
    string model = config["AZURE_OPENAI_GPT_NAME"];
    
    // Create the embedding generator.
    IEmbeddingGenerator<string, Embedding<float>> generator =
        new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential())
            .GetEmbeddingClient(deploymentName: model)
            .AsIEmbeddingGenerator();
    

    DefaultAzureCredential は、ローカル ツールから認証資格情報を検索します。 Visual Studio または Azure CLI へのサインインに使用したアカウントに Azure AI Developer ロールを割り当てる必要があります。 詳細については、「.NET を使用して Azure AI サービスに対する認証をする」を参照してください。

    // Load the configuration values.
    IConfigurationRoot config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
    string model = config["ModelName"];
    string key = config["OpenAIKey"];
    
    // Create the embedding generator.
    IEmbeddingGenerator<string, Embedding<float>> generator =
        new OpenAIClient(new ApiKeyCredential(key))
          .GetEmbeddingClient(model: model)
          .AsIEmbeddingGenerator();
    
  4. ベクター ストアを作成し、クラウド サービス データを設定します。 IEmbeddingGenerator 実装を使用して、クラウド サービス データ内の各レコードに埋め込みベクターを作成して割り当てます。

    // Create and populate the vector store.
    var vectorStore = new InMemoryVectorStore();
    VectorStoreCollection<int, CloudService> cloudServicesStore =
        vectorStore.GetCollection<int, CloudService>("cloudServices");
    await cloudServicesStore.EnsureCollectionExistsAsync();
    
    foreach (CloudService service in cloudServices)
    {
        service.Vector = await generator.GenerateVectorAsync(service.Description);
        await cloudServicesStore.UpsertAsync(service);
    }
    

    埋め込みとは、各データ レコードのセマンティック意味の数値表現であり、ベクター検索機能と互換性があります。

  5. 検索クエリの埋め込みを作成し、それを使用してベクター ストアでベクター検索を実行します。

    // Convert a search query to a vector
    // and search the vector store.
    string query = "Which Azure service should I use to store my Word documents?";
    ReadOnlyMemory<float> queryEmbedding = await generator.GenerateVectorAsync(query);
    
    IAsyncEnumerable<VectorSearchResult<CloudService>> results =
        cloudServicesStore.SearchAsync(queryEmbedding, top: 1);
    
    await foreach (VectorSearchResult<CloudService> result in results)
    {
        Console.WriteLine($"Name: {result.Record.Name}");
        Console.WriteLine($"Description: {result.Record.Description}");
        Console.WriteLine($"Vector match score: {result.Score}");
    }
    
  6. dotnet run コマンドを使用してアプリを実行します。

    dotnet run
    

    このアプリは、元のクエリに最も関連するクラウド サービスであるベクター検索の上位の結果を出力します。 クエリを変更して、さまざまな検索シナリオを試すことができます。

リソースをクリーンアップする

不要になった場合は、Azure OpenAI リソースとモデルのデプロイを削除します。

  1. Azure Portalで、Azure OpenAI リソースに移動します。
  2. Azure OpenAI リソースを選択し、[削除] を選択します。

次のステップ