Skip to content

A programming framework for agentic AI

feat: Save/Load for AgentChat.NET (#5841)

Jacob Alberb4c1e5841f1a
diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/ChatAgent.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/ChatAgent.cs
index b4cf2f738..6fc189684 100644
--- a/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/ChatAgent.cs
+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/ChatAgent.cs
@@ -2,6 +2,7 @@
// ChatAgent.cs
using System.Text.RegularExpressions;
+using Microsoft.AutoGen.Contracts;
namespace Microsoft.AutoGen.AgentChat.Abstractions;
@@ -165,7 +166,8 @@ public class ChatStreamFrame : StreamingFrame<Response, AgentMessage>;
/// </summary>
public interface IChatAgent :
IHandleChat<IEnumerable<ChatMessage>, Response>,
- IHandleStream<IEnumerable<ChatMessage>, ChatStreamFrame>
+ IHandleStream<IEnumerable<ChatMessage>, ChatStreamFrame>,
+ ISaveState
{
/// <summary>
/// The name of the agent. This is used by team to uniquely identify the agent.It should be unique within the team.
diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/ITeam.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/ITeam.cs
index e6c16cba4..17ab60c09 100644
--- a/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/ITeam.cs
+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/ITeam.cs
@@ -1,12 +1,14 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// ITeam.cs
+using Microsoft.AutoGen.Contracts;
+
namespace Microsoft.AutoGen.AgentChat.Abstractions;
/// <summary>
/// A team of agents.
/// </summary>
-public interface ITeam : ITaskRunner
+public interface ITeam : ITaskRunner, ISaveState
{
/// <summary>
/// Reset the team and all its participants to its initial state.
diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Messages.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Messages.cs
index 83a3781e6..fcc1871bb 100644
--- a/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Messages.cs
+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Messages.cs
@@ -4,7 +4,10 @@
using System.Collections;
using System.Diagnostics;
using System.Text;
-
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using System.Text.Json.Serialization.Metadata;
+using Microsoft.AutoGen.AgentChat.GroupChat;
using Microsoft.Extensions.AI;
namespace Microsoft.AutoGen.AgentChat.Abstractions;
@@ -614,3 +617,129 @@ public static class CompletionChatMessageExtensions
};
}
}
+
+public static class MessageSerializationHelpers
+{
+ internal sealed class TypeNode(Type type)
+ {
+ public Type Type { get; } = type;
+ public TypeNode? Parent { get; set; }
+ public TypeNode Root => this.Parent?.Root ?? this;
+ public List<TypeNode> Children { get; } = new List<TypeNode>();
+
+ public IEnumerable<Type> ChildrenTransitiveClosure
+ {
+ get
+ {
+ return this.Children.Select(c => c.Type)
+ .Concat(Children.SelectMany(c => c.ChildrenTransitiveClosure));
+ }
+ }
+ }
+
+ internal sealed class TypeTree
+ {
+ private static IEnumerable<Type> GetDerivedTypes(Type type)
+ {
+ // Across all assemblies
+ foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
+ {
+ // Get all types in the assembly
+ foreach (var derivedType in assembly.GetTypes().Where(t => type.IsAssignableFrom(t) && t != type))
+ {
+ yield return derivedType;
+ }
+ }
+ }
+
+ private TypeNode EnsureTypeNode(Type type)
+ {
+ if (!this.TypeNodes.TryGetValue(type, out TypeNode? currentNode))
+ {
+ currentNode = this.TypeNodes[type] = new TypeNode(type);
+ }
+
+ return currentNode;
+ }
+
+ private void EnsureType(Type type)
+ {
+ TypeNode? currentNode = this.EnsureTypeNode(type);
+
+ while (currentNode != null &&
+ currentNode.Parent == null &&
+ !this.RootTypes.Contains(currentNode.Type))
+ {
+ Type parentType = currentNode.Type.BaseType
+ ?? throw new InvalidOperationException("We should never have a non-Root, underived base");
+
+ TypeNode parentNode = this.EnsureTypeNode(parentType);
+ currentNode.Parent = parentNode;
+ parentNode.Children.Add(currentNode);
+
+ currentNode = parentNode;
+ }
+ }
+
+ public HashSet<Type> RootTypes { get; }
+ public Dictionary<Type, TypeNode> TypeNodes { get; } = new Dictionary<Type, TypeNode>();
+
+ public TypeTree(params Type[] rootTypes)
+ {
+ this.RootTypes = new HashSet<Type>();
+ foreach (var rootType in rootTypes)
+ {
+ // Check that there are no other types that this type derives from in the root types
+ // or vice versa
+ if (this.RootTypes.Any(t => t.IsAssignableFrom(rootType) || rootType.IsAssignableFrom(t)))
+ {
+ throw new ArgumentException($"Root types cannot be derived from each other: {rootType.Name}");
+ }
+
+ this.RootTypes.Add(rootType);
+
+ this.EnsureType(rootType);
+
+ foreach (var derivedType in GetDerivedTypes(rootType))
+ {
+ this.EnsureType(derivedType);
+ }
+ }
+ }
+ }
+
+ internal static readonly TypeTree MessageTypeTree = new(typeof(AgentMessage), typeof(GroupChatEventBase));
+
+ internal sealed class MessagesTypeInfoResolver : DefaultJsonTypeInfoResolver
+ {
+ public override JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options)
+ {
+ JsonTypeInfo baseTypeInfo = base.GetTypeInfo(type, options);
+
+ if (MessageTypeTree.TypeNodes.TryGetValue(type, out TypeNode? typeNode) &&
+ typeNode.Children.Any()) // Only add polymorphism info if there are derived children
+ {
+ if (baseTypeInfo.PolymorphismOptions == null)
+ {
+ baseTypeInfo.PolymorphismOptions = new JsonPolymorphismOptions();
+ }
+
+ baseTypeInfo.PolymorphismOptions.IgnoreUnrecognizedTypeDiscriminators = true;
+ baseTypeInfo.PolymorphismOptions.UnknownDerivedTypeHandling = JsonUnknownDerivedTypeHandling.FailSerialization;
+
+ foreach (Type childType in typeNode.ChildrenTransitiveClosure)
+ {
+ if (childType.IsAbstract || childType.IsInterface || childType.IsGenericTypeDefinition)
+ {
+ // Can only deserialize concrete, complete types.
+ continue;
+ }
+
+ baseTypeInfo.PolymorphismOptions.DerivedTypes.Add(new JsonDerivedType(childType, childType.FullName ?? childType.Name));
+ }
+ }
+
+ return baseTypeInfo;
+ }
+ }
+}
diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/ModelContext.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/ModelContext.cs
new file mode 100644
index 000000000..188487004
--- /dev/null
+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/ModelContext.cs
@@ -0,0 +1,73 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// ModelContext.cs
+
+using System.Text.Json;
+using Microsoft.AutoGen.AgentChat.State;
+using Microsoft.AutoGen.Contracts;
+
+using LLMMessage = Microsoft.Extensions.AI.ChatMessage;
+
+namespace Microsoft.AutoGen.AgentChat.Abstractions;
+
+public interface IModelContext : ISaveState
+{
+ public void Add(LLMMessage message);
+ public void Clear();
+
+ public IEnumerable<LLMMessage> Messages { get; }
+}
+
+public sealed class ModelContextState : BaseState
+{
+ public List<LLMMessage> Messages { get; set; } = new();
+}
+
+public abstract class ModelContextBase : IModelContext
+{
+ protected readonly List<LLMMessage> messages;
+
+ public abstract IEnumerable<LLMMessage> Messages { get; }
+
+ public ModelContextBase(params IEnumerable<LLMMessage> messages)
+ {
+ this.messages = [.. messages];
+ }
+
+ public void Add(LLMMessage message)
+ {
+ this.messages.Add(message);
+ }
+
+ public void Clear()
+ {
+ this.messages.Clear();
+ }
+
+ public ValueTask<JsonElement> SaveStateAsync()
+ {
+ SerializedState state = SerializedState.Create(new ModelContextState { Messages = this.messages });
+ return ValueTask.FromResult(state.AsJson());
+ }
+
+ public ValueTask LoadStateAsync(JsonElement state)
+ {
+ SerializedState serializedState = new(state);
+ ModelContextState modelContextState = serializedState.As<ModelContextState>();
+
+ this.messages.Clear();
+ this.messages.AddRange(modelContextState.Messages);
+
+ return ValueTask.CompletedTask;
+ }
+}
+
+public sealed class UnboundedModelContext : ModelContextBase
+{
+ public UnboundedModelContext(params IEnumerable<LLMMessage> messages) : base(messages)
+ {
+ }
+
+ public override IEnumerable<LLMMessage> Messages => this.messages;
+}
+
+// TODO: Promote ModelContext to AutoGen.Core
diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/ChatAgentRouter.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/ChatAgentRouter.cs
index 443cf8315..a466847de 100644
--- a/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/ChatAgentRouter.cs
+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/ChatAgentRouter.cs
@@ -1,7 +1,9 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// ChatAgentRouter.cs
+using System.Text.Json;
using Microsoft.AutoGen.AgentChat.Abstractions;
+using Microsoft.AutoGen.AgentChat.State;
using Microsoft.AutoGen.Contracts;
using Microsoft.AutoGen.Core;
using Microsoft.Extensions.Logging;
@@ -24,7 +26,8 @@ internal sealed class ChatAgentRouter : HostableAgentAdapter,
IHandle<GroupChatStart>,
IHandle<GroupChatAgentResponse>,
IHandle<GroupChatRequestPublish>,
- IHandle<GroupChatReset>
+ IHandle<GroupChatReset>,
+ ISaveState
{
private readonly TopicId parentTopic;
private readonly TopicId outputTopic;
@@ -93,5 +96,24 @@ internal sealed class ChatAgentRouter : HostableAgentAdapter,
this.MessageBuffer.Clear();
return this.agent.ResetAsync(messageContext.CancellationToken);
}
+
+ async ValueTask<JsonElement> ISaveState.SaveStateAsync()
+ {
+ ChatAgentContainerState state = new ChatAgentContainerState
+ {
+ AgentState = new SerializedState(await this.agent.SaveStateAsync()),
+ MessageBuffer = this.MessageBuffer
+ };
+
+ return SerializedState.Create(state).AsJson();
+ }
+
+ ValueTask ISaveState.LoadStateAsync(JsonElement state)
+ {
+ ChatAgentContainerState parsedState = new SerializedState(state).As<ChatAgentContainerState>();
+ this.MessageBuffer = parsedState.MessageBuffer;
+
+ return this.agent.LoadStateAsync(parsedState.AgentState.AsJson());
+ }
}
diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatBase.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatBase.cs
index c21a89e66..a5e2a922b 100644
--- a/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatBase.cs
+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatBase.cs
@@ -4,7 +4,9 @@
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
+using System.Text.Json;
using Microsoft.AutoGen.AgentChat.Abstractions;
+using Microsoft.AutoGen.AgentChat.State;
using Microsoft.AutoGen.Contracts;
using Microsoft.AutoGen.Core;
@@ -159,6 +161,8 @@ public abstract class GroupChatBase<TManager> : ITeam where TManager : GroupChat
await this.Runtime.RegisterOutputCollectorAsync(this.OutputSink, this.GroupChat.GroupChatOptions.OutputTopicType);
}
+ public bool HasRunOnce => this.InitOnceTask != null;
+
public async ValueTask InitializeAsync()
{
if (this.InitOnceTask == null)
@@ -293,4 +297,54 @@ public abstract class GroupChatBase<TManager> : ITeam where TManager : GroupChat
cancel,
message: TaskAlreadyRunning);
}
+
+ public ValueTask<JsonElement> SaveStateAsync()
+ {
+ if (!this.runtimeLayer.HasRunOnce)
+ {
+ throw new InvalidOperationException("The group chat has not been initialized. It must be run before it can be saved.");
+ }
+
+ const string TaskAlreadyRunning = "The team cannot be saved while it is running.";
+ return this.RunManager.RunAsync(
+ SaveStateInternalAsync,
+ CancellationToken.None, // TODO: Change this API?
+ message: TaskAlreadyRunning);
+
+ async ValueTask<JsonElement> SaveStateInternalAsync(CancellationToken _)
+ {
+ TeamState teamState = new()
+ {
+ TeamId = this.TeamId,
+ RuntimeState = await this.Runtime!.SaveStateAsync(),
+ };
+
+ JsonElement result = SerializedState.Create(teamState).AsJson();
+
+ await this.Runtime!.StopAsync();
+
+ return result;
+ }
+ }
+
+ public ValueTask LoadStateAsync(JsonElement state)
+ {
+ const string TaskAlreadyRunning = "The team cannot be loaded while it is running.";
+
+ return this.RunManager.RunAsync(
+ LoadStateInternalAsync,
+ CancellationToken.None, // TODO: Change this API?
+ message: TaskAlreadyRunning);
+
+ async ValueTask LoadStateInternalAsync(CancellationToken _)
+ {
+ TeamState parsedState = new SerializedState(state).As<TeamState>();
+
+ this.TeamId = parsedState.TeamId;
+
+ await this.Runtime!.LoadStateAsync(parsedState.RuntimeState.AsJson());
+
+ await this.Runtime!.StopAsync();
+ }
+ }
}
diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatHandlerRouter.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatHandlerRouter.cs
index fabcc574d..a7c3d62e8 100644
--- a/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatHandlerRouter.cs
+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatHandlerRouter.cs
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// GroupChatHandlerRouter.cs
+using System.Text.Json;
using Microsoft.AutoGen.Contracts;
using Microsoft.AutoGen.Core;
using Microsoft.Extensions.Logging;
@@ -9,7 +10,7 @@ namespace Microsoft.AutoGen.AgentChat.GroupChat;
internal delegate ValueTask MessagePublishServicer(GroupChatEventBase event_, string topicType, CancellationToken cancellation = default);
-internal interface IGroupChatHandler : IHandle<GroupChatStart>, IHandle<GroupChatAgentResponse>, IHandle<object>
+internal interface IGroupChatHandler : IHandle<GroupChatStart>, IHandle<GroupChatAgentResponse>, IHandle<object>, ISaveState
{
public void AttachMessagePublishServicer(MessagePublishServicer? servicer = null);
public void DetachMessagePublishServicer() => this.AttachMessagePublishServicer(null);
@@ -18,7 +19,8 @@ internal interface IGroupChatHandler : IHandle<GroupChatStart>, IHandle<GroupCha
internal sealed class GroupChatHandlerRouter<TManager> : HostableAgentAdapter,
IHandle<GroupChatStart>,
IHandle<GroupChatAgentResponse>,
- IHandle<object>
+ IHandle<object>,
+ ISaveState
where TManager : GroupChatManagerBase, IGroupChatHandler
{
@@ -45,4 +47,10 @@ internal sealed class GroupChatHandlerRouter<TManager> : HostableAgentAdapter,
public ValueTask HandleAsync(object item, MessageContext messageContext)
=> this.ChatManager.HandleAsync(item, messageContext);
+
+ ValueTask<JsonElement> ISaveState.SaveStateAsync()
+ => this.ChatManager.SaveStateAsync();
+
+ ValueTask ISaveState.LoadStateAsync(JsonElement state)
+ => this.ChatManager.LoadStateAsync(state);
}
diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatManagerBase.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatManagerBase.cs
index 69c57e344..19a96ee02 100644
--- a/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatManagerBase.cs
+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatManagerBase.cs
@@ -33,7 +33,7 @@ public abstract class GroupChatManagerBase : IGroupChatHandler
protected ITerminationCondition? TerminationCondition => this.options.TerminationCondition;
protected int? MaxTurns => this.options.MaxTurns;
- private int CurrentTurn { get; set; }
+ protected int CurrentTurn { get; set; }
protected List<AgentMessage> MessageThread;
@@ -182,6 +182,6 @@ public abstract class GroupChatManagerBase : IGroupChatHandler
public ValueTask HandleAsync(object item, MessageContext messageContext)
{
- throw new InvalidOperationException($"Unhandled message in group chat manager: {item.GetType()}");
+ throw new NotImplementedException();
}
}
diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/RoundRobinGroupChat.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/RoundRobinGroupChat.cs
index daa715063..aabe75399 100644
--- a/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/RoundRobinGroupChat.cs
+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/RoundRobinGroupChat.cs
@@ -1,14 +1,17 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// RoundRobinGroupChat.cs
+using System.Text.Json;
using Microsoft.AutoGen.AgentChat.Abstractions;
+using Microsoft.AutoGen.AgentChat.State;
+using Microsoft.AutoGen.Contracts;
namespace Microsoft.AutoGen.AgentChat.GroupChat;
/// <summary>
/// A group chat manager that selects the next speaker in a round-robin fashion.
/// </summary>
-public class RoundRobinGroupChatManager : GroupChatManagerBase
+public class RoundRobinGroupChatManager : GroupChatManagerBase, ISaveState
{
private readonly List<string> participantTopicTypes;
private int nextSpeakerIndex;
@@ -28,6 +31,29 @@ public class RoundRobinGroupChatManager : GroupChatManagerBase
return ValueTask.FromResult(result);
}
+
+ ValueTask<JsonElement> ISaveState.SaveStateAsync()
+ {
+ RoundRobinManagerState state = new RoundRobinManagerState
+ {
+ NextSpeakerIndex = this.nextSpeakerIndex,
+ CurrentTurn = this.CurrentTurn,
+ MessageThread = this.MessageThread
+ };
+
+ return ValueTask.FromResult(SerializedState.Create(state).AsJson());
+ }
+
+ ValueTask ISaveState.LoadStateAsync(JsonElement state)
+ {
+ RoundRobinManagerState parsedState = new SerializedState(state).As<RoundRobinManagerState>();
+ this.MessageThread = parsedState.MessageThread;
+ this.CurrentTurn = parsedState.CurrentTurn;
+
+ this.nextSpeakerIndex = parsedState.NextSpeakerIndex;
+
+ return ValueTask.CompletedTask;
+ }
}
/// <summary>
diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/State/BaseState.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/State/BaseState.cs
new file mode 100644
index 000000000..b72d30a00
--- /dev/null
+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/State/BaseState.cs
@@ -0,0 +1,19 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// BaseState.cs
+
+namespace Microsoft.AutoGen.AgentChat.State;
+
+[AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
+public sealed class StateSerializableAttribute : Attribute
+{
+ public StateSerializableAttribute()
+ {
+ }
+}
+
+[StateSerializable]
+public abstract class BaseState
+{
+ public string Type => this.GetType().FullName!;
+ public string Version { get; set; } = "1.0.0"; // TODO: More rigorous state versioning?
+}
diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/State/ChatAgentContainerState.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/State/ChatAgentContainerState.cs
new file mode 100644
index 000000000..b38ce00c6
--- /dev/null
+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/State/ChatAgentContainerState.cs
@@ -0,0 +1,23 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// ChatAgentContainerState.cs
+
+using Microsoft.AutoGen.AgentChat.Abstractions;
+
+namespace Microsoft.AutoGen.AgentChat.State;
+
+public class ChatAgentContainerState : BaseState
+{
+ public required SerializedState AgentState { get; set; }
+ public List<ChatMessage> MessageBuffer { get; set; } = new();
+}
+
+public class GroupChatManagerStateBase : BaseState
+{
+ public List<AgentMessage> MessageThread { get; set; } = new();
+ public int CurrentTurn { get; set; }
+}
+
+public class RoundRobinManagerState : GroupChatManagerStateBase
+{
+ public int NextSpeakerIndex { get; set; }
+}
diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/State/SerializedState.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/State/SerializedState.cs
new file mode 100644
index 000000000..75bfe2f7c
--- /dev/null
+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/State/SerializedState.cs
@@ -0,0 +1,100 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// SerializedState.cs
+
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using Microsoft.AutoGen.AgentChat.Abstractions;
+
+namespace Microsoft.AutoGen.AgentChat.State;
+
+public class SerializedStateConverter : JsonConverter<SerializedState>
+{
+ public override SerializedState Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
+ {
+ var json = JsonDocument.ParseValue(ref reader).RootElement;
+ var state = new SerializedState(json);
+ return state;
+ }
+
+ public override void Write(Utf8JsonWriter writer, SerializedState value, JsonSerializerOptions options)
+ {
+ value.AsJson().WriteTo(writer);
+ }
+}
+
+[JsonConverter(typeof(SerializedStateConverter))]
+public class SerializedState
+{
+ private readonly JsonSerializerOptions SerializerOptions = new()
+ {
+ Converters =
+ {
+ new SerializedStateConverter(),
+ },
+ TypeInfoResolver = new MessageSerializationHelpers.MessagesTypeInfoResolver(),
+ };
+
+ public JsonElement AsJson()
+ {
+ if (this.jsonValue != null)
+ {
+ return this.jsonValue.Value;
+ }
+
+ if (this.deserializedValue == null)
+ {
+ throw new InvalidOperationException("State is not initialized.");
+ }
+
+ this.jsonValue = JsonSerializer.SerializeToElement(this.deserializedValue, SerializerOptions);
+ return this.jsonValue.Value;
+ }
+
+ public static SerializedState Create<T>(T state) where T : notnull
+ {
+ return new SerializedState((object)state);
+ }
+
+ public T As<T>()
+ {
+ if (this.deserializedValue is T value)
+ {
+ return value;
+ }
+
+ if (this.deserializedValue != null)
+ {
+ throw new InvalidOperationException($"Cannot convert state of type {this.deserializedValue.GetType()} to {typeof(T)}.");
+ }
+
+ if (this.jsonValue == null)
+ {
+ throw new InvalidOperationException("State is not initialized.");
+ }
+
+ T? result = JsonSerializer.Deserialize<T>(this.jsonValue!.Value, SerializerOptions)
+ ?? throw new InvalidOperationException($"Cannot deserialize state to {typeof(T)}.");
+
+ this.deserializedValue = result;
+
+ return result;
+ }
+
+ private object? deserializedValue;
+ private JsonElement? jsonValue;
+
+ private SerializedState(object state)
+ {
+ this.deserializedValue = state;
+ }
+
+ public SerializedState(JsonElement json)
+ {
+ this.jsonValue = json;
+ }
+
+ public static implicit operator SerializedState(JsonElement json)
+ {
+ return new SerializedState(json);
+ }
+}
diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/State/TeamState.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/State/TeamState.cs
new file mode 100644
index 000000000..c0ea71211
--- /dev/null
+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/State/TeamState.cs
@@ -0,0 +1,10 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// TeamState.cs
+
+namespace Microsoft.AutoGen.AgentChat.State;
+
+public sealed class TeamState : BaseState
+{
+ public required string TeamId { get; set; }
+ public required SerializedState RuntimeState { get; set; }
+}
diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/IAgent.cs b/dotnet/src/Microsoft.AutoGen/Contracts/IAgent.cs
index 81bdd3f32..afe205b81 100644
--- a/dotnet/src/Microsoft.AutoGen/Contracts/IAgent.cs
+++ b/dotnet/src/Microsoft.AutoGen/Contracts/IAgent.cs
@@ -42,6 +42,6 @@ public interface IHostableAgent : IAgent
/// Called when the runtime is closing.
/// </summary>
/// <returns>A task representing the asynchronous operation.</returns>
- public ValueTask CloseAsync() => ValueTask.CompletedTask;
+ public ValueTask CloseAsync();
}
diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/ISaveState.cs b/dotnet/src/Microsoft.AutoGen/Contracts/ISaveState.cs
index b6fcdc67b..cdebaa97e 100644
--- a/dotnet/src/Microsoft.AutoGen/Contracts/ISaveState.cs
+++ b/dotnet/src/Microsoft.AutoGen/Contracts/ISaveState.cs
@@ -11,6 +11,8 @@ namespace Microsoft.AutoGen.Contracts;
/// </summary>
public interface ISaveState
{
+ public static ValueTask<JsonElement> DefaultSaveStateAsync() => new(JsonDocument.Parse("{}").RootElement);
+
/// <summary>
/// Saves the current state of the object.
/// </summary>
@@ -19,10 +21,7 @@ public interface ISaveState
/// containing the saved state. The structure of the state is implementation-defined
/// but must be JSON serializable.
/// </returns>
- public virtual ValueTask<JsonElement> SaveStateAsync()
- {
- return new ValueTask<JsonElement>(JsonDocument.Parse("{}").RootElement);
- }
+ public virtual ValueTask<JsonElement> SaveStateAsync() => DefaultSaveStateAsync();
/// <summary>
/// Loads a previously saved state into the object.
@@ -32,9 +31,6 @@ public interface ISaveState
/// is implementation-defined but must be JSON serializable.
/// </param>
/// <returns>A task representing the asynchronous operation.</returns>
- public virtual ValueTask LoadStateAsync(JsonElement state)
- {
- return ValueTask.CompletedTask;
- }
+ public virtual ValueTask LoadStateAsync(JsonElement state) => ValueTask.CompletedTask;
}
diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/KVStringParseHelper.cs b/dotnet/src/Microsoft.AutoGen/Contracts/KVStringParseHelper.cs
index a164a6abe..eb6e863c9 100644
--- a/dotnet/src/Microsoft.AutoGen/Contracts/KVStringParseHelper.cs
+++ b/dotnet/src/Microsoft.AutoGen/Contracts/KVStringParseHelper.cs
@@ -13,7 +13,7 @@ internal static class KVStringParseHelper
/// <summary>
/// The regular expression pattern used to match key-value pairs in the format "key/value".
/// </summary>
- private const string KVPairPattern = @"^(?<key>\w+)/(?<value>\w+)$";
+ private const string KVPairPattern = @"^(?<key>\w+)/(?<value>[\w-]+)$";
/// <summary>
/// The compiled regex used for extracting key-value pairs from a string.
diff --git a/dotnet/src/Microsoft.AutoGen/Core/BaseAgent.cs b/dotnet/src/Microsoft.AutoGen/Core/BaseAgent.cs
index 221ecfde9..5ed2a1829 100644
--- a/dotnet/src/Microsoft.AutoGen/Core/BaseAgent.cs
+++ b/dotnet/src/Microsoft.AutoGen/Core/BaseAgent.cs
@@ -12,7 +12,7 @@ namespace Microsoft.AutoGen.Core;
/// <summary>
/// Represents the base class for an agent in the AutoGen system.
/// </summary>
-public abstract class BaseAgent : IAgent, IHostableAgent
+public abstract class BaseAgent : IHostableAgent, ISaveState
{
/// <summary>
/// The activity source for tracing.
@@ -102,4 +102,19 @@ public abstract class BaseAgent : IAgent, IHostableAgent
{
return this.Runtime.PublishMessageAsync(message, topic, sender: this.Id, messageId: messageId, cancellationToken: cancellationToken);
}
+
+ //public virtual ValueTask<JsonElement> SaveStateAsync()
+ //{
+ // return new ValueTask<JsonElement>(JsonDocument.Parse("{}").RootElement);
+ //}
+
+ //public virtual ValueTask LoadStateAsync(JsonElement _)
+ //{
+ // return ValueTask.CompletedTask;
+ //}
+
+ public virtual ValueTask CloseAsync()
+ {
+ return ValueTask.CompletedTask;
+ }
}
diff --git a/dotnet/src/Microsoft.AutoGen/Core/InProcessRuntime.cs b/dotnet/src/Microsoft.AutoGen/Core/InProcessRuntime.cs
index 21baa25e0..bf18b1da2 100644
--- a/dotnet/src/Microsoft.AutoGen/Core/InProcessRuntime.cs
+++ b/dotnet/src/Microsoft.AutoGen/Core/InProcessRuntime.cs
@@ -215,7 +215,9 @@ public sealed class InProcessRuntime : IAgentRuntime, IHostedService
var agentState = await this.agentInstances[agentId].SaveStateAsync();
state[agentId.ToString()] = agentState;
}
- return JsonSerializer.SerializeToElement(state);
+
+ JsonElement jsonElement = JsonSerializer.SerializeToElement(state);
+ return jsonElement;
}
public ValueTask<AgentType> RegisterAgentFactoryAsync<TAgent>(AgentType type, Func<AgentId, IAgentRuntime, ValueTask<TAgent>> factoryFunc) where TAgent : IHostableAgent
diff --git a/dotnet/test/Microsoft.AutoGen.AgentChat.Tests/AgentChatSmokeTest.cs b/dotnet/test/Microsoft.AutoGen.AgentChat.Tests/AgentChatSmokeTest.cs
index 072bf1b5a..97305b28b 100644
--- a/dotnet/test/Microsoft.AutoGen.AgentChat.Tests/AgentChatSmokeTest.cs
+++ b/dotnet/test/Microsoft.AutoGen.AgentChat.Tests/AgentChatSmokeTest.cs
@@ -1,10 +1,13 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// AgentChatSmokeTest.cs
+using System.Text.Json;
using Microsoft.AutoGen.AgentChat.Abstractions;
using Microsoft.AutoGen.AgentChat.Agents;
using Microsoft.AutoGen.AgentChat.GroupChat;
+using Microsoft.AutoGen.AgentChat.State;
using Microsoft.AutoGen.AgentChat.Terminations;
+using Microsoft.AutoGen.Contracts;
using Xunit;
namespace Microsoft.AutoGen.AgentChat.Tests;
@@ -38,7 +41,7 @@ public class AgentChatSmokeTest
}
}
- public class TerminatingAgent : ChatAgentBase
+ public class TerminatingAgent : ChatAgentBase, ISaveState
{
public List<ChatMessage>? IncomingMessages { get; private set; }
@@ -82,6 +85,29 @@ public class AgentChatSmokeTest
return ValueTask.CompletedTask;
}
+
+ public class State : BaseState
+ {
+ public required List<ChatMessage> IncomingMessages { get; set; }
+ }
+
+ ValueTask<JsonElement> ISaveState.SaveStateAsync()
+ {
+ SerializedState serializedState = SerializedState.Create(new State
+ {
+ IncomingMessages = this.IncomingMessages ?? new List<ChatMessage>()
+ });
+
+ return ValueTask.FromResult(serializedState.AsJson());
+ }
+
+ ValueTask ISaveState.LoadStateAsync(JsonElement state)
+ {
+ State parsedState = new SerializedState(state).As<State>();
+ this.IncomingMessages = [.. parsedState.IncomingMessages];
+
+ return ValueTask.CompletedTask;
+ }
}
private ValueTask<TaskResult> RunChatAsync(TerminatingAgent terminatingAgent, out ITeam chat)
@@ -89,7 +115,7 @@ public class AgentChatSmokeTest
chat = new RoundRobinGroupChat(
[
new SpeakMessageAgent("Speak", "Speak", "Hello"),
- terminatingAgent
+ terminatingAgent,
],
terminationCondition: new StopMessageTermination());
@@ -122,4 +148,45 @@ public class AgentChatSmokeTest
Assert.Null(terminatingAgent.IncomingMessages);
}
+
+ [Fact]
+ public async Task Test_RoundRobin_SaveLoadRun()
+ {
+ TerminatingAgent t1 = new("Terminate1", "Terminate"), t2 = new("Terminate2", "Terminate");
+ SpeakMessageAgent s1 = new("Speak1", "Speak", "Hello"), s2 = new("Speak2", "Speak", "World");
+
+ ITeam chat = new RoundRobinGroupChat(
+ [s1, t1, s2, t2],
+ terminationCondition: new StopMessageTermination());
+
+ TaskResult result = await chat.RunAsync("1");
+
+ Assert.Equal(3, result.Messages.Count);
+ Assert.Equal("1", Assert.IsType<TextMessage>(result.Messages[0]).Content);
+ Assert.Equal("Hello", Assert.IsType<TextMessage>(result.Messages[1]).Content);
+ Assert.Equal("Terminating; got: Hello", Assert.IsType<StopMessage>(result.Messages[2]).Content);
+
+ // Save state
+ JsonElement state = await chat.SaveStateAsync();
+
+ // Reset chat
+ await chat.ResetAsync();
+
+ Assert.Null(t1.IncomingMessages);
+
+ // Load state
+
+ await chat.LoadStateAsync(state);
+
+ Assert.NotNull(t1.IncomingMessages);
+
+ // Check that we resume the conversation in the right place
+ TaskResult result2 = await chat.RunAsync("2");
+
+ Assert.Equal(3, result.Messages.Count);
+ Assert.Equal("2", Assert.IsType<TextMessage>(result2.Messages[0]).Content);
+ Assert.Equal("World", Assert.IsType<TextMessage>(result2.Messages[1]).Content);
+ Assert.Equal("Terminating; got: World", Assert.IsType<StopMessage>(result2.Messages[2]).Content);
+
+ }
}