Microsoft Agent Framework는 완료하는 데 시간이 걸릴 수 있는 장기 실행 작업을 처리하기 위한 백그라운드 응답을 지원합니다. 이 기능을 사용하면 에이전트가 요청 처리를 시작하고 결과를 폴링하거나 중단된 스트림을 다시 시작하는 데 사용할 수 있는 연속 토큰을 반환할 수 있습니다.
Tip
전체 작업 예제는 백그라운드 응답 샘플을 참조하세요.
백그라운드 응답을 사용하는 경우
배경 응답은 다음 작업에 특히 유용합니다.
- 상당한 처리 시간이 필요한 복잡한 추론 작업
- 네트워크 문제 또는 클라이언트 시간 제한으로 인해 중단될 수 있는 작업
- 장기 실행 작업을 시작하고 나중에 결과를 다시 확인하려는 시나리오
백그라운드 응답의 작동 방식
백그라운드 응답은 연속 토큰 메커니즘을 사용하여 장기 실행 작업을 처리합니다. 백그라운드 응답을 사용하도록 설정된 에이전트에 요청을 보내면 다음 두 가지 중 하나가 발생합니다.
- 즉시 완료: 에이전트가 작업을 신속하게 완료하고 연속 토큰 없이 최종 응답을 반환합니다.
- 백그라운드 처리: 에이전트가 백그라운드에서 처리를 시작하고 최종 결과 대신 연속 토큰을 반환합니다.
연속 토큰에는 비 스트리밍 에이전트 API를 사용하여 완료를 폴링하거나 스트리밍 에이전트 API를 사용하여 중단된 스트림을 다시 시작하는 데 필요한 모든 정보가 포함됩니다. 없는 토큰(null.NET, None Python 또는 Go의 빈 문자열)은 작업이 완료되었거나, 실패했거나, 사용자 입력이 필요한 경우 더 이상 진행할 수 없음을 의미합니다.
백그라운드 응답 사용
백그라운드 응답을 사용하려면 속성을 AllowBackgroundResponses 다음으로 설정합니다true.AgentRunOptions
using Microsoft.Agents.AI;
AgentRunOptions options = new()
{
AllowBackgroundResponses = true
};
비고
현재 OpenAI 응답 API를 사용하는 에이전트만 백그라운드 응답을 지원합니다. OpenAI 응답 에이전트 및 Azure OpenAI 응답 에이전트.
일부 에이전트는 백그라운드 응답에 대한 명시적 제어를 허용하지 않을 수 있습니다. 이러한 에이전트는 설정에 관계없이 작업의 복잡성에 따라 백그라운드 응답을 시작할지 여부를 자율적으로 결정할 수 있습니다 AllowBackgroundResponses .
비 스트리밍 백그라운드 응답
비 스트리밍 시나리오의 경우 에이전트를 처음 실행할 때 연속 토큰을 반환하거나 반환하지 않을 수 있습니다. 연속 토큰이 반환되지 않으면 작업이 완료되었음을 의미합니다. 연속 토큰이 반환되면 에이전트가 여전히 처리 중인 백그라운드 응답을 시작했으며 최종 결과를 검색하기 위해 폴링이 필요했음을 나타냅니다.
using System;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
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();
// Get initial response - may return with or without a continuation token.
AgentResponse response = await agent.RunAsync(
"Write a very long novel about otters in space.",
session,
options);
// Continue to poll until the final response is received
while (response.ContinuationToken is not null)
{
// Wait before polling again.
await Task.Delay(TimeSpan.FromSeconds(2));
options.ContinuationToken = response.ContinuationToken;
response = await agent.RunAsync(session, options);
}
Console.WriteLine(response.Text);
Warning
DefaultAzureCredential 은 개발에 편리하지만 프로덕션 환경에서 신중하게 고려해야 합니다. 프로덕션 환경에서는 특정 자격 증명(예: ManagedIdentityCredential)을 사용하여 대기 시간 문제, 의도하지 않은 자격 증명 검색 및 대체 메커니즘의 잠재적인 보안 위험을 방지하는 것이 좋습니다.
핵심 사항:
- 초기 호출은 즉시 완료되거나(연속 토큰 없음) 백그라운드 작업을 시작할 수 있습니다(연속 토큰 사용).
- 연속 토큰이 반환되지 않으면 작업이 완료되고 응답에 최종 결과가 포함됩니다.
- 연속 토큰이 반환되면 에이전트가 폴링이 필요한 백그라운드 프로세스를 시작했습니다.
- 후속 폴링 호출에서 이전 응답의 연속 토큰 사용
- 이 경우
ContinuationTokennull작업이 완료됩니다.
스트리밍 백그라운드 응답
스트리밍 시나리오에서 백그라운드 응답은 일반 스트리밍 응답과 매우 유사하게 작동합니다. 에이전트는 모든 업데이트를 실시간으로 소비자에게 다시 스트리밍합니다. 그러나 주요 차이점은 원래 스트림이 중단되면 에이전트가 연속 토큰을 통해 스트림 재개를 지원한다는 것입니다. 각 업데이트에는 현재 상태를 캡처하는 연속 토큰이 포함되어 있으므로 이 토큰을 후속 스트리밍 API 호출에 전달하여 스트림이 중단된 위치에서 스트림을 다시 시작할 수 있습니다.
using System;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
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();
AgentResponseUpdate? latestReceivedUpdate = null;
await foreach (var update in agent.RunStreamingAsync(
"Write a very long novel about otters in space.",
session,
options))
{
Console.Write(update.Text);
latestReceivedUpdate = update;
// Simulate an interruption
break;
}
// Resume from interruption point captured by the continuation token
options.ContinuationToken = latestReceivedUpdate?.ContinuationToken;
await foreach (var update in agent.RunStreamingAsync(session, options))
{
Console.Write(update.Text);
}
핵심 사항:
- 각
AgentResponseUpdate항목에는 다시 시작에 사용할 수 있는 연속 토큰이 포함됩니다. - 중단 전에 마지막으로 받은 업데이트의 연속 토큰 저장
- 저장된 연속 토큰을 사용하여 중단 지점에서 스트림 다시 시작
Tip
실행 가능한 전체 예제는 .NET 샘플 참조하세요.
Tip
전체 작업 예제는 백그라운드 응답 샘플을 참조하세요.
백그라운드 응답 사용
백그라운드 응답을 사용하도록 설정하려면 다음을 호출background할 agent.run() 때 옵션을 전달합니다.
session = agent.create_session()
response = await agent.run(
messages="Your prompt here",
session=session,
options={"background": True},
)
비고
OpenAI 응답 API, Azure OpenAI 응답 API 또는 Microsoft Foundry에서 지원하는 에이전트를 Python 백그라운드 응답을 지원합니다.
백그라운드 응답은 FoundryChatClient공급자 쪽 응답 스토리지() 또는 상태 비저장 재생store=False(store=True)을 사용하여 로컬 함수 도구를 실행할 수 있습니다. 다시 시작된 응답이 로컬 도구 루프를 계속할 수 있도록 폴링하는 동안 동일한 세션을 유지합니다.
비 스트리밍 백그라운드 응답
비 스트리밍 시나리오의 경우 에이전트를 처음 실행할 background=Truecontinuation_token때 . 이 continuation_token경우 None 작업이 완료되었습니다. 그렇지 않으면 후속 호출에서 토큰을 다시 전달하여 폴링합니다.
import asyncio
from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient
agent = Agent(
name="researcher",
instructions="You are a helpful research assistant.",
client=OpenAIChatClient(model="o3"),
)
session = agent.create_session()
# Start a background run — returns immediately
response = await agent.run(
messages="Briefly explain the theory of relativity in two sentences.",
session=session,
options={"background": True},
)
# Poll until the operation completes
while response.continuation_token is not None:
await asyncio.sleep(2)
response = await agent.run(
session=session,
options={"continuation_token": response.continuation_token},
)
# Done — response.text contains the final result
print(response.text)
요점
- 초기 호출은 즉시 완료되거나(연속 토큰 없음) 백그라운드 작업을 시작할 수 있습니다(연속 토큰 사용).
-
continuation_token후속 폴링 호출에서 이전 응답에서 사용 - 이 경우
continuation_tokenNone작업이 완료됩니다.
스트리밍 백그라운드 응답
스트리밍 시나리오에서 백그라운드 응답은 일반 스트리밍처럼 작동합니다. 에이전트 스트림은 실시간으로 다시 업데이트됩니다. 주요 차이점은 각 업데이트에 연결이 중단된 경우 스트림 다시 시작을 사용하도록 설정하는 기능이 포함되어 continuation_token있다는 것입니다.
session = agent.create_session()
# Start a streaming background run
last_token = None
stream = agent.run(
messages="Briefly list three benefits of exercise.",
stream=True,
session=session,
options={"background": True},
)
# Read chunks — each update carries a continuation_token
async for update in stream:
last_token = update.continuation_token
if update.text:
print(update.text, end="", flush=True)
# If interrupted (e.g., network issue), break and resume later
중단된 스트림 다시 열림
스트림이 중단된 경우 마지막 continuation_token 스트림을 사용하여 중단된 위치에서 다시 시작합니다.
if last_token is not None:
stream = agent.run(
stream=True,
session=session,
options={"continuation_token": last_token},
)
async for update in stream:
if update.text:
print(update.text, end="", flush=True)
요점
- 각
AgentResponseUpdate항목에는 for resumption이continuation_token포함됩니다. - 중단 전에 마지막으로 받은 업데이트의 토큰 저장
- 저장된 토큰
options={"continuation_token": token}을 통해 전달하여 다시 시작
백그라운드 응답 사용
실행을 시작할 때 전달 agent.AllowBackgroundResponses(true) 하고 agent.WithSession(session). 공급자 및 배포는 백그라운드 실행을 지원해야 합니다. 옵션을 설정해도 모든 에이전트가 비동기화되지는 않습니다.
비 스트리밍 백그라운드 응답
작업을 시작한 다음 비어 있지 않은 동안 response.ContinuationToken 폴링합니다.
a.Run(ctx, nil, ...)계속하지 않음RunText: 연속 호출에 새 메시지가 포함되어서는 안 되며 계속 진행합니다.
유지 관리되는 Azure OpenAI 응답 샘플은 시간 제한으로 작업을 제한하고, 설문 조사 간에 대기하고, 취소 시 즉시 중지합니다.
// Copyright (c) Microsoft. All rights reserved.
// This sample demonstrates long-running agent operations using the OpenAI
// Responses API "background" option. A background run returns quickly with a
// continuation token instead of the final answer; the caller then polls with
// that token until the operation completes.
//
// Ported from the Python getting-started "background responses" sample.
package main
import (
"context"
"time"
"github.com/microsoft/agent-framework-go/agent"
"github.com/microsoft/agent-framework-go/examples/internal/demo"
"github.com/microsoft/agent-framework-go/provider/openaiprovider"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/azure"
"github.com/openai/openai-go/v3/option"
)
var logger = demo.NewLogger(
"Background Responses",
"Starts a background Responses run and polls with the continuation token until it completes.",
"Model", demo.Deployment,
)
func main() {
// Bound the whole sample so a run that never completes (stuck queued, a bad
// continuation token, etc.) cannot hang indefinitely.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
token := demo.AzureTokenCredential()
client := openai.NewClient(
option.WithBaseURL(demo.Endpoint),
azure.WithTokenCredential(token),
)
researcher := openaiprovider.NewResponsesAgent(
client,
openaiprovider.AgentConfig{
Model: demo.Deployment,
Instructions: "You are a helpful research assistant. Be concise.",
Config: agent.Config{
Name: "Researcher",
Middlewares: []agent.Middleware{logger},
},
},
)
// Background runs are tied to a session so that follow-up polls target the
// same operation.
session, err := researcher.CreateSession(ctx)
if err != nil {
demo.Panic(err)
}
// Start a background run. It returns quickly with a continuation token
// rather than the final answer. (If the model or endpoint does not support
// background execution, the run simply completes inline with no token.)
resp, err := researcher.RunText(ctx,
"Briefly explain the theory of relativity in two sentences.",
agent.WithSession(session),
agent.AllowBackgroundResponses(true),
).Collect()
if err != nil {
demo.Panic(err)
}
// Poll until the operation completes — i.e. until a run no longer returns a
// continuation token. Continuation runs must not carry any messages, so use
// Run with a nil message slice.
for resp.ContinuationToken != "" {
// Wait between polls, but stop promptly if the context is cancelled or
// its deadline is reached rather than sleeping through it.
select {
case <-ctx.Done():
demo.Panic(ctx.Err())
case <-time.After(2 * time.Second):
}
resp, err = researcher.Run(ctx, nil,
agent.WithSession(session),
agent.WithContinuationToken(resp.ContinuationToken),
).Collect()
if err != nil {
demo.Panic(err)
}
}
// The final response holds the completed result.
demo.Response(resp, nil)
}
AZURE_OPENAI_DEPLOYMENT_NAME이 샘플을 실행하기 전에 Azure 자격 증명을 설정하고 AZURE_OPENAI_ENDPOINT 인증합니다. 폴링이 완료된 후 완료된 응답을 출력합니다. 즉시 완료된 응답에는 연속 토큰이 없으며 폴링이 필요하지 않습니다.
스트리밍 백그라운드 응답
및 agent.AllowBackgroundResponses(true).를 사용하여 스트리밍 실행을 agent.Stream(true) 시작합니다. 받은 마지막 업데이트의 연속 토큰을 유지합니다. 연결이 중단된 경우 새 메시지 없이 다시 시작합니다.
for update, err := range a.Run(
ctx,
nil,
agent.WithSession(session),
agent.WithContinuationToken(lastToken),
agent.Stream(true),
) {
if err != nil {
panic(err)
}
lastToken = update.ContinuationToken
fmt.Print(update.String())
}
저장된 토큰이 비어 있지 않은 경우에만 다시 시작합니다. 작업이 프로세스를 다시 시작해야 하는 경우 애플리케이션 스토리지에서 세션과 토큰을 모두 유지합니다.
Harness 에이전트에서 백그라운드 응답 사용
Harness 에이전트는 표준 에이전트 프레임워크 에이전트로 유지되므로 공급자 백그라운드 응답은 위에서 설명한 실행당 동일한 옵션을 사용합니다. Harness 생성은 .NET, options={"background": True} Python 또는 agent.AllowBackgroundResponses(true) 실행을 시작할 때 Go에서 설정 AllowBackgroundResponses 되는 공급자 백그라운드 응답을 자동으로 사용하도록 설정하지 않습니다. 작업이 프로세스를 다시 시작해야 하는 경우 세션을 유지하고 연속 토큰을 유지합니다.
이는 하나의 공급자 요청을 계속하지 않고 자식 에이전트에 작업을 위임하는 백그라운드 에이전트와는 별개입니다.
모범 사례
백그라운드 응답을 사용할 때는 다음 모범 사례를 고려합니다.
- 적절한 폴링 간격을 구현하여 서비스 압도 방지
- 작업이 예상보다 오래 걸리는 경우 폴링 간격에 지수 백오프 사용
-
처리가 완료된 시기를 확인하기 위해 부재 중인 연속 토큰(
nullNone또는 빈 Go 문자열)을 확인합니다. - 사용자 세션에 걸쳐 있을 수 있는 작업에 대해 연속 토큰을 영구적으로 저장하는 것이 좋습니다.
제한 사항 및 고려 사항
- 백그라운드 응답은 장기 실행 작업을 지원하는 기본 AI 서비스에 따라 달라집니다.
- 모든 에이전트 유형이 백그라운드 응답을 지원할 수 있는 것은 아닙니다.
- 네트워크 중단 또는 클라이언트를 다시 시작하려면 연속 토큰을 유지하기 위해 특별한 처리가 필요할 수 있습니다.