このチュートリアルでは、.NET アプリで Open AI モデルとベクター検索機能を使用した RAG パターンの統合について説明します。 サンプル アプリケーションでは、Azure Cosmos DB for MongoDB に格納されているカスタム データに対してベクター検索を実行し、GPT-35 や GPT-4 などの生成 AI モデルを使用して応答をさらに絞り込みます。 以下のセクションでは、サンプル アプリケーションを設定し、これらの概念を示す主要なコード例について説明します。
[前提条件]
- .NET 8.0
- Azure アカウント
- Azure Cosmos DB for MongoDB vCore(仮想コア) サービス
-
Azure Open AI サービス
- 埋め込み用
text-embedding-ada-002モデルをデプロイする - チャット完了用
gpt-35-turboモデルをデプロイする
- 埋め込み用
アプリの概要
Cosmos レシピ ガイド アプリを使用すると、一連のレシピ データに対してベクター検索と AI 駆動検索を実行できます。 利用可能なレシピを直接検索したり、関連するレシピを見つけるための成分名をアプリに求めたりすることができます。 このアプリとセクションでは、この種類の機能を示すために、次のワークフローについて説明します。
サンプル データを Azure Cosmos DB for MongoDB データベースにアップロードします。
Azure OpenAI
text-embedding-ada-002モデルを使用して、アップロードされたサンプル データの埋め込みとベクター インデックスを作成します。ユーザー プロンプトに基づいてベクトル類似性検索を実行します。
検索結果データに基づいてより意味のある回答を作成するには、Azure OpenAI
gpt-35-turbo入力候補モデルを使用します。
概要
次の GitHub リポジトリを複製します。
git clone https://github.com/microsoft/AzureDataRetrievalAugmentedGenerationSamples.gitC#/CosmosDB-MongoDBvCore フォルダーで、CosmosRecipeGuide.sln ファイルを開きます。
appsettings.json ファイルで、次の構成値を、MongoDb 用の Azure OpenAI と Azure CosmosDB の値に置き換えます。
"OpenAIEndpoint": "https://<your-service-name>.openai.azure.com/", "OpenAIKey": "<your-API-key>", "OpenAIEmbeddingDeployment": "<your-ADA-deployment-name>", "OpenAIcompletionsDeployment": "<your-GPT-deployment-name>", "MongoVcoreConnection": "<your-Mongo-connection-string>"Visual Studio の上部にある [スタート ] ボタンを押して、アプリを起動します。
アプリを探索する
アプリを初めて実行すると、Azure Cosmos DB に接続され、使用可能なレシピがまだないことを報告します。 アプリに表示される手順に従って、コア ワークフローを開始します。
[ レシピを Cosmos DB にアップロード] を 選択し、 Enter キーを押します。 このコマンドは、ローカル プロジェクトからサンプル JSON ファイルを読み取り、Cosmos DB アカウントにアップロードします。
Utility.cs クラスのコードは、ローカル JSON ファイルを解析します。
public static List<Recipe> ParseDocuments(string Folderpath) { List<Recipe> recipes = new List<Recipe>(); Directory.GetFiles(Folderpath) .ToList() .ForEach(f => { var jsonString= System.IO.File.ReadAllText(f); Recipe recipe = JsonConvert.DeserializeObject<Recipe>(jsonString); recipe.id = recipe.name.ToLower().Replace(" ", ""); recipes.Add(recipe); } ); return recipes; }VCoreMongoService.cs ファイルの
UpsertVectorAsyncメソッドは、ドキュメントを Azure Cosmos DB for MongoDB にアップロードします。public async Task UpsertVectorAsync(Recipe recipe) { BsonDocument document = recipe.ToBsonDocument(); if (!document.Contains("_id")) { Console.WriteLine("UpsertVectorAsync: Document does not contain _id."); throw new ArgumentException("UpsertVectorAsync: Document does not contain _id."); } string? _idValue = document["_id"].ToString(); try { var filter = Builders<BsonDocument>.Filter.Eq("_id", _idValue); var options = new ReplaceOptions { IsUpsert = true }; await _recipeCollection.ReplaceOneAsync(filter, document, options); } catch (Exception ex) { Console.WriteLine($"Exception: UpsertVectorAsync(): {ex.Message}"); throw; } }[ Vectorize the recipe(s)]\(レシピのベクター化\) を選択し、Cosmos DB に保存します。
Cosmos DB にアップロードされた JSON 項目には埋め込みがないため、ベクター検索による RAG 用に最適化されていません。 埋め込みは、テキストのセマンティック意味の情報密度の高い数値表現です。 ベクター検索では、コンテキストに似た埋め込みを持つ項目を検索できます。
OpenAIService.cs ファイルの
GetEmbeddingsAsyncメソッドは、データベース内の各項目の埋め込みを作成します。public async Task<float[]?> GetEmbeddingsAsync(dynamic data) { try { EmbeddingsOptions options = new EmbeddingsOptions(data) { Input = data }; var response = await _openAIClient.GetEmbeddingsAsync(openAIEmbeddingDeployment, options); Embeddings embeddings = response.Value; float[] embedding = embeddings.Data[0].Embedding.ToArray(); return embedding; } catch (Exception ex) { Console.WriteLine($"GetEmbeddingsAsync Exception: {ex.Message}"); return null; } }VCoreMongoService.cs ファイル内の
CreateVectorIndexIfNotExistsによってベクター インデックスが作成され、ベクターの類似性検索を実行できます。public void CreateVectorIndexIfNotExists(string vectorIndexName) { try { //Find if vector index exists in vectors collection using (IAsyncCursor<BsonDocument> indexCursor = _recipeCollection.Indexes.List()) { bool vectorIndexExists = indexCursor.ToList().Any(x => x["name"] == vectorIndexName); if (!vectorIndexExists) { BsonDocumentCommand<BsonDocument> command = new BsonDocumentCommand<BsonDocument>( BsonDocument.Parse(@" { createIndexes: 'Recipe', indexes: [{ name: 'vectorSearchIndex', key: { embedding: 'cosmosSearch' }, cosmosSearchOptions: { kind: 'vector-ivf', numLists: 5, similarity: 'COS', dimensions: 1536 } }] }")); BsonDocument result = _database.RunCommand(command); if (result["ok"] != 1) { Console.WriteLine("CreateIndex failed with response: " + result.ToJson()); } } } } catch (MongoException ex) { Console.WriteLine("MongoDbService InitializeVectorIndex: " + ex.Message); throw; } }アプリケーションで Ask AI Assistant (名前または説明でレシピを検索するか、質問する) オプションを選択して、ユーザー クエリを実行します。
ユーザー クエリは、Open AI サービスと埋め込みモデルを使用して埋め込みに変換されます。 その後、埋め込みは Azure Cosmos DB for MongoDB に送信され、ベクター検索の実行に使用されます。
VectorSearchAsyncファイル内の メソッドは、ベクター検索を実行して、指定されたベクターに近いベクターを検索し、Azure Cosmos DB for MongoDB 仮想コアからドキュメントの一覧を返します。public async Task<List<Recipe>> VectorSearchAsync(float[] queryVector) { List<string> retDocs = new List<string>(); string resultDocuments = string.Empty; try { //Search Azure Cosmos DB for MongoDB vCore collection for similar embeddings //Project the fields that are needed BsonDocument[] pipeline = new BsonDocument[] { BsonDocument.Parse( @$"{{$search: {{ cosmosSearch: {{ vector: [{string.Join(',', queryVector)}], path: 'embedding', k: {_maxVectorSearchResults}}}, returnStoredSource:true }} }}"), BsonDocument.Parse($"{{$project: {{embedding: 0}}}}"), }; var bsonDocuments = await _recipeCollection .Aggregate<BsonDocument>(pipeline).ToListAsync(); var recipes = bsonDocuments .ToList() .ConvertAll(bsonDocument => BsonSerializer.Deserialize<Recipe>(bsonDocument)); return recipes; } catch (MongoException ex) { Console.WriteLine($"Exception: VectorSearchAsync(): {ex.Message}"); throw; } }GetChatCompletionAsyncメソッドは、ユーザー プロンプトと関連するベクター検索結果に基づいて、チャット完了応答を改善します。public async Task<(string response, int promptTokens, int responseTokens)> GetChatCompletionAsync(string userPrompt, string documents) { try { ChatMessage systemMessage = new ChatMessage( ChatRole.System, _systemPromptRecipeAssistant + documents); ChatMessage userMessage = new ChatMessage( ChatRole.User, userPrompt); ChatCompletionsOptions options = new() { Messages = { systemMessage, userMessage }, MaxTokens = openAIMaxTokens, Temperature = 0.5f, //0.3f, NucleusSamplingFactor = 0.95f, FrequencyPenalty = 0, PresencePenalty = 0 }; Azure.Response<ChatCompletions> completionsResponse = await openAIClient.GetChatCompletionsAsync(openAICompletionDeployment, options); ChatCompletions completions = completionsResponse.Value; return ( response: completions.Choices[0].Message.Content, promptTokens: completions.Usage.PromptTokens, responseTokens: completions.Usage.CompletionTokens ); } catch (Exception ex) { string message = $"OpenAIService.GetChatCompletionAsync(): {ex.Message}"; Console.WriteLine(message); throw; } }また、このアプリでは、プロンプト エンジニアリングを使用して Open AI サービスの制限を確保し、提供されたレシピの応答を書式設定します。
//System prompts to send with user prompts to instruct the model for chat session private readonly string _systemPromptRecipeAssistant = @" You are an intelligent assistant for Contoso Recipes. You are designed to provide helpful answers to user questions about recipes, cooking instructions provided in JSON format below. Instructions: - Only answer questions related to the recipe provided below. - Don't reference any recipe not provided below. - If you're unsure of an answer, say ""I don't know"" and recommend users search themselves. - Your response should be complete. - List the Name of the Recipe at the start of your response followed by step by step cooking instructions. - Assume the user is not an expert in cooking. - Format the content so that it can be printed to the Command Line console. - In case there is more than one recipe you find, let the user pick the most appropriate recipe.";
.NET