在本快速入门中,你将创建一个 .NET 控制台应用,用于在向量存储上执行语义搜索,以查找用户查询的相关结果。 了解如何为用户提示生成嵌入内容,并使用这些嵌入项查询矢量数据存储。 矢量搜索功能也是检索扩充生成(RAG)方案的关键组成部分。 应用使用 Microsoft.Extensions.AI 和 Microsoft.Extensions.VectorData.Abstractions 库,以便可以使用 AI 抽象而不是特定的 SDK 编写代码。 AI 抽象有助于创建松散耦合的代码,使你可以通过最少的应用更改来更改基础 AI 模型。
先决条件
- .NET 8.0 SDK 或更高版本 - 安装 .NET 8.0 SDK。
- OpenAI 的 API 密钥,可以用于运行此示例。
先决条件
- .NET 8.0 SDK 或更高版本 - 安装 .NET 8 SDK。
- Azure 订阅 - 免费创建一个订阅。
- Azure 开发人员 CLI (可选) - 安装或更新 Azure 开发人员 CLI。
利用矢量存储与数据进行交互
矢量存储或矢量数据库对于语义搜索、检索增强生成(RAG),以及其他需要为生成式 AI 响应提供基础的场景至关重要。 虽然关系数据库和文档数据库针对结构化和半结构化数据进行了优化,但矢量数据库是用来有效地存储、编制索引和管理表示为嵌入向量的数据。 因此,对矢量数据库使用的索引和搜索算法进行优化,以有效地检索可在应用程序中下游使用的数据。
浏览 Microsoft.Extensions.VectorData.Abstractions
Microsoft.Extensions.VectorData.Abstractions 是一个 .NET 库,与语义内核和更广泛的 .NET 生态系统协作开发,为与矢量存储交互提供统一的抽象层。
Microsoft.Extensions.VectorData.Abstractions
中的抽象为库作者和开发人员提供以下功能:
- 对矢量存储执行 Create-Read-Update-Delete (CRUD) 操作
- 在矢量存储上使用矢量和文本搜索
注释
创建应用
完成以下步骤以创建可执行以下作的 .NET 控制台应用:
- 通过为数据集生成嵌入内容来创建和填充向量存储
- 为用户提示生成嵌入内容
- 使用用户提示嵌入查询矢量存储
- 显示矢量搜索的相关结果
在计算机上的空目录中,使用
dotnet new
命令创建新的控制台应用:dotnet new console -o VectorDataAI
将目录更改为应用文件夹:
cd VectorDataAI
安装所需的包:
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
:-
Azure.Identity
通过Microsoft Entra ID
类在 Azure SDK 中提供DefaultAzureCredential
令牌身份验证支持。 -
Azure.AI.OpenAI
是将 OpenAI 的 .NET 库与 Azure OpenAI 服务配合使用的官方包。 -
Microsoft.SemanticKernel.Connectors.InMemory
提供内存中矢量存储类来保存可查询矢量数据记录。 -
Microsoft.Extensions.VectorData.Abstractions
启用对矢量存储的 Create-Read-Update-Delete (CRUD) 和搜索操作。 - Microsoft.Extensions.Configuration 提供基于键值对的配置实现。
-
Microsoft.Extensions.Configuration.UserSecrets
是为Microsoft.Extensions.Configuration
提供的用户机密配置程序实现。
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
:-
Microsoft.Extensions.AI.OpenAI
为 OpenAI 兼容的模型或终结点提供 AI 抽象。 此库还包括 OpenAI 服务 API 的官方OpenAI
库作为依赖项。 -
Microsoft.SemanticKernel.Connectors.InMemory
提供内存中矢量存储类来保存可查询矢量数据记录。 -
Microsoft.Extensions.VectorData.Abstractions
启用对矢量存储的 Create-Read-Update-Delete (CRUD) 和搜索操作。 - Microsoft.Extensions.Configuration 提供基于键值对的配置实现。
-
Microsoft.Extensions.Configuration.UserSecrets
是为Microsoft.Extensions.Configuration
提供的用户机密配置程序实现。
-
在 Visual Studio Code 中打开应用(或所选编辑器)。
code .
创建 AI 服务
若要预配 Azure OpenAI 服务和模型,请完成 创建和部署 Azure OpenAI 服务资源 文章中的步骤。
在终端或命令提示符下,导航到项目目录的根目录。
运行以下命令为示例应用配置 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>
配置应用
从终端或命令提示符导航到 .NET 项目的根目录。
运行以下命令,将 OpenAI API 密钥配置为示例应用的机密:
dotnet user-secrets init dotnet user-secrets set OpenAIKey <your-OpenAI-key> dotnet user-secrets set ModelName <your-OpenAI-model-name>
注释
对于
ModelName
值,需要指定 OpenAI 文本嵌入模型(如text-embedding-3-small
或text-embedding-3-large
),以便在后面的部分中生成矢量搜索的嵌入内容。
添加应用代码
使用以下属性向项目添加新类
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
提供的 C# 属性会影响在向量存储中使用的每个属性的处理方式。 - 该
Vector
属性存储生成的嵌入,该嵌入表示和Name
矢量搜索的Description
语义含义。
- 由
在
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." } ];
创建和配置
IEmbeddingGenerator
实现以将请求发送到嵌入 AI 模型:// 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 从本地工具中搜寻身份验证凭据。 如果不使用
azd
模板来预配 Azure OpenAI 资源,则需要将Azure AI Developer
角色分配给用于登录到 Visual Studio 或 Azure CLI 的帐户。 有关详细信息,请参阅使用 .NET 向 Azure AI 服务进行身份验证。// Create the embedding generator. IEmbeddingGenerator<string, Embedding<float>> generator = new OpenAIClient(new ApiKeyCredential(key)) .GetEmbeddingClient(model: model) .AsIEmbeddingGenerator(); // Create and populate the vector store. var vectorStore = new InMemoryVectorStore(); IVectorStoreRecordCollection<int, CloudService> cloudServicesStore = vectorStore.GetCollection<int, CloudService>("cloudServices"); await cloudServicesStore.CreateCollectionIfNotExistsAsync();
使用云服务数据创建和填充向量存储。 使用
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); }
嵌入是每个数据记录语义含义的数字表示形式,这使得它们与矢量搜索功能兼容。
为搜索查询创建嵌入,并使用它在向量存储上执行矢量搜索:
// 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); List<VectorSearchResult<CloudService>> results = await cloudServicesStore.SearchAsync(queryEmbedding, top: 1).ToListAsync(); 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}"); }
使用
dotnet run
命令运行应用:dotnet run
应用输出矢量搜索的顶部结果,这是与原始查询最相关的云服务。 可以修改查询以尝试不同的搜索方案。
清理资源
如果不再需要它们,请删除 Azure OpenAI 资源和 GPT-4 模型部署。
- 在 Azure 门户中,导航到 Azure OpenAI 资源。
- 选择 Azure OpenAI 资源,然后选择 删除。
后续步骤
- 快速入门 - 使用本地 AI 模型聊天
- 在 .NET 中使用 AI 生成图像