// Copyright (c) Microsoft. All rights reserved. using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.Shared.Diagnostics; namespace Microsoft.Extensions.AI.Agents; /// /// A base class for agent threads that always store conversation state in the service, and only keep an ID reference in the . /// public abstract class ServiceIdAgentThread : AgentThread { /// /// Initializes a new instance of the class. /// protected ServiceIdAgentThread() { } /// /// Initializes a new instance of the class with the specified service thread ID. /// /// The ID that the conversation state is stored under in the service. protected ServiceIdAgentThread(string serviceThreadId) { this.ServiceThreadId = Throw.IfNullOrEmpty(serviceThreadId); } /// /// Initializes a new instance of the class from serialized state. /// /// A representing the serialized state of the thread. /// Optional settings for customizing the JSON deserialization process. /// The is not a JSON object. /// The is invalid or cannot be deserialized to the expected type. protected ServiceIdAgentThread( JsonElement serializedThreadState, JsonSerializerOptions? jsonSerializerOptions = null) { if (serializedThreadState.ValueKind != JsonValueKind.Object) { throw new ArgumentException("The serialized thread state must be a JSON object.", nameof(serializedThreadState)); } var state = serializedThreadState.Deserialize( AgentAbstractionsJsonUtilities.DefaultOptions.GetTypeInfo(typeof(ServiceIdAgentThreadState))) as ServiceIdAgentThreadState; if (state?.ServiceThreadId is string serviceThreadId) { this.ServiceThreadId = serviceThreadId; } } /// /// Gets the ID that the conversation state is stored under in the service. /// protected string? ServiceThreadId { get; set; } /// /// Serializes the current object's state to a using the specified serialization options. /// /// The JSON serialization options to use. /// The to monitor for cancellation requests. The default is . /// A representation of the object's state. public override async Task SerializeAsync(JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default) { var state = new ServiceIdAgentThreadState { ServiceThreadId = this.ServiceThreadId, }; return JsonSerializer.SerializeToElement(state, AgentAbstractionsJsonUtilities.DefaultOptions.GetTypeInfo(typeof(ServiceIdAgentThreadState))); } internal sealed class ServiceIdAgentThreadState { public string? ServiceThreadId { get; set; } } }