다음을 통해 공유


Microsoft Agent Framework 다중 턴 대화 및 쓰레드 처리

Microsoft 에이전트 프레임워크는 AI 에이전트와의 멀티 턴 대화를 관리하기 위한 기본 제공 지원을 제공합니다. 여기에는 여러 상호 작용 간에 컨텍스트를 유지하는 것이 포함됩니다. 에이전트를 빌드하는 데 사용되는 다양한 에이전트 유형 및 기본 서비스는 서로 다른 스레딩 유형을 지원할 수 있으며, 에이전트 프레임워크는 이러한 차이를 추상화하여 개발자에게 일관된 인터페이스를 제공합니다.

예를 들어 주조 에이전트를 기반으로 ChatClientAgent를 사용하는 경우 대화 기록은 서비스에 유지됩니다. 반면 gpt-4.1에서 채팅 완료를 기반으로 ChatClientAgent를 사용하는 경우 대화 기록은 메모리 내이며 에이전트가 관리합니다.

형식은 AgentThread 에이전트가 있는 대화 스레드를 나타내는 추상화입니다. AIAgent 인스턴스는 상태 비 상태이며 동일한 에이전트 인스턴스를 여러 AgentThread 인스턴스와 함께 사용할 수 있습니다. 따라서 모든 상태는 .에 AgentThread유지됩니다. AgentThread는 채팅 기록뿐 아니라 에이전트가 여러 상호 작용에서 유지해야 하는 다른 상태도 나타낼 수 있습니다. 채팅 기록은 원격 채팅 기록에 대한 참조만 포함하는 스레드 자체 또는 원격 AgentThread 으로 저장될 수 있습니다. AgentThread 상태는 또한 원격으로 저장 된 메모리에 대 한 참조 또는 메모리를 포함할 수 있습니다.

팁 (조언)

에이전트 프레임워크의 채팅 기록 및 메모리에 대한 자세한 내용은 에이전트 채팅 기록 및 메모리를 참조하세요.

AgentThread 만들기

AgentThread 인스턴스는 다음 두 가지 방법으로 만들 수 있습니다.

  1. 에이전트의 GetNewThread를 호출합니다.
  2. 에이전트를 실행하고 AgentThread을(를) 제공하지 않음으로써. 에이전트는 이 경우에, 실행 기간 동안만 사용될 기본 스레드를 가진 임시적 AgentThread을 생성합니다.

일부 기본 스레드는 서비스에 필요한 기본 서비스(예: Foundry 에이전트 또는 OpenAI 응답)에서 영구적으로 만들어질 수 있습니다. 이러한 스레드의 정리 또는 삭제는 사용자의 책임입니다.

// Create a new thread.
AgentThread thread = agent.GetNewThread();
// Run the agent with the thread.
var response = await agent.RunAsync("Hello, how are you?", thread);

// Run an agent with a temporary thread.
response = await agent.RunAsync("Hello, how are you?");

AgentThread 저장소

AgentThread 인스턴스는 나중에 사용하기 위해 직렬화 및 저장될 수 있습니다. 이렇게 하면 여러 세션 또는 서비스 호출에서 대화 컨텍스트를 보존할 수 있습니다.

대화 기록이 서비스에 저장되는 경우, serial된 AgentThread는 서비스의 스레드 ID를 포함하게 됩니다. 대화 기록이 메모리 내로 관리되는 경우 serialize AgentThread 된 메시지에는 메시지 자체가 포함됩니다.

// Create a new thread.
AgentThread thread = agent.GetNewThread();
// Run the agent with the thread.
var response = await agent.RunAsync("Hello, how are you?", thread);

// Serialize the thread for storage.
JsonElement serializedThread = await thread.SerializeAsync();
// Deserialize the thread state after loading from storage.
AgentThread resumedThread = await agent.DeserializeThreadAsync(serializedThread);

// Run the agent with the resumed thread.
var response = await agent.RunAsync("Hello, how are you?", resumedThread);

Microsoft 에이전트 프레임워크는 AI 에이전트와의 멀티 턴 대화를 관리하기 위한 기본 제공 지원을 제공합니다. 여기에는 여러 상호 작용 간에 컨텍스트를 유지하는 것이 포함됩니다. 에이전트를 빌드하는 데 사용되는 다양한 에이전트 유형 및 기본 서비스는 서로 다른 스레딩 유형을 지원할 수 있으며, 에이전트 프레임워크는 이러한 차이를 추상화하여 개발자에게 일관된 인터페이스를 제공합니다.

예를 들어 Foundry 에이전트를 기반으로 사용하는 ChatAgent 경우 대화 기록은 서비스에 유지됩니다. gpt-4에서 채팅 완료를 기반으로 사용하는 ChatAgent 경우 대화 기록은 메모리 내이며 에이전트가 관리합니다.

기본 스레딩 모델 간의 차이는 AgentThread 타입을 통해 추상화됩니다.

Agent/AgentThread 관계

AIAgent 인스턴스는 상태 비 상태이며 동일한 에이전트 인스턴스를 여러 AgentThread 인스턴스와 함께 사용할 수 있습니다.

하지만 모든 에이전트가 모든 스레드 형식을 지원하는 것은 아닙니다. 예를 들어 ChatClientAgent을 응답 서비스와 사용하는 경우, 이 에이전트에서 생성한 AgentThread 인스턴스는 Foundry Agent 서비스를 사용하는 ChatClientAgent과 함께 작동하지 않습니다. 이것은 이러한 서비스가 모두 서비스 내 대화 기록 저장을 지원하고, AgentThread가 이 서비스의 관리 스레드에 대한 참조만 가지고 있기 때문입니다.

따라서 기본 스레딩 모델 및 해당 의미를 인식하지 않는 한 다른 에이전트 인스턴스를 사용하여 한 에이전트에서 만든 인스턴스를 사용하는 AgentThread 것은 안전하지 않은 것으로 간주됩니다.

서비스/프로토콜별 스레딩 지원

서비스 스레딩 지원
주조 에이전트 서비스 관리 영구 스레드
OpenAI 응답 서비스가 관리하는 영구 스레드 또는 메모리 상 스레드
오픈AI 대화완성 메모리 내 스레드
OpenAI 도우미 서비스 관리 스레드
A2A 서비스 관리 스레드

AgentThread 만들기

AgentThread 인스턴스는 다음 두 가지 방법으로 만들 수 있습니다.

  1. 에이전트의 get_new_thread()를 호출합니다.
  2. 에이전트를 실행하고 AgentThread을(를) 제공하지 않음으로써. 에이전트는 이 경우에, 실행 기간 동안만 사용될 기본 스레드를 가진 임시적 AgentThread을 생성합니다.

일부 기본 스레드는 서비스에 필요한 기본 서비스(예: Azure AI 에이전트 또는 OpenAI 응답)에서 영구적으로 만들어질 수 있습니다. 이러한 스레드의 정리 또는 삭제는 사용자의 책임입니다.

# Create a new thread.
thread = agent.get_new_thread()
# Run the agent with the thread.
response = await agent.run("Hello, how are you?", thread=thread)

# Run an agent with a temporary thread.
response = await agent.run("Hello, how are you?")

AgentThread 저장소

AgentThread 인스턴스는 나중에 사용하기 위해 직렬화 및 저장될 수 있습니다. 이렇게 하면 여러 세션 또는 서비스 호출에서 대화 컨텍스트를 보존할 수 있습니다.

대화 기록이 서비스에 저장되는 경우, serial된 AgentThread는 서비스의 스레드 ID를 포함하게 됩니다. 대화 기록이 메모리 내로 관리되는 경우 serialize AgentThread 된 메시지에는 메시지 자체가 포함됩니다.

# Create a new thread.
thread = agent.get_new_thread()
# Run the agent with the thread.
response = await agent.run("Hello, how are you?", thread=thread)

# Serialize the thread for storage.
serialized_thread = await thread.serialize()
# Deserialize the thread state after loading from storage.
resumed_thread = await agent.deserialize_thread(serialized_thread)

# Run the agent with the resumed thread.
response = await agent.run("Hello, how are you?", thread=resumed_thread)

사용자 지정 메시지 저장소

메모리 내 스레드의 경우 사용자 지정 메시지 저장소 구현을 제공하여 메시지를 저장하고 검색하는 방법을 제어할 수 있습니다.

from agent_framework import AgentThread, ChatMessageStore, ChatAgent
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential

class CustomStore(ChatMessageStore):
    # Implement custom storage logic here
    pass

# You can also provide a custom message store factory when creating the agent
def custom_message_store_factory():
    return CustomStore()  # or your custom implementation

async with AzureCliCredential() as credential:
    agent = ChatAgent(
        chat_client=AzureAIAgentClient(async_credential=credential),
        instructions="You are a helpful assistant",
        chat_message_store_factory=custom_message_store_factory
    )
    # Or let the agent create one automatically
    thread = agent.get_new_thread()
    # thread.message_store is not a instance of CustomStore

Agent/AgentThread 관계

Agents 는 상태 비 상태이며 동일한 에이전트 인스턴스를 여러 AgentThread 인스턴스와 함께 사용할 수 있습니다.

하지만 모든 에이전트가 모든 스레드 형식을 지원하는 것은 아닙니다. 예를 들어, OpenAI 응답 서비스를 사용하는 ChatAgent의 경우, 이 에이전트에서 사용하는 store=True, AgentThread 인스턴스는 thread_ids가 호환되지 않기 때문에 Azure AI 에이전트 서비스를 사용하는 ChatAgent에서는 작동하지 않습니다.

따라서 기본 스레딩 모델 및 해당 의미를 인식하지 않는 한 다른 에이전트 인스턴스를 사용하여 한 에이전트에서 만든 인스턴스를 사용하는 AgentThread 것은 안전하지 않은 것으로 간주됩니다.

실용적인 멀티 턴 예제

다음은 여러 상호 작용에서 컨텍스트를 유지하는 방법을 보여 주는 전체 예제입니다.

from agent_framework import ChatAgent
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential

async def multi_turn_example():
    async with (
        AzureCliCredential() as credential,
        ChatAgent(
            chat_client=AzureAIAgentClient(async_credential=credential),
            instructions="You are a helpful assistant"
        ) as agent
    ):
        # Create a thread for persistent conversation
        thread = agent.get_new_thread()

        # First interaction
        response1 = await agent.run("My name is Alice", thread=thread)
        print(f"Agent: {response1.text}")

        # Second interaction - agent remembers the name
        response2 = await agent.run("What's my name?", thread=thread)
        print(f"Agent: {response2.text}")  # Should mention "Alice"

        # Serialize thread for storage
        serialized = await thread.serialize()

        # Later, deserialize and continue conversation
        new_thread = await agent.deserialize_thread(serialized)
        response3 = await agent.run("What did we talk about?", thread=new_thread)
        print(f"Agent: {response3.text}")  # Should remember previous context

다음 단계