// Copyright (c) Microsoft. All rights reserved. using System; using System.Collections.Generic; using System.IO; using System.Text.Json; using Microsoft.Agents.AI; using Microsoft.Extensions.AI; namespace AgentConversation.IntegrationTests; /// /// Provides helpers for serializing and deserializing conversation contexts (lists of ) /// to and from JSON, enabling the initial context of a test case to be captured once and reused across runs. /// public static class ConversationContextSerializer { private static readonly JsonSerializerOptions s_serializerOptions = AgentAbstractionsJsonUtilities.DefaultOptions; /// /// Serializes a list of instances to a JSON string. /// /// The messages to serialize. /// A JSON string representation of the messages. public static string Serialize(IList messages) => JsonSerializer.Serialize(messages, s_serializerOptions); /// /// Deserializes a JSON string into a list of instances. /// /// The JSON string to deserialize. /// The deserialized list of messages. /// /// Thrown when the JSON cannot be deserialized into a list of instances. /// public static IList Deserialize(string json) { var messages = JsonSerializer.Deserialize>(json, s_serializerOptions); return messages ?? throw new InvalidOperationException("Failed to deserialize chat messages from the provided JSON."); } /// /// Saves a list of instances to a JSON file. /// /// The path of the file to write. /// The messages to save. public static void SaveToFile(string filePath, IList messages) { var json = Serialize(messages); File.WriteAllText(filePath, json); } /// /// Loads a list of instances from a JSON file. /// /// The path of the file to read. /// The deserialized list of messages. /// Thrown when does not exist. public static IList LoadFromFile(string filePath) { if (!File.Exists(filePath)) { throw new FileNotFoundException($"Conversation context file not found: '{filePath}'. " + "Run the context creation step first to generate this file.", filePath); } var json = File.ReadAllText(filePath); return Deserialize(json); } }