tghamm / Anthropic.SDK

An unofficial C#/.NET SDK for accessing the Anthropic Claude API
https://www.nuget.org/packages/Anthropic.SDK
MIT License
65 stars 11 forks source link

Serialize and Deserialize list of Messages #49

Open MiiChielHD opened 3 weeks ago

MiiChielHD commented 3 weeks ago

Hi there, I'm using the SDK with NewtonSoft. I would like to make 'snapshots' of all my agents and their messages.

I can serialize a list of Messages to JSON, yet I can't convert it back because Type is an Interface or abstract class:

Could not create an instance of type Anthropic.SDK.Messaging.ContentBase. Type is an interface or abstract class and cannot be instantiated

Is there something i'm missing, or do i need to work around this?

MiiChielHD commented 3 weeks ago

Okay so I found the answer mostly. Because ContentBase is an interface, you need to build a custom deserializer.:

public class ContentBaseDeserializer : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(ContentBase));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // Load the JSON object from the reader
        if (typeof(ContentBase).IsAssignableFrom(objectType))
        {
            JObject jObject = JObject.Load(reader);

            // Create an instance of the concrete class
            ContentBase target = new Anthropic.SDK.Messaging.TextContent();

            // Populate the concrete object with the JSON data
            serializer.Populate(jObject.CreateReader(), target);

            return target;
        }
        else
        {
            // Let the default serializer handle other types
            return serializer.Deserialize(reader, objectType);
        }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        // Use the default serialization for writing the JSON
        serializer.Serialize(writer, value);
    }
}

Then in your main code:

 JsonSerializerSettings settings = new JsonSerializerSettings();
 settings.Converters.Add(new ContentBaseDeserializer());

 var tempResult= JsonConvert.DeserializeObject<SomeClassWithMessageObjects>(tempJSON, settings);

I'm not certain how to discretize the TextContent and ImageContent class yet... but for now its okay.