MAF 中间件管道架构:企业级 Agent 的三层拦截体系
一句话简介
MAF 提供三层中间件架构,分别拦截 ChatClient 调用、Agent 运行和工具调用,实现日志、限流、权限等企业级横切关注点。
🎯 核心价值
-
✅ 三层拦截:ChatClient 层、Agent Run 层、Function Invocation 层 -
✅ 职责分离:每层处理不同粒度的横切关注点 -
✅ 灵活组合:可独立或组合使用,按需配置
📝 三层中间件架构
各层职责对比
|
|
|
|
|
|---|---|---|---|
| Agent Run | RunAsync()
|
|
|
| ChatClient |
|
|
|
| Function |
|
|
|
💻 实现方式
1. ChatClient 中间件
使用 MEAI 的 DelegatingChatClient 或 Use() 方法:
var chatClient = AIClientHelper.GetDefaultChatClient()
.AsBuilder()
.Use(getResponseFunc: async (messages, options, innerClient, ct) =>
{
Console.WriteLine($"📊 [ChatClient] 请求消息数: {messages.Count()}");
var response = await innerClient.GetResponseAsync(messages, options, ct);
Console.WriteLine($"📊 [ChatClient] Token: {response.Usage?.TotalTokenCount}");
return response;
})
.Build();
核心要点:
-
🔧 拦截每次 LLM 调用 -
🔧 可访问完整的请求和响应 -
🔧 适用于监控、限流、缓存等场景
2. Agent Run 中间件
使用 AgentBuilder.Use() 添加:
var agent = chatClient.CreateAIAgent(instructions: "你是智能助手")
.AsBuilder()
.Use(async (messages, thread, options, innerAgent, ct) =>
{
Console.WriteLine($"🛡️ [Agent Run] Pre-Run 检查");
var response = await innerAgent.RunAsync(messages, thread, options, ct);
Console.WriteLine($"🛡️ [Agent Run] Post-Run 完成");
return response;
}, null)
.Build();
核心要点:
-
🛡️ 包裹整个 Agent 执行流程 -
🛡️ 适用于安全检查、审计日志 -
🛡️ 每次 RunAsync()只触发一次
3. Function Invocation 中间件
拦截工具函数的执行:
var agent = chatClient.CreateAIAgent(...)
.AsBuilder()
.Use(async (agent, context, next, ct) =>
{
Console.WriteLine($"🔧 [Function] 调用: {context.Function.Name}");
var result = await next(context, ct);
Console.WriteLine($"🔧 [Function] 结果: {result}");
return result;
})
.Build();
核心要点:
-
🔧 拦截每个工具函数调用 -
🔧 可修改参数或覆盖结果 -
🔧 适用于权限检查、Mock 数据
🏢 企业级最佳实践
推荐的中间件组合
// 1️⃣ ChatClient 层:监控和性能
var chatClient = baseChatClient.AsBuilder()
.Use(new TokenMonitoringMiddleware())
.Use(new RateLimitingMiddleware())
.Build();
// 2️⃣ Agent 层:安全和审计
var agent = chatClient.CreateAIAgent(...)
.AsBuilder()
.Use(PIIFilterMiddleware, null) // PII 过滤
.Use(GuardrailsMiddleware, null) // 内容安全
.Use(FunctionLoggingMiddleware) // 工具日志
.Build();
各层职责建议
|
|
|
|---|---|
| ChatClient |
|
| Agent Run |
|
| Function |
|
🎯 总结
-
✅ 三层架构:ChatClient、Agent Run、Function Invocation 各司其职 -
✅ 洋葱模型:请求从外向内,响应从内向外 -
✅ 灵活组合:根据需求选择合适的中间件层级 -
✅ 企业级应用:安全检查最外层,性能优化靠内层
如需获取文章配套完整代码,可扫码咨询领取。👇

