You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向Microsoft Agent Framework代理传入初始上下文参数?

针对Microsoft Agent Framework传入客户参数的优化方案

方案1:自定义WorkflowContext扩展属性

直接扩展框架的WorkflowContext,添加业务所需的CustomerId等参数,整个工作流管道的执行器都能直接访问,无需通过消息传递:

// 自定义工作流上下文,继承默认实现
public class CustomerAwareWorkflowContext : DefaultWorkflowContext
{
    // 添加客户ID属性
    public string CustomerId { get; set; } = string.Empty;
}

// 创建代理实例时初始化自定义上下文
var customerContext = new CustomerAwareWorkflowContext
{
    CustomerId = "CUST-12345"
};

// 传入上下文创建代理
var customAgent = new YourCustomAgent(customerContext);

这种方式最直接,符合将参数存在WorkflowContext的预期,所有执行器可直接通过context.WorkflowContext.CustomerId获取值,完全规避消息过滤的不稳定问题。

方案2:利用WorkflowContext的Items字典注入

如果不想自定义上下文类,可直接使用默认WorkflowContext内置的Items字典存储全局参数,在工作流启动前完成注入:

// 初始化默认上下文并注入客户ID
var workflowContext = new DefaultWorkflowContext();
workflowContext.Items["CustomerId"] = "CUST-12345";

// 将上下文传入代理或工作流
var agent = new YourCustomAgent(workflowContext);

或者通过前置执行器实现参数注入(适合动态传递参数的场景):

// 自定义前置执行器,负责注入客户ID
public class CustomerIdInjectorExecutor : IWorkflowExecutor
{
    private readonly string _customerId;

    public CustomerIdInjectorExecutor(string customerId)
    {
        _customerId = customerId;
    }

    public async Task ExecuteAsync(WorkflowExecutionContext context, CancellationToken cancellationToken)
    {
        // 将客户ID存入全局上下文
        context.WorkflowContext.Items["CustomerId"] = _customerId;
        // 继续执行后续管道步骤
        await context.NextAsync(cancellationToken);
    }
}

// 构建工作流管道时将该执行器放在最前面
var pipelineBuilder = new WorkflowPipelineBuilder();
pipelineBuilder.Use<CustomerIdInjectorExecutor>("CUST-12345");
// 添加其他业务执行器
pipelineBuilder.Use<YourBusinessExecutor>();

var pipeline = pipelineBuilder.Build();

额外建议

由于框架处于预览阶段,API可能存在变动:

  • 优先使用WorkflowContext相关的扩展或内置存储方案,这是框架设计用于共享工作流全局数据的标准方式
  • 可关注官方GitHub仓库的更新日志和Issue区,很多预览版的最佳实践会在社区讨论中出现

内容的提问来源于stack exchange,提问作者sjhuk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.11 17:42:34