다음을 통해 공유


에이전트 대화 유지 및 다시 시작

이 자습서에서는 에이전트 대화(AgentThread)를 저장하고 나중에 다시 로드하는 방법을 보여 줍니다.

서비스 또는 클라이언트 애플리케이션에서 에이전트를 호스팅하는 경우 여러 요청 또는 세션에서 대화 상태를 유지하려는 경우가 많습니다. 대화 컨텍스트를 AgentThread유지하면 대화 컨텍스트를 저장하고 나중에 다시 로드할 수 있습니다.

필수 조건

필수 구성 요소 및 NuGet 패키지 설치는 이 자습서의 간단한 에이전트 만들기 및 실행 단계를 참조하세요.

대화 유지 및 다시 열기

에이전트를 만들고 대화 상태를 보유할 새 스레드를 가져옵니다.

using System;
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using OpenAI;

AIAgent agent = new AzureOpenAIClient(
    new Uri("https://<myresource>.openai.azure.com"),
    new AzureCliCredential())
     .GetChatClient("gpt-4o-mini")
     .CreateAIAgent(instructions: "You are a helpful assistant.", name: "Assistant");

AgentThread thread = agent.GetNewThread();

이 교환을 포함할 수 있도록 스레드를 전달하여 에이전트를 AgentThread 실행합니다.

// Run the agent and append the exchange to the thread
Console.WriteLine(await agent.RunAsync("Tell me a short pirate joke.", thread));

스레드에서 Serialize 메서드를 호출하여 JsonElement로 serialize합니다. 그런 다음 스토리지용 문자열로 변환하여 데이터베이스, Blob Storage 또는 파일에 저장할 수 있습니다.

using System.IO;
using System.Text.Json;

// Serialize the thread state
string serializedJson = thread.Serialize(JsonSerializerOptions.Web).GetRawText();

// Example: save to a local file (replace with DB or blob storage in production)
string filePath = Path.Combine(Path.GetTempPath(), "agent_thread.json");
await File.WriteAllTextAsync(filePath, serializedJson);

스토리지에서 지속형 JSON을 로드하고 해당 스토리지에서 AgentThread 인스턴스를 다시 만듭니다. 에이전트 인스턴스를 사용하여 스레드를 역직렬화해야 합니다. 원래 스레드를 만드는 데 사용된 것과 동일한 에이전트 형식이어야 합니다. 에이전트는 자체 스레드 형식을 가질 수 있으며 해당 에이전트 유형과 관련된 추가 기능을 사용하여 스레드를 생성할 수 있기 때문입니다.

// Read persisted JSON
string loadedJson = await File.ReadAllTextAsync(filePath);
JsonElement reloaded = JsonSerializer.Deserialize<JsonElement>(loadedJson, JsonSerializerOptions.Web);

// Deserialize the thread into an AgentThread tied to the same agent type
AgentThread resumedThread = agent.DeserializeThread(reloaded, JsonSerializerOptions.Web);

다시 시작된 스레드를 사용하여 대화를 계속합니다.

// Continue the conversation with resumed thread
Console.WriteLine(await agent.RunAsync("Now tell that joke in the voice of a pirate.", resumedThread));

이 자습서에서는 에이전트 대화(AgentThread)를 저장하고 나중에 다시 로드하는 방법을 보여 줍니다.

서비스 또는 클라이언트 애플리케이션에서 에이전트를 호스팅하는 경우 여러 요청 또는 세션에서 대화 상태를 유지하려는 경우가 많습니다. 대화 컨텍스트를 AgentThread유지하면 대화 컨텍스트를 저장하고 나중에 다시 로드할 수 있습니다.

필수 조건

필수 구성 요소 및 Python 패키지 설치는 이 자습서의 간단한 에이전트 만들기 및 실행 단계를 참조하세요.

대화 유지 및 다시 열기

에이전트를 만들고 대화 상태를 보유할 새 스레드를 가져옵니다.

from azure.identity import AzureCliCredential
from agent_framework import ChatAgent
from agent_framework.azure import AzureOpenAIChatClient

agent = ChatAgent(
    chat_client=AzureOpenAIChatClient(
        endpoint="https://<myresource>.openai.azure.com",
        credential=AzureCliCredential(),
        ai_model_id="gpt-4o-mini"
    ),
    name="Assistant",
    instructions="You are a helpful assistant."
)

thread = agent.get_new_thread()

이 교환을 포함할 수 있도록 스레드를 전달하여 에이전트를 AgentThread 실행합니다.

# Run the agent and append the exchange to the thread
response = await agent.run("Tell me a short pirate joke.", thread=thread)
print(response.text)

스레드에서 serialize 메서드를 호출하여 사전으로 serialize합니다. 그런 다음 스토리지를 위해 JSON으로 변환하고 데이터베이스, Blob Storage 또는 파일에 저장할 수 있습니다.

import json
import tempfile
import os

# Serialize the thread state
serialized_thread = await thread.serialize()
serialized_json = json.dumps(serialized_thread)

# Example: save to a local file (replace with DB or blob storage in production)
temp_dir = tempfile.gettempdir()
file_path = os.path.join(temp_dir, "agent_thread.json")
with open(file_path, "w") as f:
    f.write(serialized_json)

스토리지에서 지속형 JSON을 로드하고 해당 스토리지에서 AgentThread 인스턴스를 다시 만듭니다. 에이전트 인스턴스를 사용하여 스레드를 역직렬화해야 합니다. 원래 스레드를 만드는 데 사용된 것과 동일한 에이전트 형식이어야 합니다. 에이전트는 자체 스레드 형식을 가질 수 있으며 해당 에이전트 유형과 관련된 추가 기능을 사용하여 스레드를 생성할 수 있기 때문입니다.

# Read persisted JSON
with open(file_path, "r") as f:
    loaded_json = f.read()

reloaded_data = json.loads(loaded_json)

# Deserialize the thread into an AgentThread tied to the same agent type
resumed_thread = await agent.deserialize_thread(reloaded_data)

다시 시작된 스레드를 사용하여 대화를 계속합니다.

# Continue the conversation with resumed thread
response = await agent.run("Now tell that joke in the voice of a pirate.", thread=resumed_thread)
print(response.text)

다음 단계