Partilhar via


Persistência e retoma de conversas com o agente

Este tutorial mostra como persistir uma conversa de agente (AgentThread) para armazenar e recarregá-la mais tarde.

Ao hospedar um agente em um serviço ou até mesmo em um aplicativo cliente, muitas vezes você deseja manter o estado da conversa em várias solicitações ou sessões. Ao persistir o AgentThread, você pode salvar o contexto da conversa e recarregá-lo mais tarde.

Pré-requisitos

Para obter pré-requisitos e instalar pacotes NuGet, consulte a etapa Criar e executar um agente simples neste tutorial.

Persistir e continuar com o diálogo

Crie um agente e obtenha um novo thread que manterá o estado da conversa.

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();

Execute o agente, passando no thread, para que o AgentThread inclua essa troca.

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

Chame o Serialize método no thread para serializá-lo para um JsonElement. Em seguida, ele pode ser convertido em uma cadeia de caracteres para armazenamento e salvo em um banco de dados, armazenamento de blob ou arquivo.

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);

Carregue o JSON persistente do armazenamento e recrie a instância do AgentThread a partir dele. O thread deve ser desserializado usando uma instância do agente. Este deve ser o mesmo tipo de agente que foi usado para criar o thread original. Isso ocorre porque os agentes podem ter seus próprios tipos de thread e podem construir threads com funcionalidade adicional específica para esse tipo de agente.

// 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);

Use o tópico retomado para continuar a conversa.

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

Este tutorial mostra como persistir uma conversa de agente (AgentThread) para armazenar e recarregá-la mais tarde.

Ao hospedar um agente em um serviço ou até mesmo em um aplicativo cliente, muitas vezes você deseja manter o estado da conversa em várias solicitações ou sessões. Ao persistir o AgentThread, você pode salvar o contexto da conversa e recarregá-lo mais tarde.

Pré-requisitos

Para pré-requisitos e instalação de pacotes Python, consulte a etapa Criar e executar um agente simples neste tutorial.

Persistir e continuar com o diálogo

Crie um agente e obtenha um novo thread que manterá o estado da conversa.

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()

Execute o agente, passando no thread, para que o AgentThread inclua essa troca.

# 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)

Chame o serialize método no thread para serializá-lo em um dicionário. Em seguida, ele pode ser convertido em JSON para armazenamento e salvo em um banco de dados, armazenamento de blob ou arquivo.

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)

Carregue o JSON persistente do armazenamento e recrie a instância do AgentThread a partir dele. O thread deve ser desserializado usando uma instância do agente. Este deve ser o mesmo tipo de agente que foi usado para criar o thread original. Isso ocorre porque os agentes podem ter seus próprios tipos de thread e podem construir threads com funcionalidade adicional específica para esse tipo de agente.

# 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)

Use o tópico retomado para continuar a conversa.

# 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)

Próximos passos