Microsoft.Extensions.AI 缓存机制示例总结

项目概述

一个演示如何为AI聊天客户端添加分布式缓存的C#控制台应用程序。

当问题再次发送时,系统会计算缓存键,并检查缓存中是否存在该键。如果存在,则直接返回缓存中的响应,否则会调用模型生成新的响应并将其存储在缓存中。

核心技术栈

1. AI服务集成

  • AI客户端: Microsoft.Extensions.AIChatClient

  • 模型: OpenAI GPT-4.1-nano

  • API提供商: OpenRouter.ai

  • 获取方式: 通过 CommonToolsProvider.GetChatClient() 获取预配置的客户端

2. 缓存方案

  • 缓存类型: 分布式缓存

  • 实现: Microsoft.Extensions.Caching.StackExchangeRedis

  • 连接: 本地Redis服务器 (localhost:6379)

  • 实例命名: "AIChat" 命名空间

核心代码结构

初始化阶段

csharp

// 1. 获取基础AI聊天客户端
var chatClient = CommonToolsProvider.GetChatClient(
    "https://openrouter.ai/api/v1",
    "openai/gpt-4.1-nano", 
    "API密钥"
);

// 2. 配置Redis分布式缓存
var redisOptions = new RedisCacheOptions
{
    Configuration = "localhost:6379",
    InstanceName = "AIChat"
};

IDistributedCache distributedCache = new RedisCache(redisOptions);

// 3. 构建带缓存的客户端
var cachedChatClient = new ChatClientBuilder(chatClient)
    .UseDistributedCache(distributedCache)
    .UseDistributedCache(distributedCache, configure: c =>
    {
        c.CacheKeyAdditionalValues = new[] { "prod", "v2", "zh-CN" };
    })
    .Build();

缓存配置优化

csharp

// 配置缓存客户端的高级选项
if (cachedChatClient is DistributedCachingChatClient distributedCachingClient)
{
    // 合并流式更新(默认开启)
    distributedCachingClient.CoalesceStreamingUpdates = true;
    
    // 可选的缓存键附加值(用于环境/版本区分)
    // distributedCachingClient.CacheKeyAdditionalValues = new[] { "v1", "production" };
}

缓存测试流程

csharp

// 第一次请求 - 调用实际模型
var response1 = await cachedChatClient.GetResponseAsync(testMessage);

// 第二次请求 - 从缓存读取
var response2 = await cachedChatClient.GetResponseAsync(testMessage);

// 性能对比
double speedupRatio = (double)第一次耗时 / 第二次耗时;
bool contentMatch = response1.Text == response2.Text;

不会做游戏