使用矢量搜索在 .NET 应用中实现包含 RAG 的 Azure OpenAI

本教程探讨在 .NET 应用中使用 OpenAI 模型和矢量搜索功能的 RAG 模式的集成。 示例应用程序对存储在 Azure DocumentDB 中的自定义数据执行矢量搜索,并使用生成式 AI 模型(如 gpt-5)进一步优化响应。 在后面的部分中,你将设置一个示例应用程序并浏览演示这些概念的关键代码示例。

先决条件

应用概述

借助 Cosmos 食谱指南应用,你可以针对一组食谱数据执行矢量和 AI 驱动的搜索。 直接搜索可用的食谱或提示应用使用成分名称查找相关食谱。 前面的应用和各部分将指导你完成以下工作流,以演示这种类型的功能:

  1. 将示例数据上传到 Azure DocumentDB 数据库。

  2. 使用 Azure OpenAI text-embedding-3-small 模型为上传的示例数据创建嵌入和矢量索引。

  3. 根据用户提示执行矢量相似性搜索。

  4. 使用 Azure OpenAI gpt-35-turbo 完成模型根据搜索结果数据撰写更有意义的答案。

    显示正在运行的示例应用的屏幕截图。

开始

  1. 克隆以下 GitHub 存储库:

    git clone https://github.com/microsoft/AzureDataRetrievalAugmentedGenerationSamples.git
    
  2. 在 C#/CosmosDB-MongoDBvCore 文件夹中,打开 CosmosRecipeGuide.sln 文件。

  3. 在 appsettings.json 文件中,将以下配置值替换为 Azure OpenAI 和 Azure DocumentDB 值:

    "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>"
    
  4. 通过按 Visual Studio 顶部的 “开始 ”按钮启动应用。

浏览应用

首次运行应用时,它将连接到 Azure DocumentDB,并报告尚没有可用的食谱。 按照应用显示的步骤开始核心工作流。

  1. 选择“ 将食谱上传到 Cosmos DB” ,然后按 Enter。 此命令从本地项目读取示例 JSON 文件,并将其上传到 Azure DocumentDB 群集。

    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;
    }
    

    UpsertVectorAsync VCoreMongoService.cs文件中的该方法将文档上传到 Azure DocumentDB。

    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;
            }
        }
    
  2. 选择 向量化食谱并将其存储在 Cosmos DB 中。

    上传到 Azure DocumentDB 的 JSON 项不包含嵌入,因此不会通过矢量搜索针对 RAG 进行优化。 嵌入是一段文本语义含义的信息密集的数字表示形式。 矢量搜索可以查找上下文类似的嵌入项。

    GetEmbeddingsAsync OpenAIService.cs文件中的方法为数据库中的每一项创建嵌入。

    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;
        }
    }
    
  3. 在应用中选择 “询问 AI 助手”(按名称或说明搜索食谱或提出问题) 选项以运行用户查询。

    应用使用 OpenAI 服务和嵌入模型将用户查询转换为嵌入,然后将嵌入发送到 Azure DocumentDB 来执行矢量搜索。 VCoreMongoService.cs 文件中的 SearchAsync 方法执行向量搜索,以查找与所提供向量接近的向量,并返回 Azure DocumentDB 中的文档列表。

    public async Task<List<Recipe>> VectorSearchAsync(float[] queryVector)
        {
            List<string> retDocs = new List<string>();
            string resultDocuments = string.Empty;
    
            try
            {
                //Search Azure DocumentDB 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;
        }
    }
    

    该应用还使用提示工程来确保 OpenAI 服务限制并设置提供的食谱的响应格式。

    //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.";