Semantic Kernel 内存架构演进:ADR-0013 将 Memory 逻辑重构为独立 Plugin 的完整解读
Semantic Kernel 内存架构演进:ADR-0013 将 Memory 逻辑重构为独立 Plugin 的完整解读
导读
本文基于 docs/decisions/0013-memory-as-plugin.md 这一架构决策记录(ADR),深入解析 Semantic Kernel(.NET 版本)为何要将全部内存(Memory)相关逻辑从核心类型中剥离、收敛为独立的 Plugins.Memory 项目,并对照当前仓库源码说明重构后的真实形态:TextMemoryPlugin 的参数体系、ISemanticTextMemory / IMemoryStore 的分层职责、以及如何通过依赖注入将内存能力注入其他 Plugin。读完本文,你将理解 Semantic Kernel 中"内存即插件"的设计哲学,掌握在插件中注入并使用语义内存的完整落地方案,以及该决策对 Kernel 核心逻辑瘦身的实际影响。
背景:Memory 逻辑分散带来的架构问题
决策上下文
在 ADR-0013 提出之时(2023-09-21,由 dmytrostruk 发起,shawncal 与 dmytrostruk 共同决策),Memory 相关逻辑分散在三个不同的 C# 项目中:
| 所在项目 | 类型 |
|---|---|
SemanticKernel.Abstractions |
IMemoryStore、ISemanticTextMemory、MemoryRecord、NullMemory |
SemanticKernel.Core |
MemoryConfiguration、SemanticTextMemory、VolatileMemoryStore |
Plugins.Core |
TextMemoryPlugin |
同时,Kernel 类型上暴露了一个 ISemanticTextMemory Memory 属性。问题在于:Kernel 本身并不使用这个属性,它存在的唯一目的就是"把 Memory 能力注入到需要它的 Plugin 中"。例如,当时的典型用法是 new TextMemoryPlugin(kernel.Memory),直接把 Kernel 上的内存实例塞给插件。
核心问题:为什么不能"照着做"下去
这种为某个插件专门在 Kernel 上开一个属性的做法,一旦推广就会立刻失控。ADR 明确指出:
Following the same approach and adding
Mathproperty toKerneltype is not scalable solution, as it's not possible to define separate properties for each available Plugin.
也就是说,如果今天要为 MathPlugin 注入能力,就得给 Kernel 加一个 Math 属性;明天有 TextPlugin、SearchPlugin,就继续往 Kernel 上加属性。每个可用插件都定义一个专属属性显然不可扩展,这会把 Kernel 变成一个不断膨胀的"万能口袋",彻底违背其作为服务与插件编排中枢的职责边界。
决策驱动因素与最终方案
三条决策驱动
- 内存不该成为
Kernel的属性——既然 Kernel 自身不使用它,就没有理由把它挂在 Kernel 类型上; - 内存应与其他插件、服务同等对待——它只是"某些特定插件可能依赖的能力"之一,不应享有特殊地位;
- 必须存在标准的注册与注入途径——要能把"内存能力 + 其背后挂载的向量数据库(Vector DB)"注册为一个整体,并注入到需要它的插件中。
决策结论:独立 Plugins.Memory 项目
最终结论是将所有 Memory 逻辑迁入独立项目 Plugins.Memory。迁移带来了三个直接收益:
- 简化 Kernel 逻辑,让 Kernel 专注于编排本身;
- 让 Memory 能力可以在真正需要它的地方(其他插件)按需使用;
- 打开"以插件注入插件"的通用通道,而不是为每个能力定制 Kernel 属性。
ADR 中还列出了一份高层任务清单(High-level tasks),可以视作该决策的验收标准:
- 将 Memory 相关代码迁移到独立项目;
- 实现"向需要内存的插件注入内存"的标准方式;
- 从
Kernel类型中移除Memory属性。
重构后的仓库落地形态
独立的 Plugins.Memory 项目
在当前仓库中,该决策已经完整落地。独立项目位于 dotnet/src/Plugins/Plugins.Memory,其工程文件 Plugins.Memory.csproj 表明:
- 程序集名为
Microsoft.SemanticKernel.Plugins.Memory; - 目标框架覆盖
net10.0; net8.0; netstandard2.0,版本后缀为alpha,整体标注为实验性 API(SKEXP0001); - 通过
ProjectReference依赖SemanticKernel.Core,并引用System.Text.Json与System.Numerics.Tensors(后者用于向量运算)。
项目内包含的核心文件有:
- TextMemoryPlugin.cs——对外暴露的语义内存插件;
- VolatileMemoryStore.cs——纯内存实现的内存存储;
- Collections——
MinHeap、ScoredValue、TopNCollection等用于 Top-N 相似度检索的辅助集合。
对应地,抽象层仍保留在 SemanticKernel.Abstractions:IMemoryStore.cs、ISemanticTextMemory.cs、MemoryRecord、NullMemory;而具体实现 SemanticTextMemory 位于 SemanticKernel.Core/Memory/SemanticTextMemory.cs。这正是 ADR 所述"抽象在 Abstractions、实现在 Core、插件在 Plugins.Memory"的分层格局。
内核是否已移除 Memory 属性
从当前 Kernel 源码看,Kernel 不再暴露 Memory 属性(对 ISemanticTextMemory Memory 的搜索在 SemanticKernel.Abstractions 下无结果)。这与 ADR 的高层任务 3 一致——Kernel 只保留服务注册与插件编排职责,内存能力完全交由插件系统承载。
核心实现:TextMemoryPlugin 的参数体系与行为
TextMemoryPlugin(标记为 [Experimental("SKEXP0001")])是这一决策的对外出口。它通过构造函数注入 ISemanticTextMemory,从而让"任何需要记忆能力的插件"都能复用它。其公开 API 定义了五个语义明确的参数名常量:
| 常量 | 值 | 含义 |
|---|---|---|
InputParam |
input |
输入文本(保存或检索的内容/查询) |
CollectionParam |
collection |
要使用的内存集合名 |
RelevanceParam |
relevance |
检索相关性得分 |
KeyParam |
key |
与存储信息关联的唯一键 |
LimitParam |
limit |
召回的记忆条数上限 |
默认值方面,源码明确定义了:集合默认 "generic"、相关性默认 0.0、召回数量默认 1。这意味着不指定任何参数时,RecallAsync 只会返回最相关的一条记忆。
插件对外提供四个 [KernelFunction] 方法,构成完整的 CRUD + 语义检索能力:
RetrieveAsync(key, collection):按唯一键精确查找记忆。底层调用ISemanticTextMemory.GetAsync(collection, key, ...),命中则返回MemoryRecord.Metadata.Text,未命中返回空字符串。RecallAsync(input, collection, relevance, limit):语义搜索。底层调用ISemanticTextMemory.SearchAsync(collection, input, limit, relevance, ...);当limit == 1时直接返回单条文本,否则用注入的JsonSerializerOptions将多条结果序列化为 JSON 数组。SaveAsync(input, key, collection):保存信息。底层调用SaveInformationAsync(collection, text, id: key, ...),id即调用方传入的key。RemoveAsync(key, collection):删除指定记忆,底层调用RemoveAsync(collection, key, ...)。
此外,构造函数的第三个可选参数 jsonSerializerOptions 允许调用方自定义"多条记忆转 JSON"的序列化选项,未提供时回退到 JsonSerializerOptions.Default;loggerFactory 为空时使用 NullLogger.Instance,保证插件可以无日志环境运行。
依赖注入:把 Memory 能力注入其他插件的标准路径
ADR 要求"内存能力 + 向量数据库"能以标准方式注册并注入。当前仓库的最佳实践样例位于 OpenAI_FunctionCallingWithMemoryPlugin.cs,其链路完整呈现了这套模式:
// 1. 构建 Kernel:注册聊天完成 + Embedding 生成服务
IKernelBuilder kernelBuilder = Kernel.CreateBuilder();
kernelBuilder.AddOpenAIChatCompletion(modelId, apiKey);
kernelBuilder.AddOpenAIEmbeddingGenerator(modelId, apiKey);
Kernel kernel = kernelBuilder.Build();
// 2. 组装"内存能力 + 存储后端"
var embeddingGenerator = kernel.GetRequiredService<IEmbeddingGenerator<string, Embedding<float>>>();
VolatileMemoryStore memoryStore = new();
SemanticTextMemory textMemory = new(memoryStore, embeddingGenerator);
string collectionName = "SemanticKernel";
// 3. 将内存封装为插件并挂载到 Kernel
MemoryPlugin memoryPlugin = new(collectionName, textMemory);
kernel.Plugins.AddFromObject(memoryPlugin, "Memory");
// 4. 开启函数自动调用,让 LLM 按需调用"记忆检索"函数
var executionSettings = new OpenAIPromptExecutionSettings
{
FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
};
var response = await kernel.InvokePromptAsync("What is Semantic Kernel?", new(executionSettings));
样例中自定义的 MemoryPlugin 就是一个典型的"依赖 ISemanticTextMemory 的插件":
private sealed class MemoryPlugin(string collection, ISemanticTextMemory memory)
{
[KernelFunction]
[Description("Retrieve useful information to help answer a question.")]
public async Task<string> GetUsefulInformationAsync(
[Description("The question being asked")] string question)
{
List<MemoryQueryResult> memories = await memory
.SearchAsync(collection, question)
.ToListAsync()
.ConfigureAwait(false);
return JsonSerializer.Serialize(memories.Select(x => x.Metadata.Text));
}
}
这正回应了 ADR 的核心诉求:内存不再是 Kernel.Memory 特供,而是与其他服务一样,通过 DI 容器构建,再以普通插件身份注册。TextMemoryPlugin 本身也完全适用同样的模式——只需 new TextMemoryPlugin(textMemory) 并 kernel.Plugins.AddFromObject(...) 即可。值得注意的是,样例注释明确提示:VolatileMemoryStore 与 SemanticTextMemory 属旧模式实现,即将被新(更完善的)Vector Store 模式取代,读者在跟进时应对此保持关注。
分层职责:IMemoryStore 与 ISemanticTextMemory
要真正理解"Memory 作为插件",还需看清它背后的两层抽象:
IMemoryStore(IMemoryStore.cs)是"存储层"契约,负责在数据存储中读写带索引的MemoryRecord:集合的创建/列举/存在性检查/删除(CreateCollectionAsync、GetCollectionsAsync、DoesCollectionExistAsync、DeleteCollectionAsync),单条与批量 Upsert/Get/Remove,以及核心的向量相似度检索(GetNearestMatchesAsync、GetNearestMatchAsync,以余弦相似度为默认度量)。VolatileMemoryStore是它的纯内存实现,适合原型与单测。ISemanticTextMemory(ISemanticTextMemory.cs)是"语义层"契约,屏蔽了 Embedding 计算细节,向上层提供:保存原文副本的SaveInformationAsync、仅存外部引用的SaveReferenceAsync、按键取回GetAsync、删除RemoveAsync、语义检索SearchAsync(默认limit = 1、minRelevanceScore = 0.7),以及GetCollectionsAsync。
TextMemoryPlugin 只依赖 ISemanticTextMemory,因此存储后端(内存、向量数据库)如何替换,对插件层完全透明——这正是 ADR 中"注册 Memory 能力并挂载向量数据库"在架构上的具体承载。从源码结构可以推断,这一"抽象存储 / 语义封装 / 插件暴露"的三层设计,正是为了让 Memory 能力与普通服务一样可组合、可替换、可注入。
总结:该决策的架构价值与后续演进
回顾 ADR-0013,它的本质是一次职责边界收编:
- 对 Kernel:卸下了"为每个能力开属性"的不可扩展包袱,回归服务编排与插件管理的中枢角色;
- 对 Memory:从"Kernel 的附庸"变为"一等公民插件",拥有独立项目
Plugins.Memory、独立 NuGet 程序集与独立的生命周期管理; - 对插件体系:确立了"能力以依赖注入方式注入到需要它的插件"这一通用范式,
TextMemoryPlugin与用户自定义MemoryPlugin共用同一套ISemanticTextMemory契约。
当前仓库中的 TextMemoryPlugin.cs、VolatileMemoryStore.cs、SemanticTextMemory.cs 以及 OpenAI_FunctionCallingWithMemoryPlugin.cs 样例,共同构成了对这一决策的完整实现与验证。如果你正在自己的应用中为 Agent 注入"长期记忆",这套"插件 + DI 注入"模式即是现成的可复制范本;同时建议持续跟踪仓库中 Vector Store 新模式的演进,它是该 ADR 所确立方向上更现代的接续。