Microsoft Agent Framework는 완료하는 데 시간이 걸릴 수 있는 장기 실행 작업을 처리하기 위한 백그라운드 응답을 지원합니다. 이 기능을 사용하면 에이전트가 요청 처리를 시작하고 결과를 폴링하거나 중단된 스트림을 다시 시작하는 데 사용할 수 있는 연속 토큰을 반환할 수 있습니다.
팁 (조언)
전체 작업 예제는 백그라운드 응답 샘플을 참조하세요.
백그라운드 응답을 사용하는 경우
배경 응답은 다음 작업에 특히 유용합니다.
- 상당한 처리 시간이 필요한 복잡한 추론 작업
- 네트워크 문제 또는 클라이언트 시간 제한으로 인해 중단될 수 있는 작업
- 장기 실행 작업을 시작하고 나중에 결과를 다시 확인하려는 시나리오
백그라운드 응답의 작동 방식
백그라운드 응답은 연속 토큰 메커니즘을 사용하여 장기 실행 작업을 처리합니다. 백그라운드 응답을 사용하도록 설정된 에이전트에 요청을 보내면 다음 두 가지 중 하나가 발생합니다.
- 즉시 완료: 에이전트가 작업을 신속하게 완료하고 연속 토큰 없이 최종 응답을 반환합니다.
- 백그라운드 처리: 에이전트가 백그라운드에서 처리를 시작하고 최종 결과 대신 연속 토큰을 반환합니다.
연속 토큰에는 비 스트리밍 에이전트 API를 사용하여 완료를 폴링하거나 스트리밍 에이전트 API를 사용하여 중단된 스트림을 다시 시작하는 데 필요한 모든 정보가 포함됩니다. 연속 토큰이 있으면 작업이 완료됩니다 null. 백그라운드 응답이 완료되었거나, 실패했거나, 더 이상 진행할 수 없는 경우(예: 사용자 입력이 필요한 경우) 이 작업이 완료됩니다.
백그라운드 응답 사용
백그라운드 응답을 사용하려면 속성을 AllowBackgroundResponses 다음으로 설정합니다true.AgentRunOptions
AgentRunOptions options = new()
{
AllowBackgroundResponses = true
};
비고
현재 OpenAI 응답 API를 사용하는 에이전트만 백그라운드 응답을 지원합니다. OpenAI 응답 에이전트 및 Azure OpenAI 응답 에이전트.
일부 에이전트는 백그라운드 응답에 대한 명시적 제어를 허용하지 않을 수 있습니다. 이러한 에이전트는 설정에 관계없이 작업의 복잡성에 따라 백그라운드 응답을 시작할지 여부를 자율적으로 결정할 수 있습니다 AllowBackgroundResponses .
비 스트리밍 백그라운드 응답
비 스트리밍 시나리오의 경우 에이전트를 처음 실행할 때 연속 토큰을 반환하거나 반환하지 않을 수 있습니다. 연속 토큰이 반환되지 않으면 작업이 완료되었음을 의미합니다. 연속 토큰이 반환되면 에이전트가 여전히 처리 중인 백그라운드 응답을 시작했으며 최종 결과를 검색하기 위해 폴링이 필요했음을 나타냅니다.
AIAgent agent = new AzureOpenAIClient(
new Uri("https://<myresource>.openai.azure.com"),
new DefaultAzureCredential())
.GetOpenAIResponseClient("<deployment-name>")
.AsAIAgent();
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);
경고
DefaultAzureCredential 은 개발에 편리하지만 프로덕션 환경에서 신중하게 고려해야 합니다. 프로덕션 환경에서는 특정 자격 증명(예: ManagedIdentityCredential)을 사용하여 대기 시간 문제, 의도하지 않은 자격 증명 검색 및 대체 메커니즘의 잠재적인 보안 위험을 방지하는 것이 좋습니다.
핵심 내용:
- 초기 호출은 즉시 완료되거나(연속 토큰 없음) 백그라운드 작업을 시작할 수 있습니다(연속 토큰 사용).
- 연속 토큰이 반환되지 않으면 작업이 완료되고 응답에 최종 결과가 포함됩니다.
- 연속 토큰이 반환되면 에이전트가 폴링이 필요한 백그라운드 프로세스를 시작했습니다.
- 후속 폴링 호출에서 이전 응답의 연속 토큰 사용
- 이 경우
ContinuationTokennull작업이 완료됩니다.
스트리밍 백그라운드 응답
스트리밍 시나리오에서 백그라운드 응답은 일반 스트리밍 응답과 매우 유사하게 작동합니다. 에이전트는 모든 업데이트를 실시간으로 소비자에게 다시 스트리밍합니다. 그러나 주요 차이점은 원래 스트림이 중단되면 에이전트가 연속 토큰을 통해 스트림 재개를 지원한다는 것입니다. 각 업데이트에는 현재 상태를 캡처하는 연속 토큰이 포함되어 있으므로 이 토큰을 후속 스트리밍 API 호출에 전달하여 스트림이 중단된 위치에서 스트림을 다시 시작할 수 있습니다.
AIAgent agent = new AzureOpenAIClient(
new Uri("https://<myresource>.openai.azure.com"),
new DefaultAzureCredential())
.GetOpenAIResponseClient("<deployment-name>")
.AsAIAgent();
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항목에는 다시 시작에 사용할 수 있는 연속 토큰이 포함됩니다. - 중단 전에 마지막으로 받은 업데이트의 연속 토큰 저장
- 저장된 연속 토큰을 사용하여 중단 지점에서 스트림 다시 시작
팁 (조언)
실행 가능한 전체 예제는 .NET 샘플을 참조하세요.
팁 (조언)
전체 작업 예제는 백그라운드 응답 샘플을 참조하세요.
백그라운드 응답 사용
백그라운드 응답을 사용하도록 설정하려면 다음을 호출agent.run()할 background 때 옵션을 전달합니다.
session = agent.create_session()
response = await agent.run(
messages="Your prompt here",
session=session,
options={"background": True},
)
비고
현재 OpenAI 응답 API를 사용하는 에이전트만 백그라운드 응답을 지원합니다. OpenAI 응답 에이전트 및 Azure OpenAI 응답 에이전트.
비 스트리밍 백그라운드 응답
비 스트리밍 시나리오의 경우 에이전트를 처음 실행할 background=Truecontinuation_token때 . 이 None경우 continuation_token 작업이 완료되었습니다. 그렇지 않으면 후속 호출에서 토큰을 다시 전달하여 폴링합니다.
import asyncio
from agent_framework import Agent
from agent_framework.openai import OpenAIResponsesClient
agent = Agent(
name="researcher",
instructions="You are a helpful research assistant.",
client=OpenAIResponsesClient(model_id="o3"),
)
session = await 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 = await 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}을 통해 전달하여 다시 시작
모범 사례
백그라운드 응답을 사용할 때는 다음 모범 사례를 고려합니다.
- 적절한 폴링 간격을 구현하여 서비스 압도 방지
- 작업이 예상보다 오래 걸리는 경우 폴링 간격에 지수 백오프 사용
- 처리가 완료되는 시기를 확인하기 위해 연속 토큰을 항상 확인
null합니다. - 사용자 세션에 걸쳐 있을 수 있는 작업에 대해 연속 토큰을 영구적으로 저장하는 것이 좋습니다.
제한 사항 및 고려 사항
- 백그라운드 응답은 장기 실행 작업을 지원하는 기본 AI 서비스에 따라 달라집니다.
- 모든 에이전트 유형이 백그라운드 응답을 지원할 수 있는 것은 아닙니다.
- 네트워크 중단 또는 클라이언트를 다시 시작하려면 연속 토큰을 유지하기 위해 특별한 처리가 필요할 수 있습니다.