后台响应
MAF 支持后台响应来处理长时间运行的操作,这些操作可能需要一段时间才能完成。此功能使 Agent 能够开始处理请求并返回延续令牌,用于轮询结果或恢复中断的流。
适用场景
后台响应特别适用于:
- 需要大量处理时间的复杂推理任务
- 网络问题或客户端超时可能中断的操作
- 启动长时间运行的任务后稍后查看结果
工作原理
后台响应使用延续令牌机制。向启用了后台响应的 Agent 发送请求时,会发生两种情况之一:
- 立即完成:Agent 快速完成任务并返回最终响应,无需延续令牌
- 后台处理:Agent 开始在后台进行处理,返回延续令牌而不是最终结果
延续令牌包含使用非流式代理 API 轮询完成的所有必要信息。当延续令牌为 null 时,操作已完成。
启用后台响应
csharp
AgentRunOptions options = new()
{
AllowBackgroundResponses = true
};目前只有使用 OpenAI 响应 API 的 Agent 支持后台响应:OpenAI 响应代理和 Azure OpenAI 响应代理。
非流式后台响应
csharp
AIAgent agent = new AIProjectClient(
new Uri("<your-foundry-project-endpoint>"),
new DefaultAzureCredential())
.AsAIAgent(
model: "<deployment-name>",
instructions: "You are a helpful assistant.");
AgentRunOptions options = new()
{
AllowBackgroundResponses = true
};
AgentSession session = await agent.CreateSessionAsync();
// 初始调用——可能立即完成,也可能启动后台操作
AgentResponse response = await agent.RunAsync(
"Write a very long novel about otters in space.",
session, options);
// 轮询直到获得最终结果
while (response.ContinuationToken is not null)
{
await Task.Delay(TimeSpan.FromSeconds(2));
options.ContinuationToken = response.ContinuationToken;
response = await agent.RunAsync(session, options);
}
Console.WriteLine(response.Text);要点:
- 初始调用可能立即完成(无延续令牌)或启动后台操作(有延续令牌)
- 如果未返回延续令牌,操作已完成,响应包含最终结果
- 如果返回延续令牌,Agent 仍在后台处理,需使用
options.ContinuationToken轮询 - 当延续令牌为
null时,操作最终完成
下一步:RAG 检索增强生成 — 为 Agent 添加知识库检索能力。