你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。

适用于 Microsoft Agent Framework 的持久任务扩展

适用于 Microsoft Agent Framework 的 持久任务扩展将 持久执行引入 Microsoft Agent Framework。 可以通过使用扩展程序注册代理,使其能够自动持久化,具有持久会话、内置的 API 端点和分布式扩展功能,而无需更改代理逻辑。

何时使用持久代理

在需要时选择持久任务扩展:

  • 持续对话状态 ——代理会话能够在进程崩溃、重启和扩展事件中存活而不丢失上下文。
  • 多代理编排 ——在确定性工作流中协调专业代理,实现自动检查点和故障恢复。
  • 长期工作流 ——支持人工参与审批或定时等待,这些等待时间可持续数小时、数天甚至数周,且不消耗计算资源。
  • 可扩展、无服务器托管——在 Azure Functions Flex Consumption 计划下,可扩展至数千个并发代理会话(或零会话)。

如果不需要持久状态或多代理协调,则没有扩展的标准 Microsoft Agent Framework 代理可能已足够。

小窍门

有关包括本地设置、先决条件和部署在内的分步操作,请参阅 代理框架教程。 那份指南涵盖了应用 API 和托管。 本文涵盖了持久任务集成、后端配置、状态生命周期和操作。

建筑

扩展在内部实现 基于实体的代理循环,其中每个代理会话都是一个持久实体,可自动管理会话状态和检查点。

该扩展支持两种托管方法:

  • Azure Functions,使用 Azure Functions 集成包。
  • 使用基础包自备计算资源。

以下示例展示了每种语言和托管模型的功能。 生成的 HTTP 端点是 Functions 的集成功能;自托管应用会暴露并保护自身的 API。

语言 托管模型 持久代理和编排 基于图形的工作流
C# Azure Functions 代理示例 工作流示例
C# 自承载 代理示例 工作流示例
Python Azure Functions Functions 示例 函数工作流示例
Python 自承载 Worker 和客户端示例 独立工作流示例

Important

安装下方为您的托管模型展示的软件包,包括如有提示的预览包。 有关完整的应用程序,请参阅 源和示例。

源分支文档可以描述已发布的软件包中尚未提供的功能。 仅对已安装的版本中包括的功能应用配置和迁移步骤。

代理托管

使用标准 Microsoft Agent Framework 模式定义代理,然后使用 Durable Task 扩展对其进行增强。 该扩展会自动处理会话持久性、终结点创建和状态管理。

此示例使用 AIProjectClient 包 Azure.AI.Projects 及其 .AsAIAgent() 扩展与持久任务扩展集成。

var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
    ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT")
    ?? "gpt-4o-mini";

// Create an AI agent using the Microsoft Agent Framework pattern
AIAgent agent = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential())
    .AsAIAgent(
        model: deploymentName,
        instructions: "You are a professional content writer who creates engaging, "
                    + "well-structured documents for any given topic.",
        name: "DocumentPublisher");

// One line to make the agent durable with serverless hosting
using IHost app = FunctionsApplication
    .CreateBuilder(args)
    .ConfigureFunctionsWebApplication()
    .ConfigureDurableAgents(options => options.AddAIAgent(agent))
    .Build();
app.Run();

此示例使用 AIProjectClient 包 Azure.AI.Projects 及其 .AsAIAgent() 扩展与持久任务扩展集成。

var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
    ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT")
    ?? "gpt-4o-mini";

// Create an AI agent using the Microsoft Agent Framework pattern
AIAgent agent = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential())
    .AsAIAgent(
        model: deploymentName,
        instructions: "You are a professional content writer who creates engaging, "
                    + "well-structured documents for any given topic.",
        name: "DocumentPublisher");

// Host the agent with Durable Task Scheduler
string connectionString = "Endpoint=http://localhost:8080;TaskHub=default;Authentication=None";

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.ConfigureDurableAgents(
            options => options.AddAIAgent(agent),
            workerBuilder: builder => builder.UseDurableTaskScheduler(connectionString),
            clientBuilder: builder => builder.UseDurableTaskScheduler(connectionString));
    })
    .Build();

await host.StartAsync();

注释

完整的主机配置请参见 Agent Framework 设置指南以及 GitHub 上的示例。

使用持久检查点的多智能体业务流程

你可以在持久化编排中将多个专用智能体作为步骤进行协调。 每个代理调用都设置检查点,如果任何步骤失败,协调流程将自动恢复。 已完成的代理调用在恢复时不会被重新执行。

检查点不会让外部工具的副作用变成事务性的或恰好一次的。 使工具和活动操作具有幂等性,尤其是在它们发布文档、向账户收费或更新其他服务时。 在外部写入之后但在持久化提交之前发生故障,可能会导致该操作再次运行。

DurableAIAgent包装器确保调用被框架跟踪并进行检查点保存。

以下示例演示了一个顺序的多代理工作流,其中研究代理收集信息和编写器代理生成文档。

使用 context.GetAgent() 检索编排内的已注册代理。

[Function(nameof(DocumentPublishingOrchestration))]
public async Task<string> DocumentPublishingOrchestration(
    [OrchestrationTrigger] TaskOrchestrationContext context)
{
    var docRequest = context.GetInput<DocumentRequest>();

    DurableAIAgent researchAgent = context.GetAgent("ResearchAgent");
    DurableAIAgent writerAgent = context.GetAgent("DocumentPublisherAgent");

    // Step 1: Research the topic
    AgentResponse<ResearchResult> researchResult = await researchAgent
        .RunAsync<ResearchResult>(
            $"Research the following topic: {docRequest.Topic}");

    // Step 2: Write the document using the research findings
    AgentResponse<DocumentResponse> document = await writerAgent
        .RunAsync<DocumentResponse>(
            $"""Create a document about {docRequest.Topic}.
            Research findings: {researchResult.Result.Findings}""");

    // Step 3: Publish
    return await context.CallActivityAsync<string>(
        nameof(PublishDocument),
        new { docRequest.Topic, document.Result.Text });
}

用于 context.GetAgent() 检索编排内的注册代理。

static async Task<string> DocumentPublishingOrchestration(
    TaskOrchestrationContext context, DocumentRequest docRequest)
{
    DurableAIAgent researchAgent = context.GetAgent("ResearchAgent");
    DurableAIAgent writerAgent = context.GetAgent("DocumentPublisherAgent");

    // Step 1: Research the topic
    AgentResponse<ResearchResult> researchResult = await researchAgent
        .RunAsync<ResearchResult>(
            $"Research the following topic: {docRequest.Topic}");

    // Step 2: Write the document using the research findings
    AgentResponse<DocumentResponse> document = await writerAgent
        .RunAsync<DocumentResponse>(
            $"""Create a document about {docRequest.Topic}.
            Research findings: {researchResult.Result.Findings}""");

    // Step 3: Publish
    return await context.CallActivityAsync<string>(
        nameof(PublishDocument),
        new { docRequest.Topic, document.Result.Text });
}

使用 Microsoft Agent Framework 的基于图形的工作流

Durable Task 扩展还支持 Microsoft Agent Framework 工作流,该工作流使用声明性基于图形的编程模型(WorkflowBuilder)定义执行器和代理的多步骤管道。 该扩展会自动检查关系图中的每个步骤,并从故障中恢复,而无需更改工作流定义。

工作流与业务流程相辅相成:使用业务流程来利用条件逻辑进行命令性智能体协调,而使用工作流来利用类型经过验证的消息路由确定图形拓扑。

顺序工作流

以下示例将三个执行程序链接到订单取消工作流:查找订单、取消订单,然后发送确认电子邮件。

OrderLookup orderLookup = new();
OrderCancel orderCancel = new();
SendEmail sendEmail = new();

Workflow cancelOrder = new WorkflowBuilder(orderLookup)
    .WithName("CancelOrder")
    .WithDescription("Cancel an order and notify the customer")
    .AddEdge(orderLookup, orderCancel)
    .AddEdge(orderCancel, sendEmail)
    .Build();

using IHost app = FunctionsApplication
    .CreateBuilder(args)
    .ConfigureFunctionsWebApplication()
    .ConfigureDurableWorkflows(workflows => workflows.AddWorkflows(cancelOrder))
    .Build();
app.Run();

OrderLookup、OrderCancel 和 SendEmail 执行程序是标准Microsoft Agent Framework 执行程序,没有特定于 Durable 的代码。 有关完整的实现,请参阅 GitHub 上的样本。

string dtsConnectionString = Environment.GetEnvironmentVariable("DURABLE_TASK_SCHEDULER_CONNECTION_STRING")
    ?? "Endpoint=http://localhost:8080;TaskHub=default;Authentication=None";

OrderLookup orderLookup = new();
OrderCancel orderCancel = new();
SendEmail sendEmail = new();

Workflow cancelOrder = new WorkflowBuilder(orderLookup)
    .WithName("CancelOrder")
    .WithDescription("Cancel an order and notify the customer")
    .AddEdge(orderLookup, orderCancel)
    .AddEdge(orderCancel, sendEmail)
    .Build();

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.ConfigureDurableWorkflows(
            workflowOptions => workflowOptions.AddWorkflow(cancelOrder),
            workerBuilder: builder => builder.UseDurableTaskScheduler(dtsConnectionString),
            clientBuilder: builder => builder.UseDurableTaskScheduler(dtsConnectionString));
    })
    .Build();

await host.StartAsync();

IWorkflowClient workflowClient = host.Services.GetRequiredService<IWorkflowClient>();
IAwaitableWorkflowRun run = (IAwaitableWorkflowRun)await workflowClient.RunAsync(cancelOrder, "ORD-12345");
string? result = await run.WaitForCompletionAsync<string>();

OrderLookup、OrderCancel 和 SendEmail 执行程序是标准Microsoft Agent Framework 执行程序,没有特定于 Durable 的代码。 有关完整的实现,请参阅 GitHub 上的样本。

扇出/扇入(并发)工作流

你可以将任务分发到多个执行器或智能体并行运行,然后再汇总结果。 下面的示例并行向物理学家和化学家代理发送科学问题,然后聚合他们的回答。

ChatClient chatClient = new AzureOpenAIClient(
    new Uri(endpoint), new DefaultAzureCredential()).GetChatClient(deploymentName);

AIAgent physicist = chatClient.AsAIAgent(
    "You are a physics expert. Be concise (2-3 sentences).", "Physicist");
AIAgent chemist = chatClient.AsAIAgent(
    "You are a chemistry expert. Be concise (2-3 sentences).", "Chemist");

ParseQuestionExecutor parseQuestion = new();
AggregatorExecutor aggregator = new();

Workflow workflow = new WorkflowBuilder(parseQuestion)
    .WithName("ExpertReview")
    .AddFanOutEdge(parseQuestion, [physicist, chemist])
    .AddFanInBarrierEdge([physicist, chemist], aggregator)
    .Build();

using IHost app = FunctionsApplication
    .CreateBuilder(args)
    .ConfigureFunctionsWebApplication()
    .ConfigureDurableWorkflows(workflows => workflows.AddWorkflows(workflow))
    .Build();
app.Run();

ParseQuestionExecutor 和 AggregatorExecutor 是标准Microsoft Agent Framework 执行程序,没有特定于 Durable 的代码。 有关完整的实现,请参阅 GitHub 上的样本。

string dtsConnectionString = Environment.GetEnvironmentVariable("DURABLE_TASK_SCHEDULER_CONNECTION_STRING")
    ?? "Endpoint=http://localhost:8080;TaskHub=default;Authentication=None";

ChatClient chatClient = new AzureOpenAIClient(
    new Uri(endpoint), new DefaultAzureCredential()).GetChatClient(deploymentName);

ParseQuestionExecutor parseQuestion = new();
AIAgent physicist = chatClient.AsAIAgent(
    "You are a physics expert. Be concise (2-3 sentences).", "Physicist");
AIAgent chemist = chatClient.AsAIAgent(
    "You are a chemistry expert. Be concise (2-3 sentences).", "Chemist");
AggregatorExecutor aggregator = new();

Workflow workflow = new WorkflowBuilder(parseQuestion)
    .WithName("ExpertReview")
    .AddFanOutEdge(parseQuestion, [physicist, chemist])
    .AddFanInBarrierEdge([physicist, chemist], aggregator)
    .Build();

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.ConfigureDurableOptions(
            options => options.Workflows.AddWorkflow(workflow),
            workerBuilder: builder => builder.UseDurableTaskScheduler(dtsConnectionString),
            clientBuilder: builder => builder.UseDurableTaskScheduler(dtsConnectionString));
    })
    .Build();

await host.StartAsync();

IWorkflowClient workflowClient = host.Services.GetRequiredService<IWorkflowClient>();
IWorkflowRun run = await workflowClient.RunAsync(workflow, "Why is the sky blue?");

if (run is IAwaitableWorkflowRun awaitableRun)
{
    string? result = await awaitableRun.WaitForCompletionAsync<string>();
    Console.WriteLine(result);
}

ParseQuestionExecutor 和 AggregatorExecutor 是标准Microsoft Agent Framework 执行程序,没有特定于 Durable 的代码。 有关完整的实现,请参阅 GitHub 上的样本。

条件路由工作流

可以根据运行时结果将执行路由到不同的分支。 以下示例使用垃圾邮件检测代理对传入电子邮件进行分类,然后将路由到垃圾邮件处理程序或电子邮件助理代理。

AIAgent spamDetector = chatClient.AsAIAgent(
    "You are a spam detection assistant. Return JSON with is_spam (bool) and reason (string).",
    "SpamDetectionAgent");
AIAgent emailAssistant = chatClient.AsAIAgent(
    "You are an email assistant. Draft a professional response.",
    "EmailAssistantAgent");

SpamHandlerExecutor spamHandler = new();
EmailSenderExecutor emailSender = new();

Workflow workflow = new WorkflowBuilder(spamDetector)
    .WithName("EmailClassification")
    .AddSwitchCaseEdgeGroup(spamDetector, [
        new Case(condition: IsSpamDetected, target: spamHandler),
        new Default(target: emailAssistant),
    ])
    .AddEdge(emailAssistant, emailSender)
    .Build();

using IHost app = FunctionsApplication
    .CreateBuilder(args)
    .ConfigureFunctionsWebApplication()
    .ConfigureDurableWorkflows(workflows => workflows.AddWorkflows(workflow))
    .Build();
app.Run();

SpamHandlerExecutor 和 EmailSenderExecutor 是标准Microsoft Agent Framework 执行程序,没有特定于 Durable 的代码。 有关完整的实现,请参阅 GitHub 上的样本。

string dtsConnectionString = Environment.GetEnvironmentVariable("DURABLE_TASK_SCHEDULER_CONNECTION_STRING")
    ?? "Endpoint=http://localhost:8080;TaskHub=default;Authentication=None";

ChatClient chatClient = new AzureOpenAIClient(
    new Uri(endpoint), new DefaultAzureCredential()).GetChatClient(deploymentName);

AIAgent spamDetector = chatClient.AsAIAgent(
    "You are a spam detection assistant. Return JSON with is_spam (bool) and reason (string).",
    "SpamDetectionAgent");
AIAgent emailAssistant = chatClient.AsAIAgent(
    "You are an email assistant. Draft a professional response.",
    "EmailAssistantAgent");

SpamHandlerExecutor spamHandler = new();
EmailSenderExecutor emailSender = new();

Workflow workflow = new WorkflowBuilder(spamDetector)
    .WithName("EmailClassification")
    .AddSwitchCaseEdgeGroup(spamDetector, [
        new Case(condition: IsSpamDetected, target: spamHandler),
        new Default(target: emailAssistant),
    ])
    .AddEdge(emailAssistant, emailSender)
    .Build();

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.ConfigureDurableWorkflows(
            workflowOptions => workflowOptions.AddWorkflow(workflow),
            workerBuilder: builder => builder.UseDurableTaskScheduler(dtsConnectionString),
            clientBuilder: builder => builder.UseDurableTaskScheduler(dtsConnectionString));
    })
    .Build();

await host.StartAsync();

IWorkflowClient workflowClient = host.Services.GetRequiredService<IWorkflowClient>();
IAwaitableWorkflowRun run = (IAwaitableWorkflowRun)await workflowClient.RunAsync(workflow, "Check this email for spam");
string? result = await run.WaitForCompletionAsync<string>();

SpamHandlerExecutor 和 EmailSenderExecutor 是标准Microsoft Agent Framework 执行程序,没有特定于 Durable 的代码。 有关完整的实现,请参阅 GitHub 上的样本。

人机协同(HITL)工作流

可以在指定点暂停工作流执行,等待外部输入,然后再继续。 Microsoft Agent Framework 工作流模型使用 RequestPort 节点(.NET)或 ctx.request_info()(Python)来定义暂停点。 以下示例使用经理审批以及并行预算和合规性审批来实现支出报销工作流。

CreateApprovalRequest createRequest = new();
RequestPort<ApprovalRequest, ApprovalResponse> managerApproval =
    RequestPort.Create<ApprovalRequest, ApprovalResponse>("ManagerApproval");
PrepareFinanceReview prepareFinanceReview = new();
RequestPort<ApprovalRequest, ApprovalResponse> budgetApproval =
    RequestPort.Create<ApprovalRequest, ApprovalResponse>("BudgetApproval");
RequestPort<ApprovalRequest, ApprovalResponse> complianceApproval =
    RequestPort.Create<ApprovalRequest, ApprovalResponse>("ComplianceApproval");
ExpenseReimburse reimburse = new();

Workflow expenseApproval = new WorkflowBuilder(createRequest)
    .WithName("ExpenseReimbursement")
    .WithDescription("Expense reimbursement with manager and parallel finance approvals")
    .AddEdge(createRequest, managerApproval)
    .AddEdge(managerApproval, prepareFinanceReview)
    .AddFanOutEdge(prepareFinanceReview, [budgetApproval, complianceApproval])
    .AddFanInBarrierEdge([budgetApproval, complianceApproval], reimburse)
    .Build();

using IHost app = FunctionsApplication
    .CreateBuilder(args)
    .ConfigureFunctionsWebApplication()
    .ConfigureDurableWorkflows(workflows =>
        workflows.AddWorkflow(expenseApproval, exposeStatusEndpoint: true))
    .Build();
app.Run();

框架自动生成三个 HTTP 终结点用于 HITL 交互。

  • POST /api/workflows/{name}/run :开始工作流
  • GET /api/workflows/{name}/status/{id} :检查状态和待处理的审批
  • POST /api/workflows/{name}/respond/{id} :发送批准回复以恢复

以下记录类型定义流经工作流的数据:

public record ApprovalRequest(string ExpenseId, decimal Amount, string EmployeeName);
public record ApprovalResponse(bool Approved, string? Comments);

CreateApprovalRequest、PrepareFinanceReview 和 ExpenseReimburse 执行程序是标准Microsoft Agent Framework 执行程序,没有特定于 Durable 的代码。 有关完整的实现,请参阅 GitHub 上的样本。

string dtsConnectionString = Environment.GetEnvironmentVariable("DURABLE_TASK_SCHEDULER_CONNECTION_STRING")
    ?? "Endpoint=http://localhost:8080;TaskHub=default;Authentication=None";

CreateApprovalRequest createRequest = new();
RequestPort<ApprovalRequest, ApprovalResponse> managerApproval =
    RequestPort.Create<ApprovalRequest, ApprovalResponse>("ManagerApproval");
PrepareFinanceReview prepareFinanceReview = new();
RequestPort<ApprovalRequest, ApprovalResponse> budgetApproval =
    RequestPort.Create<ApprovalRequest, ApprovalResponse>("BudgetApproval");
RequestPort<ApprovalRequest, ApprovalResponse> complianceApproval =
    RequestPort.Create<ApprovalRequest, ApprovalResponse>("ComplianceApproval");
ExpenseReimburse reimburse = new();

Workflow expenseApproval = new WorkflowBuilder(createRequest)
    .WithName("ExpenseReimbursement")
    .AddEdge(createRequest, managerApproval)
    .AddEdge(managerApproval, prepareFinanceReview)
    .AddFanOutEdge(prepareFinanceReview, [budgetApproval, complianceApproval])
    .AddFanInBarrierEdge([budgetApproval, complianceApproval], reimburse)
    .Build();

IHost host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.ConfigureDurableWorkflows(
            options => options.AddWorkflow(expenseApproval),
            workerBuilder: builder => builder.UseDurableTaskScheduler(dtsConnectionString),
            clientBuilder: builder => builder.UseDurableTaskScheduler(dtsConnectionString));
    })
    .Build();

await host.StartAsync();

IWorkflowClient workflowClient = host.Services.GetRequiredService<IWorkflowClient>();
IStreamingWorkflowRun run = await workflowClient.StreamAsync(expenseApproval, "EXP-2025-001");

await foreach (WorkflowEvent evt in run.WatchStreamAsync())
{
    switch (evt)
    {
        case DurableWorkflowWaitingForInputEvent requestEvent:
            Console.WriteLine($"Workflow paused at: {requestEvent.RequestPort.Id}");
            ApprovalResponse approval = new(Approved: true, Comments: "Approved.");
            await run.SendResponseAsync(requestEvent, approval);
            break;

        case DurableWorkflowCompletedEvent completedEvent:
            Console.WriteLine($"Workflow completed: {completedEvent.Result}");
            break;
    }
}

以下记录类型定义流经工作流的数据:

public record ApprovalRequest(string ExpenseId, decimal Amount, string EmployeeName);
public record ApprovalResponse(bool Approved, string? Comments);

CreateApprovalRequest、PrepareFinanceReview 和 ExpenseReimburse 执行程序是标准Microsoft Agent Framework 执行程序,没有特定于 Durable 的代码。 有关完整的实现,请参阅 GitHub 上的样本。

持久任务计划程序仪表板

使用 Durable Task Scheduler 仪表板,全面了解您的持久任务代理、任务编排和基于图形的工作流:

  • 查看每个代理会话的对话历史记录
  • 检查工具调用和结构化输出
  • 跟踪编排和工作流执行流程
  • 监视性能指标

本地开发(通过模拟器)和生产部署都显示了相同的仪表板体验。

应用程序必须使用持久任务调度器后端以及您在仪表板中打开的同一任务中心。 Python 函数示例默认使用 Azure 存储;仅启动调度器模拟器并不会切换后端。 在期望这些会话显示在此之前,先配置 Functions 存储提供程序和调度器连接。

以下屏幕截图显示了一个代理会话,其中包含其会话历史记录和会话详细信息:

持久任务调度器仪表板截图,显示代理对话历史和会话详情。

以下屏幕截图显示了包含活动执行详细信息的确定性编排:

持久任务调度器仪表板截图,显示确定性代理编排视图。

持久代理的会话生存时间(TTL)

持久代理会话会自动维护会话历史记录和状态,这可能会无限期累积。 TTL(生存时间)功能可自动清理空闲会话,避免存储资源消耗并降低成本。

当代理会话闲置时间超过适用的 TTL 周期时,该会话将有资格被删除。 每个新的交互都会重置 TTL 计时器,从而延长会话的生存期。 清理并不保证在精确时间进行删除。

默认值

  • 旧版 .NET 默认 TTL:14 天。 在架构 v2 的带收据的状态下,未配置的旧版默认不会自动删除实体。 如果您想进行空闲会话删除,请明确配置全局或每个代理的 TTL。
  • 默认的 .NET 最小 TTL 删除延迟:5 分钟。 这个调度下限并不是保留期。

配置

可以全局或按代理配置 TTL。 代理会话过期时,将删除其整个状态,包括会话历史记录和任何自定义状态数据。 如果在删除后将消息发送到同一会话,则会使用新的会话历史记录创建新会话。

注释

以下 TTL 配置适用于 .NET。 Python 保留和状态预算选项与这种全会话 TTL 策略是分开的。

services.ConfigureDurableAgents(
    options =>
    {
        // Set global default TTL to 7 days
        options.DefaultTimeToLive = TimeSpan.FromDays(7);

        // Agent with custom TTL of 1 day
        options.AddAIAgent(shortLivedAgent, timeToLive: TimeSpan.FromDays(1));

        // Agent with custom TTL of 90 days
        options.AddAIAgent(longLivedAgent, timeToLive: TimeSpan.FromDays(90));

        // Agent using global default (7 days)
        options.AddAIAgent(defaultAgent);

        // null doesn't override the global default: this agent also uses 7 days
        options.AddAIAgent(inheritedAgent, timeToLive: null);
    });

要禁用没有有效的每个代理覆盖设置的代理的全局 TTL,请设置 options.DefaultTimeToLive = null。 传递 timeToLive: null 给 AddAIAgent 不会创建每个代理“永不过期”的覆盖。

单独的会话、历史和结果策略

全会话TTL会删除该实体,包括其会话和完成回执。 结果负载保留控制已完成响应可用的时间长短;在 .NET 中,ResultRetentionPeriod默认为 60 秒。 保留的完成回执仍可识别操作成功或失败,即使其结果负载变得不可用。

持久的转录本保留和模型-输入压缩解决了不同的问题。 .NET 默认为DurableAgentHistoryRetentionMode.KeepAll;选择启用Auto,以进行基于压力的转录记录保留。 Python 通过其主机选项提供保留和状态预算。 模型输入压缩减少了发送给模型的上下文,并不必然消除持久的历史记录。 请参阅 .NET 生命周期指南和 Python 保留指南,了解它们各自的具体默认值和限制。

Python 还支持可选的 SDK 管理的 Blob 负载卸载。 此传输功能不会取消实体状态容量限制,也不会取代保留期。 会话删除、结果过期和编排清除都不会删除这些负载 Blob。 单独配置 Blob 生命周期,只要持久状态或重放历史仍在引用它们,就保留 blob。

升级现有部署

模式-v2 状态和版本化实体身份需要部署计划。 不要替换现有 Hub 上的所有工作进程,并假设每个会话或工作流历史都能恢复。

  • .NET:新会话使用dafx-v2-实体命名空间。 在v1工作者保持活跃状态时,保持遗留处理处于禁用状态。 仅在所有 v1 工作者停止后启用 ProcessLegacyEntities 。 并排函数主机需要兼容的主机端工作项过滤;仅仅不同的触发器名称并不足以实现隔离。 不使用筛选,使用离线切换。 请参阅 .NET 升级和过滤要求。
  • Python:通过 Durable Task Scheduler 筛选明确选择two_phase,或选择isolated_v2用于带有升级后工作进程和客户端的隔离部署。 两阶段路径支持符合条件的就地实体升级;每次迁移都不需要新的任务中心。 在共存期间保持兼容的筛选工作进程处于可用状态,并在启用历史名称处理前停止旧工作进程。 参见 Python 实体迁移。
  • Python 工作流程历史:实体迁移并不能修复重放兼容性。 受影响的旧工作流历史记录,包括较早的 v2 历史记录,必须在其原始 worker 和 hub 上完成。 在升级后的运行时上启动新的工作流实例。 请参阅 Python 运行时兼容性指南。

已知的限制

  • 最大对话大小。
    代理会话状态受持久后端状态大小限制的约束。 使用 持久任务计划程序时,最大实体状态大小为 1 MB。 历史保留可以移除符合条件的转录内容,但受保护的状态、完成收据和实时结果也会占用容量。 无论是压缩还是 Blob 负载卸载,都不能保证能够容纳得下该实体。 配置状态预算,监控容量故障,并在受保护状态无法容纳时使用新会话。

  • 延迟。
    所有代理交互都通过 Durable Task Scheduler 进行路由,这增加了与内存中代理执行相比的延迟。 这种权衡在提供持久性和分布式缩放方面具有优点。

  • 流媒体。
    由于持久代理是在持久实体的基础上实现的,因此基础通信模型是请求/响应。 通过响应回调支持流式传输(例如,将令牌推送至 Redis Stream 供客户端使用),而在流处理完成后,实体会返回完整的响应。

    在 Python Redis 流式示例中,区块和完成标记是临时的。 它们可能在保留检查和持久化提交之前到达。 在将流式输出视为已提交之前,请单独确认权威结果。

  • TTL到期。
    TTL 计时器基于自上次消息以来的时钟时间,而不是累积活动时间。 删除会话(通过 TTL 过期或手动删除)后,无法恢复其会话历史记录。

生产检查与故障排除

对于生成的 .NET Functions 代理端点,202 Accepted表示已分派,而非成功执行。 等待中的请求会返回 200,表示可用的已提交成功;对于受支持的已提交终端失败,则返回 500。 410 Gone 表示已知已完成但结果不可得;保留的结果可以是 succeeded 或 failed。 这不一定是执行失败,也不一定只是结果过期。 不要在 410 之后自动提交新操作。 这些是代理端点语义,而非 Durable Functions 编排状态 API。 参见 代理完成结果。

将应用程序用户授权与函数键、模型凭据和调度器访问分开。 在接受会话 ID 或审批响应之前强制执行所有权;会话和请求 ID 是标识符,而非授权。 向目标工作者或客户端身份授予模型和调度器权限。

问题 检查
Python Functions 主机无法加载或启动 使用 Python 3.13 或更高版本,在代理托管中安装软件包,并明确选择部署策略。
调度程序仪表板中不显示任何会话 确认应用程序使用调度器后端,而非 Azure 存储,并且端点和任务中心与仪表板匹配。
旧运行在升级后失败 在恢复历史运行之前,检查工作程序生成、派遣筛选器、实体迁移前提条件以及工作流重放兼容性。
状态写入尽管压缩仍失败 检查整体实体容量、受保护状态和保留设置。 仅靠模型上下文大小无法衡量存储实体的大小。
流结束了,但结果不可用 检查持久完成结果和结果保留策略;流标记不是持久提交证据。

其他功能

GitHub上的samples中提供了以下高级模式,但本文未作详细介绍:

模式 说明
长时间运行的工具 代理可以通过工具调用启动持久编排,从而启用能够长时间运行并跟踪进度的工具。
代理作为 MCP 工具 将持久代理公开为 模型上下文协议 (MCP) 工具,允许其他代理或客户端通过标准接口调用它们。
可靠的流式传输 使用 Redis Streams(或类似传输)进行可恢复的令牌流式传输,以便在客户端断开连接和重新连接后续存。

后续步骤