当前位置: 首页 > news >正文

基于Microsoft.Extensions.AI 和 Microsoft.Extensions.VectorData构建向量搜索

今天简单看了看,基于Microsoft.Extensions.AI 和 Microsoft.Extensions.VectorData构建向量搜索。给大家分享分享。

首先,创建.NET 控制台应用,然后执行以下开发步骤

  • 通过为数据集生成嵌入内容来创建和填充向量存储。
  • 为用户提示生成嵌入内容。
  • 使用用户提示嵌入查询矢量存储。
  • 显示矢量搜索的相关结果。
dotnet new console -o VectorDataAIDemo

切换到以上

VectorDataAIDemo

目录下,安装以下Nuget包

dotnet add package Microsoft.Extensions.AI.OpenAI --prerelease
dotnet add package Microsoft.Extensions.VectorData.Abstractions
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
  • Microsoft.Extensions.AI.OpenAI 为 OpenAI 兼容的模型或终结点提供 AI 抽象。 此库还包括 OpenAI 服务 API 的官方 OpenAI 库作为依赖项。
  • Microsoft.Extensions.VectorData.Abstractions 启用对向量存储的 Create-Read-Update-Delete (CRUD) 和搜索操作。
  • Microsoft.SemanticKernel.Connectors.InMemory 提供内存中向量存储类来保存可查询向量数据记录。
  • Microsoft.Extensions.Configuration 提供基于键值对的配置实现。
  • Microsoft.Extensions.Configuration.UserSecrets 是为 Microsoft.Extensions.Configuration 提供的用户机密配置程序实现。

新建Class:CloudServiceWiki

using Microsoft.Extensions.VectorData;namespace VectorDataAIDemo;internal class CloudServiceWiki
{[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 值在矢量搜索中的语义含义。

在 Program.cs 文件中,添加以下代码以创建描述云服务知识库集合的数据集:

List<CloudServiceWiki> 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."}
];

创建和配置 IEmbeddingGenerator 实现以将请求发送到嵌入 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();

使用云服务知识库数据创建和填充向量存储。 使用 IEmbeddingGenerator 实现为云服务知识库数据中的每个记录创建和分配嵌入向量:

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

嵌入是每个数据记录语义含义的数字表示形式,这使得它们与向量搜索功能兼容。

搜索查询

// 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<CloudServiceWiki>> results =cloudServicesStore.SearchAsync(queryEmbedding, top: 1);await foreach (VectorSearchResult<CloudServiceWiki> result in results)
{Console.WriteLine($"Name: {result.Record.Name}");Console.WriteLine($"Description: {result.Record.Description}");Console.WriteLine($"Vector match score: {result.Score}");
}

 

周国庆

20260309

 

http://www.jsqmd.com/news/452786/

相关文章:

  • Windows 系统下 JDK 1.8 + Tomcat 安装与配置
  • 农产品实名收购系统功能说明之电子秤已支持类型和厂家型号
  • 基于Java开发的大学社团管理系统源码+运行步骤+计算机技术
  • MySQL 常用内置函数与高级查询技巧,看这一篇就够了!
  • 2026年天津消防电缆生产厂家推荐:耐火、防火、阻燃、阻燃B1级等电缆厂家都包含 - 品牌2026
  • 在空论视域中:一个跨时空的思想对话——儒释道千年裂隙在自感(定稿)
  • 详细介绍:Visual Studio 原生项目(.vcxproj) 和 CMake 项目对比
  • LangChain 能干什么
  • 如何甄别专业的装修套餐企业?关键标准与选择逻辑 - 2026年企业推荐榜
  • C++11(下) 入门三部曲终章(基础篇):夯实语法,解锁基础编程能力 - 详解
  • 2026-03-09 闲话
  • 波段末段的心态
  • 模型加载权重的时候发生了什么
  • 2026年矿山煤矿电力电缆生产厂家推荐:中低压、低压、中压、变频等厂家名单 - 品牌2026
  • 2026年天津消防电缆生产厂家推荐(含耐火、阻燃、阻燃B1级等全品类) - 品牌2026
  • 346. Java IO API - 操作文件和目录
  • 0309晨间日记
  • 超越简单分类:构建面向真实世界的多层文本分类系统
  • 基于贾子军事战略理论体系的美国军事 AI 系统深度研究报告
  • Harmonyos应用示例32. 有余数的除法:分草莓动画
  • Harmonyos应用示例33. 数量间的乘除关系:倍数关系可视化
  • Harmonyos应用示例34. 万以内的数的认识:数位拨珠器
  • Harmonyos应用示例35. 万以内的数的认识:数字排序游戏
  • Harmonyos应用示例36. 万以内的加法和减法:竖式计算器
  • Harmonyos应用示例37. 万以内的加法和减法:智慧购物
  • Harmonyos应用示例38. 数学连环画:故事拼图
  • Harmonyos应用示例39. 有余数的除法:余数与除数关系
  • 拒绝全表扫描灾难:用 SSCAN 安全遍历 Redis 亿级 Set 集合
  • 2603,禁止微软更新工具
  • 2603C++,简单实现协程