找回密码
 立即注册
首页 业界区 业界 基于Microsoft.Extensions.AI核心库实现RAG应用 ...

基于Microsoft.Extensions.AI核心库实现RAG应用

扈梅风 4 天前
大家好,我是Edison。
之前我们了解 Microsoft.Extensions.AI 和 Microsoft.Extensions.VectorData 两个重要的AI应用核心库。基于对他们的了解,今天我们就可以来实战一个RAG问答应用,把之前所学的串起来。
前提知识点:向量存储、词嵌入、向量搜索、提示词工程、函数调用。
案例需求背景

假设我们在一家名叫“易速鲜花”的电商网站工作,顾名思义,这是一家从事鲜花电商的网站。我们有一些运营手册、员工手册之类的文档(例如下图所示的一些pdf文件),想要将其导入知识库并创建一个AI机器人,负责日常为员工解答一些政策性的问题。
例如,员工想要了解奖励标准、行为准备、报销流程等等,都可以通过和这个AI机器人对话就可以快速了解最新的政策和流程。
在接下来的Demo中,我们会使用以下工具:
(1) LLM 采用 Qwen2.5-7B-Instruct,可以使用SiliconFlow平台提供的API,你也可以改为你喜欢的其他模型如DeepSeek,但是建议不要用大炮打蚊子哈。
注册地址:点此注册
(2) Qdrant 作为 向量数据库,可以使用Docker在你本地运行一个:
  1. docker run -p 6333:6333 -p 6334:6334 \
  2. -v $(pwd)/qdrant_storage:/qdrant/storage \
  3. qdrant/qdrant
复制代码
(3) Ollama 运行 bge-m3 模型 作为 Emedding生成器,可以自行拉取一个在你本地运行:
  1. ollama pull bge-m3
复制代码
构建你的RAG应用

创建一个控制台应用程序,添加一些必要的文件目录 和 配置文件(json),最终的解决方案如下图所示。
1.png

在Documents目录下放了我们要导入的一些pdf文档,例如公司运营手册、员工手册等等。
在Models目录下放了一些公用的model类,其中TextSnippet类作为向量存储的实体类,而TextSearchResult类则作为向量搜索结果的模型类。
(1)TextSnippet
这里我们的TextEmbedding字段就是我们的向量值,它有1024维。
注意:这里的维度是我们自己定义的,你也可以改为你想要的维度数量,但是你的词嵌入模型需要支持你想要的维度数量。
  1. public sealed class TextSnippet<TKey>
  2. {
  3.     [VectorStoreRecordKey]
  4.     public required TKey Key { get; set; }
  5.     [VectorStoreRecordData]
  6.     public string? Text { get; set; }
  7.     [VectorStoreRecordData]
  8.     public string? ReferenceDescription { get; set; }
  9.     [VectorStoreRecordData]
  10.     public string? ReferenceLink { get; set; }
  11.     [VectorStoreRecordVector(Dimensions: 1024)]
  12.     public ReadOnlyMemory<float> TextEmbedding { get; set; }
  13. }
复制代码
(2)TextSearchResult
这个类主要用来返回给LLM做推理用的,我这里只需要三个字段:Value, Link 和 Score 即可。
  1. public class TextSearchResult
  2. {
  3.     public string  Value { get; set; }
  4.     public string? Link { get; set; }
  5.     public double? Score { get; set; }
  6. }
复制代码
(3)RawContent
这个类主要用来在PDF导入时作为一个临时存储源数据文档内容。
  1. public sealed class RawContent
  2. {
  3.     public string? Text { get; init; }
  4.     public int PageNumber { get; init; }
  5. <strong>}</strong>
复制代码
在Plugins目录下放了一些公用的帮助类,如PdfDataLoader可以实现PDF文件的读取和导入向量数据库,VectorDataSearcher可以实现根据用户的query搜索向量数据库获取TopN个近似文档,而UniqueKeyGenerator则用来生成唯一的ID Key。
(1)PdfDataLoader
作为PDF文件的导入核心逻辑,它实现了PDF文档读取、切分、生成指定维度的向量 并 存入向量数据库。
注意:这里只考虑了文本格式的内容,如果你还想考虑文件中的图片将其转成文本,你需要增加一个LLM来帮你做图片转文本的工作。
  1. public sealed class PdfDataLoader<TKey> where TKey : notnull
  2. {
  3.     private readonly IVectorStoreRecordCollection<TKey, TextSnippet<TKey>> _vectorStoreRecordCollection;
  4.     private readonly UniqueKeyGenerator<TKey> _uniqueKeyGenerator;
  5.     private readonly IEmbeddingGenerator<string, Embedding<float>> _embeddingGenerator;
  6.     public PdfDataLoader(
  7.         UniqueKeyGenerator<TKey> uniqueKeyGenerator,
  8.         IVectorStoreRecordCollection<TKey, TextSnippet<TKey>> vectorStoreRecordCollection,
  9.         IEmbeddingGenerator<string, Embedding<float>> embeddingGenerator)
  10.     {
  11.         _vectorStoreRecordCollection = vectorStoreRecordCollection;
  12.         _uniqueKeyGenerator = uniqueKeyGenerator;
  13.         _embeddingGenerator = embeddingGenerator;
  14.     }
  15.     public async Task LoadPdf(string pdfPath, int batchSize, int betweenBatchDelayInMs)
  16.     {
  17.         // Create the collection if it doesn't exist.
  18.         await _vectorStoreRecordCollection.CreateCollectionIfNotExistsAsync();
  19.         // Load the text and images from the PDF file and split them into batches.
  20.         var sections = LoadAllTexts(pdfPath);
  21.         var batches = sections.Chunk(batchSize);
  22.         // Process each batch of content items.
  23.         foreach (var batch in batches)
  24.         {
  25.             // Get text contents
  26.             var textContentTasks = batch.Select(async content =>
  27.             {
  28.                 if (content.Text != null)
  29.                     return content;
  30.                 return new RawContent { Text = string.Empty, PageNumber = content.PageNumber };
  31.             });
  32.             var textContent = (await Task.WhenAll(textContentTasks))
  33.                 .Where(c => !string.IsNullOrEmpty(c.Text))
  34.                 .ToList();
  35.             // Map each paragraph to a TextSnippet and generate an embedding for it.
  36.             var recordTasks = textContent.Select(async content => new TextSnippet<TKey>
  37.             {
  38.                 Key = _uniqueKeyGenerator.GenerateKey(),
  39.                 Text = content.Text,
  40.                 ReferenceDescription = $"{new FileInfo(pdfPath).Name}#page={content.PageNumber}",
  41.                 ReferenceLink = $"{new Uri(new FileInfo(pdfPath).FullName).AbsoluteUri}#page={content.PageNumber}",
  42.                 TextEmbedding = await _embeddingGenerator.GenerateEmbeddingVectorAsync(content.Text!)
  43.             });
  44.             // Upsert the records into the vector store.
  45.             var records = await Task.WhenAll(recordTasks);
  46.             var upsertedKeys = _vectorStoreRecordCollection.UpsertBatchAsync(records);
  47.             await foreach (var key in upsertedKeys)
  48.             {
  49.                 Console.WriteLine($"Upserted record '{key}' into VectorDB");
  50.             }
  51.             await Task.Delay(betweenBatchDelayInMs);
  52.         }
  53.     }
  54.     private static IEnumerable<RawContent> LoadAllTexts(string pdfPath)
  55.     {
  56.         using (PdfDocument document = PdfDocument.Open(pdfPath))
  57.         {
  58.             foreach (Page page in document.GetPages())
  59.             {
  60.                 var blocks = DefaultPageSegmenter.Instance.GetBlocks(page.GetWords());
  61.                 foreach (var block in blocks)
  62.                     yield return new RawContent { Text = block.Text, PageNumber = page.Number };
  63.             }
  64.         }
  65.     }
  66. }
复制代码
(2)VectorDataSearcher
和上一篇文章介绍的内容类似,主要做语义搜索,获取TopN个近似内容。
  1. public class VectorDataSearcher<TKey> where TKey : notnull
  2. {
  3.     private readonly IVectorStoreRecordCollection<TKey, TextSnippet<TKey>> _vectorStoreRecordCollection;
  4.     private readonly IEmbeddingGenerator<string, Embedding<float>> _embeddingGenerator;
  5.     public VectorDataSearcher(IVectorStoreRecordCollection<TKey, TextSnippet<TKey>> vectorStoreRecordCollection, IEmbeddingGenerator<string, Embedding<float>> embeddingGenerator)
  6.     {
  7.         _vectorStoreRecordCollection = vectorStoreRecordCollection;
  8.         _embeddingGenerator = embeddingGenerator;
  9.     }
  10.     [Description("Get top N text search results from vector store by user's query (N is 1 by default)")]
  11.     [return: Description("Collection of text search result")]
  12.     public async Task<IEnumerable<TextSearchResult>> GetTextSearchResults(string query, int topN = 1)
  13.     {
  14.         var queryEmbedding = await _embeddingGenerator.GenerateEmbeddingVectorAsync(query);
  15.         // Query from vector data store
  16.         var searchOptions = new VectorSearchOptions()
  17.         {
  18.             Top = topN,
  19.             VectorPropertyName = nameof(TextSnippet<TKey>.TextEmbedding)
  20.         };
  21.         var searchResults = await _vectorStoreRecordCollection.VectorizedSearchAsync(queryEmbedding, searchOptions);
  22.         var responseResults = new List<TextSearchResult>();
  23.         await foreach (var result in searchResults.Results)
  24.         {
  25.             responseResults.Add(new TextSearchResult()
  26.             {
  27.                 Value = result.Record.Text ?? string.Empty,
  28.                 Link = result.Record.ReferenceLink ?? string.Empty,
  29.                 Score = result.Score
  30.             });
  31.         }
  32.         return responseResults;
  33.     }
  34. }
复制代码
(3)UniqueKeyGenerator
这个主要是一个代理,后续我们主要使用Guid作为Key。
  1. public sealed class UniqueKeyGenerator<TKey>(Func<TKey> generator)
  2.     where TKey : notnull
  3. {
  4.     /// <summary>
  5.     /// Generate a unique key.
  6.     /// </summary>
  7.     /// <returns>The unique key that was generated.</returns>
  8.     public TKey GenerateKey() => generator();
  9. }
复制代码
串联实现RAG问答

安装NuGet包:
  1. Microsoft.Extensions.AI (preview)
  2. Microsoft.Extensions.Ollama (preivew)
  3. Microsoft.Extensions.AI.OpenAI (preivew)
  4. Microsoft.Extensions.VectorData.Abstractions (preivew)
  5. Microsoft.SemanticKernel.Connectors.Qdrant (preivew)
  6. PdfPig (0.1.9)
  7. Microsoft.Extensions.Configuration (8.0.0)
  8. Microsoft.Extensions.Configuration.Json (8.0.0)
复制代码
下面我们分解几个核心步骤来实现RAG问答。
Step1. 配置文件appsettings.json:
  1. {
  2.   "LLM": {
  3.     "EndPoint": "https://api.siliconflow.cn",
  4.     "ApiKey": "sk-**********************", // Replace with your ApiKey
  5.     "ModelId": "Qwen/Qwen2.5-7B-Instruct"
  6.   },
  7.   "Embeddings": {
  8.     "Ollama": {
  9.       "EndPoint": "http://localhost:11434",
  10.       "ModelId": "bge-m3"
  11.     }
  12.   },
  13.   "VectorStores": {
  14.     "Qdrant": {
  15.       "Host": "edt-dev-server",
  16.       "Port": 6334,
  17.       "ApiKey": "EdisonTalk@2025"
  18.     }
  19.   },
  20.   "RAG": {
  21.     "CollectionName": "oneflower",
  22.     "DataLoadingBatchSize": 10,
  23.     "DataLoadingBetweenBatchDelayInMilliseconds": 1000,
  24.     "PdfFileFolder": "Documents"
  25.   }
  26. }
复制代码
Step2. 加载配置:
  1. var config = new ConfigurationBuilder()
  2.     .AddJsonFile($"appsettings.json")
  3.     .Build();
复制代码
Step3. 初始化ChatClient、Embedding生成器 以及 VectorStore:
  1. # ChatClient
  2. var apiKeyCredential = new ApiKeyCredential(config["LLM:ApiKey"]);
  3. var aiClientOptions = new OpenAIClientOptions();
  4. aiClientOptions.Endpoint = new Uri(config["LLM:EndPoint"]);
  5. var aiClient = new OpenAIClient(apiKeyCredential, aiClientOptions)
  6.     .AsChatClient(config["LLM:ModelId"]);
  7. var chatClient = new ChatClientBuilder(aiClient)
  8.     .UseFunctionInvocation()
  9.     .Build();
  10. # EmbeddingGenerator
  11. var embedingGenerator =
  12.     new OllamaEmbeddingGenerator(new Uri(config["Embeddings:Ollama:EndPoint"]), config["Embeddings:Ollama:ModelId"]);
  13. # VectorStore
  14. var vectorStore =
  15.     new QdrantVectorStore(new QdrantClient(host: config["VectorStores:Qdrant:Host"], port: int.Parse(config["VectorStores:Qdrant:Port"]), apiKey: config["VectorStores:Qdrant:ApiKey"]));
复制代码
Step4. 导入PDF文档到VectorStore:
  1. var ragConfig = config.GetSection("RAG");
  2. // Get the unique key genrator
  3. var uniqueKeyGenerator = new UniqueKeyGenerator<Guid>(() => Guid.NewGuid());
  4. // Get the collection in qdrant
  5. var ragVectorRecordCollection = vectorStore.GetCollection<Guid, TextSnippet<Guid>>(ragConfig["CollectionName"]);
  6. // Get the PDF loader
  7. var pdfLoader = new PdfDataLoader<Guid>(uniqueKeyGenerator, ragVectorRecordCollection, embedingGenerator);
  8. // Start to load PDF to VectorStore
  9. var pdfFilePath = ragConfig["PdfFileFolder"];
  10. var pdfFiles = Directory.GetFiles(pdfFilePath);
  11. try
  12. {
  13.     foreach (var pdfFile in pdfFiles)
  14.     {
  15.         Console.WriteLine($"[LOG] Start Loading PDF into vector store: {pdfFile}");
  16.         await pdfLoader.LoadPdf(
  17.             pdfFile,
  18.             int.Parse(ragConfig["DataLoadingBatchSize"]),
  19.             int.Parse(ragConfig["DataLoadingBetweenBatchDelayInMilliseconds"]));
  20.         Console.WriteLine($"[LOG] Finished Loading PDF into vector store: {pdfFile}");
  21.     }
  22.     Console.WriteLine($"[LOG] All PDFs loaded into vector store succeed!");
  23. }
  24. catch (Exception ex)
  25. {
  26.     Console.WriteLine($"[ERROR] Failed to load PDFs: {ex.Message}");
  27.     return;
  28. }
复制代码
Step5. 构建AI对话机器人:
重点关注这里的提示词模板,我们做了几件事情:
(1)给AI设定一个人设:鲜花网站的AI对话机器人,告知其负责的职责。
(2)告诉AI要使用相关工具(向量搜索插件)进行相关背景信息的搜索获取,然后将结果 连同 用户的问题 组成一个新的提示词,最后将这个新的提示词发给大模型进行处理。
(3)告诉AI在输出信息时要把引用的文档信息链接也一同输出。
  1. Console.WriteLine("[LOG] Now starting the chatting window for you...");
  2. Console.ForegroundColor = ConsoleColor.Green;
  3. var promptTemplate = """
  4.           你是一个专业的AI聊天机器人,为易速鲜花网站的所有员工提供信息咨询服务。
  5.           请使用下面的提示使用工具从向量数据库中获取相关信息来回答用户提出的问题:
  6.           {{#with (SearchPlugin-GetTextSearchResults question)}}  
  7.             {{#each this}}  
  8.               Value: {{Value}}
  9.               Link: {{Link}}
  10.               Score: {{Score}}
  11.               -----------------
  12.              {{/each}}
  13.             {{/with}}
  14.             
  15.             输出要求:请在回复中引用相关信息的地方包括对相关信息的引用。
  16.             用户问题: {{question}}
  17.             """;
  18. var history = new List<ChatMessage>();
  19. var vectorSearchTool = new VectorDataSearcher<Guid>(ragVectorRecordCollection, embedingGenerator);
  20. var chatOptions = new ChatOptions()
  21. {
  22.     Tools =
  23.     [
  24.       AIFunctionFactory.Create(vectorSearchTool.GetTextSearchResults)
  25.     ]
  26. };
  27. // Prompt the user for a question.
  28. Console.ForegroundColor = ConsoleColor.Green;
  29. Console.WriteLine($"助手> 今天有什么可以帮到你的?");
  30. while (true)
  31. {
  32.     // Read the user question.
  33.     Console.ForegroundColor = ConsoleColor.White;
  34.     Console.Write("用户> ");
  35.     var question = Console.ReadLine();
  36.     // Exit the application if the user didn't type anything.
  37.     if (!string.IsNullOrWhiteSpace(question) && question.ToUpper() == "EXIT")
  38.         break;
  39.     var ragPrompt = promptTemplate.Replace("{question}", question);
  40.     history.Add(new ChatMessage(ChatRole.User, ragPrompt));
  41.     Console.ForegroundColor = ConsoleColor.Green;
  42.     Console.Write("助手> ");
  43.     var result = await chatClient.GetResponseAsync(history, chatOptions);<br>    var response = result.ToString();
  44.     Console.Write(response);
  45.     history.Add(new ChatMessage(ChatRole.Assistant, response));
  46.     Console.WriteLine();
  47. }
复制代码
调试验证

首先,看看PDF导入中的log显示:
2.png

其次,验证下Qdrant中是否新增了导入的PDF文档数据:
3.png

最后,和AI机器人对话咨询问题:
问题1及其回复:
4.png

问题2及其回复:
5.png

更多的问题,就留给你去调戏了。
小结

本文介绍了如何基于Microsoft.Extensions.AI + Microsoft.Extensions.VectorData 一步一步地实现一个RAG(检索增强生成)应用,相信会对你有所帮助。
如果你也是.NET程序员希望参与AI应用的开发,那就快快了解和使用基于Microsoft.Extensioins.AI + Microsoft.Extensions.VectorData 的生态组件库吧。
示例源码

GitHub:点此查看

参考内容

Semantic Kernel 《.NET Sample Demos》
推荐内容

Microsoft Learn
eShopSupport
devblogs
 
6.jpeg

作者:周旭龙
出处:https://edisonchou.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
  1. var
复制代码
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册