Remarque
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de vous connecter ou de modifier des répertoires.
L’accès à cette page nécessite une autorisation. Vous pouvez essayer de modifier des répertoires.
Ce tutoriel montre comment conserver une conversation d’agent (AgentThread) dans le stockage et la recharger ultérieurement.
Lors de l’hébergement d’un agent dans un service ou même dans une application cliente, vous souhaitez souvent maintenir l’état de conversation entre plusieurs requêtes ou sessions. En sauvegardant AgentThread, vous pouvez enregistrer le contexte de la conversation et le recharger ultérieurement.
Prerequisites
Pour connaître les prérequis et l’installation des packages NuGet, consultez l’étape Créer et exécuter un agent simple dans ce tutoriel.
Continuer et reprendre la conversation
Créez un agent et obtenez un nouveau thread qui contiendra l’état de la conversation.
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();
Exécutez l’agent en transmettant le thread, afin que AgentThread inclue cet échange.
// Run the agent and append the exchange to the thread
Console.WriteLine(await agent.RunAsync("Tell me a short pirate joke.", thread));
Appelez la Serialize méthode sur le thread pour le sérialiser vers un JsonElement.
Il peut ensuite être converti en chaîne pour le stockage et enregistré dans une base de données, un stockage d’objets blob ou un fichier.
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);
Chargez le JSON persistant à partir du stockage et recréez l’instance AgentThread à partir de celle-ci. Le thread doit être désérialisé à l’aide d’une instance d’agent. Il doit s’agir du même type d’agent que celui utilisé pour créer le thread d’origine. Cela est dû au fait que les agents peuvent avoir leurs propres types de threads et peuvent construire des threads avec des fonctionnalités supplémentaires spécifiques à ce type d’agent.
// 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);
Utilisez le thread repris pour poursuivre la conversation.
// Continue the conversation with resumed thread
Console.WriteLine(await agent.RunAsync("Now tell that joke in the voice of a pirate.", resumedThread));
Ce tutoriel montre comment conserver une conversation d’agent (AgentThread) dans le stockage et la recharger ultérieurement.
Lors de l’hébergement d’un agent dans un service ou même dans une application cliente, vous souhaitez souvent maintenir l’état de conversation entre plusieurs requêtes ou sessions. En sauvegardant AgentThread, vous pouvez enregistrer le contexte de la conversation et le recharger ultérieurement.
Prerequisites
Pour connaître les prérequis et l’installation des packages Python, consultez l’étape Créer et exécuter un agent simple dans ce tutoriel.
Continuer et reprendre la conversation
Créez un agent et obtenez un nouveau thread qui contiendra l’état de la conversation.
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()
Exécutez l’agent en transmettant le thread, afin que AgentThread inclue cet échange.
# 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)
Appelez la serialize méthode sur le thread pour le sérialiser dans un dictionnaire.
Il peut ensuite être converti en JSON pour le stockage et enregistré dans une base de données, un stockage d’objets blob ou un fichier.
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)
Chargez le JSON persistant à partir du stockage et recréez l’instance AgentThread à partir de celle-ci. Le thread doit être désérialisé à l’aide d’une instance d’agent. Il doit s’agir du même type d’agent que celui utilisé pour créer le thread d’origine. Cela est dû au fait que les agents peuvent avoir leurs propres types de threads et peuvent construire des threads avec des fonctionnalités supplémentaires spécifiques à ce type d’agent.
# 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)
Utilisez le thread repris pour poursuivre la conversation.
# 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)