在智能体中使用存储

存储是 Microsoft 365 智能体 SDK 的关键组件。 它使智能体能够在不同会话之间持久化对话状态、用户数据和其他信息。 该 SDK 支持多种存储选项,包括:

  • 内存存储
  • Azure Cosmos DB
  • Azure Blob 存储
  • 自定义存储提供程序

主要存储选项

Agents SDK 提供了多种内置存储提供程序,每种都有其特定的应用场景和优势。 您可以选择最符合您智能体需求的存储提供程序。 您还可以实现自己的自定义存储提供程序。

  1. 内存存储

    • 适用于测试和开发场景。
    • 智能体重启时数据会被清空,因此不适合生产环境。
    • 数据仅在 Web 应用实例上可用,因此不适用于集群环境。
  2. Azure Cosmos DB

    • 一种全球分布式、多模型数据库,非常适合生产环境中的智能体。
    • 支持分区存储,以实现可扩展性和高性能。
  3. Azure Blob 存储

    • 针对文本或二进制文件等非结构化数据的存储进行了优化。
    • 通常用于存储智能体状态和对话记录。
  4. 通过实现 IStorage 提供自定义存储选项

使用不同的存储提供商

内存存储

所有示例均使用 MemoryStorage。 此类存储具有易失性,仅适用于开发和测试。 对于生产环境,请使用更持久的存储选项,例如 Azure Cosmos DB 或 Azure Blob 存储。

Program.cs 中,注册 MemoryStorage

builder.Services.AddSingleton<IStorage, MemoryStorage>();

Azure CosmosDb 存储

  1. Microsoft.Agents.Storage.CosmosDb 添加包依赖项。

  2. Program.cs 中,添加(或替换现有)IStorage 注册信息,内容如下:

    builder.Services.AddSingleton<IStorage>(sp =>
    {
          var options = new CosmosDbPartitionedStorageOptions()
          {
             CosmosDbEndpoint = "your-cosmosdb-endpoint",
             DatabaseId = "your-database-id",
             ContainerId = "your-container-id",
    
             // Get a TokenCredential from your defined Connections
             TokenCredential = sp.GetService<IConnections>().GetConnection("ServiceConnection").GetTokenCredential()
          };
    
          return new CosmosDbPartitionedStorage(options);
    });
    
  3. 若要了解详细信息,请访问 CosmosDbPartitionedStorageOptions

Azure Blob 存储

  1. Microsoft.Agents.Storage.Blobs 添加包依赖项。

  2. Program.cs 中,添加(或替换现有)IStorage 注册信息,内容如下:

    builder.Services.AddSingleton<IStorage>(sp =>
    {
       // Get a TokenCredential from your defined Connections
       var tokenCredential = sp.GetService<IConnections>().GetConnection("ServiceConnection").GetTokenCredential();
    
       return new BlobsStorage(
          new Uri("{{your-blobs-storage-endpoint}}/agent-state"),
          tokenCredential);
    });