本教學課程示範如何將代理程式交談 (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。
然後,可以將其轉換為用於存儲的字符串並保存到數據庫、Blob 存儲或文件。
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 方法,將其序列化成字典形式。
然後,可以將其轉換為 JSON 進行存儲並保存到數據庫、Blob 存儲或文件。
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)