本教程演示如何将代理会话(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)