A programming framework for agentic AI
.NET AgentChat Part 1: Abstractions, Base Classes, RoundRobin (#5434)
Jacob Alber9f1c4c924f67
diff --git a/dotnet/AutoGen.sln b/dotnet/AutoGen.slnindex 74b7ac965..a267a11e6 100644--- a/dotnet/AutoGen.sln+++ b/dotnet/AutoGen.sln@@ -122,6 +122,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GettingStartedGrpc", "samplEndProjectProject("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.AutoGen.Core.Grpc.Tests", "test\Microsoft.AutoGen.Core.Grpc.Tests\Microsoft.AutoGen.Core.Grpc.Tests.csproj", "{23A028D3-5EB1-4FA0-9CD1-A1340B830579}"EndProject+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.AutoGen.AgentChat", "src\Microsoft.AutoGen\AgentChat\Microsoft.AutoGen.AgentChat.csproj", "{7F828599-56E8-4597-8F68-EE26FD631417}"+EndProject+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.AutoGen.AgentChat.Tests", "test\Microsoft.AutoGen.AgentChat.Tests\Microsoft.AutoGen.AgentChat.Tests.csproj", "{217A4F86-8ADD-4998-90BA-880092A019F5}"+EndProjectGlobalGlobalSection(SolutionConfigurationPlatforms) = preSolutionDebug|Any CPU = Debug|Any CPU@@ -300,16 +304,14 @@ Global{70A8D4B5-D0A6-4098-A6F3-6ED274B65E7D}.Debug|Any CPU.Build.0 = Debug|Any CPU{70A8D4B5-D0A6-4098-A6F3-6ED274B65E7D}.Release|Any CPU.ActiveCfg = Release|Any CPU{70A8D4B5-D0A6-4098-A6F3-6ED274B65E7D}.Release|Any CPU.Build.0 = Release|Any CPU- {3D83C6DB-ACEA-48F3-959F-145CCD2EE135}.CoreOnly|Any CPU.ActiveCfg = Debug|Any CPU- {3D83C6DB-ACEA-48F3-959F-145CCD2EE135}.CoreOnly|Any CPU.Build.0 = Debug|Any CPU- {3D83C6DB-ACEA-48F3-959F-145CCD2EE135}.Debug|Any CPU.ActiveCfg = Debug|Any CPU- {3D83C6DB-ACEA-48F3-959F-145CCD2EE135}.Debug|Any CPU.Build.0 = Debug|Any CPU- {3D83C6DB-ACEA-48F3-959F-145CCD2EE135}.Release|Any CPU.ActiveCfg = Release|Any CPU- {3D83C6DB-ACEA-48F3-959F-145CCD2EE135}.Release|Any CPU.Build.0 = Release|Any CPU{AAD593FE-A49B-425E-A9FE-A0022CD25E3D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU{AAD593FE-A49B-425E-A9FE-A0022CD25E3D}.Debug|Any CPU.Build.0 = Debug|Any CPU{AAD593FE-A49B-425E-A9FE-A0022CD25E3D}.Release|Any CPU.ActiveCfg = Release|Any CPU{AAD593FE-A49B-425E-A9FE-A0022CD25E3D}.Release|Any CPU.Build.0 = Release|Any CPU+ {3D83C6DB-ACEA-48F3-959F-145CCD2EE135}.Debug|Any CPU.ActiveCfg = Debug|Any CPU+ {3D83C6DB-ACEA-48F3-959F-145CCD2EE135}.Debug|Any CPU.Build.0 = Debug|Any CPU+ {3D83C6DB-ACEA-48F3-959F-145CCD2EE135}.Release|Any CPU.ActiveCfg = Release|Any CPU+ {3D83C6DB-ACEA-48F3-959F-145CCD2EE135}.Release|Any CPU.Build.0 = Release|Any CPU{C3740DF1-18B1-4607-81E4-302F0308C848}.Debug|Any CPU.ActiveCfg = Debug|Any CPU{C3740DF1-18B1-4607-81E4-302F0308C848}.Debug|Any CPU.Build.0 = Debug|Any CPU{C3740DF1-18B1-4607-81E4-302F0308C848}.Release|Any CPU.ActiveCfg = Release|Any CPU@@ -318,6 +320,14 @@ Global{23A028D3-5EB1-4FA0-9CD1-A1340B830579}.Debug|Any CPU.Build.0 = Debug|Any CPU{23A028D3-5EB1-4FA0-9CD1-A1340B830579}.Release|Any CPU.ActiveCfg = Release|Any CPU{23A028D3-5EB1-4FA0-9CD1-A1340B830579}.Release|Any CPU.Build.0 = Release|Any CPU+ {7F828599-56E8-4597-8F68-EE26FD631417}.Debug|Any CPU.ActiveCfg = Debug|Any CPU+ {7F828599-56E8-4597-8F68-EE26FD631417}.Debug|Any CPU.Build.0 = Debug|Any CPU+ {7F828599-56E8-4597-8F68-EE26FD631417}.Release|Any CPU.ActiveCfg = Release|Any CPU+ {7F828599-56E8-4597-8F68-EE26FD631417}.Release|Any CPU.Build.0 = Release|Any CPU+ {217A4F86-8ADD-4998-90BA-880092A019F5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU+ {217A4F86-8ADD-4998-90BA-880092A019F5}.Debug|Any CPU.Build.0 = Debug|Any CPU+ {217A4F86-8ADD-4998-90BA-880092A019F5}.Release|Any CPU.ActiveCfg = Release|Any CPU+ {217A4F86-8ADD-4998-90BA-880092A019F5}.Release|Any CPU.Build.0 = Release|Any CPUEndGlobalSectionGlobalSection(SolutionProperties) = preSolutionHideSolutionNode = FALSE@@ -368,11 +378,13 @@ Global{EAFFE339-26CB-4019-991D-BCCE8E7D33A1} = {F823671B-3ECA-4AE6-86DA-25E920D3FE64}{58AD8E1D-83BD-4950-A324-1A20677D78D9} = {F823671B-3ECA-4AE6-86DA-25E920D3FE64}{70A8D4B5-D0A6-4098-A6F3-6ED274B65E7D} = {CE0AA8D5-12B8-4628-9589-DAD8CB0DDCF6}- {3D83C6DB-ACEA-48F3-959F-145CCD2EE135} = {18BF8DD7-0585-48BF-8F97-AD333080CE06}{AAD593FE-A49B-425E-A9FE-A0022CD25E3D} = {F42F9C8E-7BD9-4687-9B63-AFFA461AF5C1}{F42F9C8E-7BD9-4687-9B63-AFFA461AF5C1} = {CE0AA8D5-12B8-4628-9589-DAD8CB0DDCF6}+ {3D83C6DB-ACEA-48F3-959F-145CCD2EE135} = {18BF8DD7-0585-48BF-8F97-AD333080CE06}{C3740DF1-18B1-4607-81E4-302F0308C848} = {CE0AA8D5-12B8-4628-9589-DAD8CB0DDCF6}{23A028D3-5EB1-4FA0-9CD1-A1340B830579} = {F823671B-3ECA-4AE6-86DA-25E920D3FE64}+ {7F828599-56E8-4597-8F68-EE26FD631417} = {18BF8DD7-0585-48BF-8F97-AD333080CE06}+ {217A4F86-8ADD-4998-90BA-880092A019F5} = {F823671B-3ECA-4AE6-86DA-25E920D3FE64}EndGlobalSectionGlobalSection(ExtensibilityGlobals) = postSolutionSolutionGuid = {93384647-528D-46C8-922C-8DB36A382F0B}diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/ChatAgent.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/ChatAgent.csnew file mode 100644index 000000000..6cad4f88d--- /dev/null+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/ChatAgent.cs@@ -0,0 +1,193 @@+// Copyright (c) Microsoft Corporation. All rights reserved.+// ChatAgent.cs++using System.Text.RegularExpressions;++namespace Microsoft.AutoGen.AgentChat.Abstractions;++/// <summary>+/// A valid name for an agent.+/// </summary>+/// <remarks>+/// To ensure parity with Python, we require agent names to be Python identifiers.+/// </remarks>+public struct AgentName+{+ //+ // TODO: Ensure that only valid C# identifiers can pass the validation on Python?++ /*+ From https://docs.python.org/3/reference/lexical_analysis.html#identifiers:+ ```+ identifier ::= xid_start xid_continue*+ id_start ::= <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property>+ id_continue ::= <all characters in id_start, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property>+ xid_start ::= <all characters in id_start whose NFKC normalization is in "id_start xid_continue*">+ xid_continue ::= <all characters in id_continue whose NFKC normalization is in "id_continue*">+ ```++ Note: we are not going to deal with normalization; it would require a lot of effort for likely little gain+ (this will mean that, strictly speaking, .NET will support a subset of the identifiers that Python does)++ The Unicode category codes mentioned above stand for:++ * Lu - uppercase letters+ * Ll - lowercase letters+ * Lt - titlecase letters+ * Lm - modifier letters+ * Lo - other letters+ * Nl - letter numbers*+ * Mn - nonspacing marks+ * Mc - spacing combining marks*+ * Nd - decimal numbers+ * Pc - connector punctuations++ Of these, most are captured by "word characters" in .NET, \w, only needing \p{Nl} and \p{Mc} to be added.+ While Copilot /thinks/ that \p{Pc} is needed, it is not, as it is part of \w in .NET.++ * Other_ID_Start - explicit list of characters in PropList.txt to support backwards compatibility+ * Other_ID_Continue - likewise++ # ================================================++ 1885..1886 ; Other_ID_Start # Mn [2] MONGOLIAN LETTER ALI GALI BALUDA..MONGOLIAN LETTER ALI GALI THREE BALUDA+ 2118 ; Other_ID_Start # Sm SCRIPT CAPITAL P+ 212E ; Other_ID_Start # So ESTIMATED SYMBOL+ 309B..309C ; Other_ID_Start # Sk [2] KATAKANA-HIRAGANA VOICED SOUND MARK..KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK++ # Total code points: 6++ The pattern for this in .NET is [\u1185-\u1186\u2118\u212E\u309B-\u309C]++ # ================================================++ 00B7 ; Other_ID_Continue # Po MIDDLE DOT+ 0387 ; Other_ID_Continue # Po GREEK ANO TELEIA+ 1369..1371 ; Other_ID_Continue # No [9] ETHIOPIC DIGIT ONE..ETHIOPIC DIGIT NINE+ 19DA ; Other_ID_Continue # No NEW TAI LUE THAM DIGIT ONE+ 200C..200D ; Other_ID_Continue # Cf [2] ZERO WIDTH NON-JOINER..ZERO WIDTH JOINER+ 30FB ; Other_ID_Continue # Po KATAKANA MIDDLE DOT+ FF65 ; Other_ID_Continue # Po HALFWIDTH KATAKANA MIDDLE DOT++ # Total code points: 16++ The pattern for this in .NET is [\u00B7\u0387\u1369-\u1371\u19DA\u200C\u200D\u30FB\uFF65]++ # ================================================++ Classes for "IdStart": {Lu, Ll, Lt, Lm, Lo, Nl, '_', Other_ID_Start}+ pattern: [\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}_\u1185-\u1186\u2118\u212E\u309B-\u309C]++ Classes for "IdContinue": {\w, Nl, Mc, Other_ID_Start, Other_ID_Continue}+ pattern: [\w\p{Nl}\p{Mc}_\u1185-\u1186\u2118\u212E\u309B-\u309C\u00B7\u0387\u1369-\u1371\u19DA\u200C\u200D\u30FB\uFF65]++ Match group for identifiers:+ (?<ident>(?:[\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}_\u1185-\u1186\u2118\u212E\u309B-\u309C])(?:[\w\p{Nl}\p{Mc}_\u1185-\u1186\u2118\u212E\u309B-\u309C\u00B7\u0387\u1369-\u1371\u19DA\u200C\u200D\u30FB\uFF65])*)+ */++ private const string IdStartClass = @"[\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}_\u1185-\u1186\u2118\u212E\u309B-\u309C]";+ private const string IdContinueClass = @"[\w\p{Nl}\p{Mc}_\u1185-\u1186\u2118\u212E\u309B-\u309C\u00B7\u0387\u1369-\u1371\u19DA\u200C\u200D\u30FB\uFF65]";++ private static readonly Regex AgentNameRegex = new Regex($"^{IdStartClass}{IdContinueClass}*$", RegexOptions.Compiled | RegexOptions.Singleline);++ public string Value { get; }++ public AgentName(string name)+ {+ AgentName.CheckValid(name);++ this.Value = name;+ }++ public static bool IsValid(string name) => AgentNameRegex.IsMatch(name);++ public static void CheckValid(string name)+ {+ if (!AgentName.IsValid(name))+ {+ throw new ArgumentException($"Agent name '{name}' is not a valid identifier.");+ }+ }++ // Implicit cast to string+ public static implicit operator string(AgentName agentName) => agentName.Value;+}++/// <summary>+/// A response from calling <see cref="IChatAgent"/>'s <see cref="IHandleChat{TIn, Response}.HandleAsync(TIn)"/>."/>+/// </summary>+public class Response+{+ /// <summary>+ /// A chat message produced by the agent as a response.+ /// </summary>+ public required ChatMessage Message { get; set; }++ /// <summary>+ /// Inner messages produced by the agent.+ /// </summary>+ public List<AgentMessage>? InnerMessages { get; set; }+}++/// <summary>+/// Base class for representing a stream of messages interspacing responses (<typeparamref name="TResponse"/>) and+/// internal processing messages (<typeparamref name="TInternalMessage"/>). This functions as a discriminated union.+/// </summary>+/// <typeparam name="TResponse">The response type. Usually <see cref="Response"/>.</typeparam>+/// <typeparam name="TInternalMessage">The ineternal message type. Usually <see cref="AgentMessage"/>.</typeparam>+public class StreamingFrame<TResponse, TInternalMessage>() where TInternalMessage : AgentMessage+{+ public enum FrameType+ {+ InternalMessage,+ Response+ }++ public FrameType Type { get; set; }++ public TInternalMessage? InternalMessage { get; set; }+ public TResponse? Response { get; set; }+}++/// <summary>+/// Base class for representing a stream of messages with internal messages of any <see cref="AgentMessage"/> subtype.+/// </summary>+/// <typeparam name="TResponse">The response type. Usually <see cref="Response"/>.</typeparam>+public class StreamingFrame<TResponse> : StreamingFrame<TResponse, AgentMessage>;++/// <summary>+/// The stream frame for <see cref="IChatAgent"/>'s <see cref="IHandleStream{TIn, ChatStreamFrame}.StreamAsync(TIn)"/>+/// </summary>+public class ChatStreamFrame : StreamingFrame<Response, AgentMessage>;++/// <summary>+/// An agent that can participate in a chat.+/// </summary>+public interface IChatAgent :+ IHandleChat<IEnumerable<ChatMessage>, Response>,+ IHandleStream<IEnumerable<ChatMessage>, ChatStreamFrame>+{+ /// <summary>+ /// The name of the agent. This is used by team to uniquely identify the agent.It should be unique within the team.+ /// </summary>+ AgentName Name { get; }++ /// <summary>+ /// The description of the agent. This is used by team to make decisions about which agents to use.The description+ /// should describe the agent's capabilities and how to interact with it.+ /// </summary>+ string Description { get; }++ /// <summary>+ /// The types of messages that the agent produces.+ /// </summary>+ IEnumerable<Type> ProducedMessageTypes { get; } // TODO: Is there a way to make this part of the type somehow?+ // Annotations, or IProduce<>? Do we ever actually access this?++ /// <summary>+ /// Reset the agent to its initialization state.+ /// </summary>+ /// <param name="cancellationToken"></param>+ /// <returns></returns>+ ValueTask ResetAsync(CancellationToken cancellationToken);+}diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Handoff.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Handoff.csnew file mode 100644index 000000000..0153f111c--- /dev/null+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Handoff.cs@@ -0,0 +1,50 @@+// Copyright (c) Microsoft Corporation. All rights reserved.+// Handoff.cs++namespace Microsoft.AutoGen.AgentChat.Abstractions;++/// <summary>+/// Handoff configuration.+/// </summary>+/// <param name="target">The name of the target agent receiving the handoff.</param>+/// <param name="description">The description of the handoff such as the condition under which it should happen and the target+/// agent's ability. If not provided, it is generated from the target agent's name.</param>+/// <param name="name">The name of this handoff configuration. If not provided, it is generated from the target agent's name.</param>+/// <param name="message">The message to the target agent. If not provided, it is generated from the target agent's name.</param>+public class Handoff(string target, string? description = null, string? name = null, string? message = null)+{+ private static string? CheckName(string? name)+ {+ if (name != null && !AgentName.IsValid(name))+ {+ throw new ArgumentException($"Handoff name '{name}' is not a valid identifier.");+ }++ return name;+ }++ /// <summary>+ /// The name of the target agent receiving the handoff.+ /// </summary>+ public AgentName Target { get; } = new AgentName(target);++ /// <summary>+ /// The description of the handoff such as the condition under which it should happen and the target.+ /// </summary>+ public string Description { get; } = description ?? $"Handoff to {target}";++ /// <summary>+ /// The name of this handoff configuration.+ /// </summary>+ public string Name { get; } = CheckName(name) ?? $"transfer_to_{target.ToLowerInvariant()}";++ /// <summary>+ /// The content of the HandoffMessage that will be sent.+ /// </summary>+ public string Message { get; } = message ?? $"Transferred to {target}, adopting the role of {target} immediately.";++ /// <summary>+ /// Handoff Tool to execute the handoff.+ /// </summary>+ public ITool HandoffTool => new CallableTool(this.Name, this.Description, () => { return this.Message; });+}diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/ITeam.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/ITeam.csnew file mode 100644index 000000000..e6c16cba4--- /dev/null+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/ITeam.cs@@ -0,0 +1,17 @@+// Copyright (c) Microsoft Corporation. All rights reserved.+// ITeam.cs++namespace Microsoft.AutoGen.AgentChat.Abstractions;++/// <summary>+/// A team of agents.+/// </summary>+public interface ITeam : ITaskRunner+{+ /// <summary>+ /// Reset the team and all its participants to its initial state.+ /// </summary>+ /// <param name="cancellationToken"></param>+ /// <returns>A <see cref="ValueTask"/> representing the asynchronous operation.</returns>+ ValueTask ResetAsync(CancellationToken cancellationToken = default);+}diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/MessageHandling.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/MessageHandling.csnew file mode 100644index 000000000..4183723e8--- /dev/null+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/MessageHandling.cs@@ -0,0 +1,38 @@+// Copyright (c) Microsoft Corporation. All rights reserved.+// MessageHandling.cs++namespace Microsoft.AutoGen.AgentChat.Abstractions;++public interface IHandleChat<in TIn>+{+ ValueTask HandleAsync(TIn item)+ {+ return this.HandleAsync(item, CancellationToken.None);+ }++ ValueTask HandleAsync(TIn item, CancellationToken cancellationToken);+}++public interface IHandleChat<in TIn, TOut> // TODO: Map this to IHandle<> somehow?+{+ ValueTask<TOut> HandleAsync(TIn item)+ {+ return this.HandleAsync(item, CancellationToken.None);+ }++ ValueTask<TOut> HandleAsync(TIn item, CancellationToken cancellationToken);+}++public interface IHandleDefault : IHandleChat<object>+{+}++public interface IHandleStream<in TIn, TOut>+{+ IAsyncEnumerable<TOut> StreamAsync(TIn item)+ {+ return this.StreamAsync(item, CancellationToken.None);+ }++ IAsyncEnumerable<TOut> StreamAsync(TIn item, CancellationToken cancellationToken);+}diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Messages.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Messages.csnew file mode 100644index 000000000..83a3781e6--- /dev/null+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Messages.cs@@ -0,0 +1,616 @@+// Copyright (c) Microsoft Corporation. All rights reserved.+// Messages.cs++using System.Collections;+using System.Diagnostics;+using System.Text;++using Microsoft.Extensions.AI;++namespace Microsoft.AutoGen.AgentChat.Abstractions;++/// <summary>+/// The base class for all messages that can be sent between agents.+/// </summary>+/// <remarks>+/// This functions as a combination of both <c>BaseMessage</c> and <c>AgentMessage</c> on the Python side.+/// </remarks>+public abstract class AgentMessage+{+ /// <summary>+ /// The name of the agent that sent this message.+ /// </summary>+ public required string Source { get; set; }++ // IMPORTANT NOTE: Unlike the ITypeMarshal<AgentMessage, WireProtocol.AgentMessage> implementation in ProtobufTypeMarshal,+ // the .ToWire() call on this is intended to be used for directly converting a concrete message type to its leaf representation.+ // In the context of Protobuf these may not be the same due to discriminated union types being real types, as opposed to+ // a runtime union restriction.+ //public IMessage ToWire()+ //{+ // return this switch+ // {+ // ChatMessage chatMessage => ProtobufTypeMarshal.Convert<ChatMessage, WireProtocol.ChatMessage>(chatMessage),+ // AgentEvent agentEvent => ProtobufTypeMarshal.Convert<AgentEvent, WireProtocol.AgentEvent>(agentEvent),+ // _ => throw new InvalidOperationException($"Unknown type {this.GetType().Name}"),+ // };+ //}+}++/// <summary>+/// Events emitted by agents and teams when they work, not used for agent-to-agent communication.+/// </summary>+public abstract class AgentEvent : AgentMessage+{+ public Microsoft.Extensions.AI.ChatMessage ToCompletionClientMessage()+ => ToCompletionClientMessage(role: ChatRole.Assistant);++ /// <summary>+ /// Converts the <see cref="AgentEvent"/> to a <see cref="Microsoft.Extensions.AI.ChatMessage"/>.+ /// </summary>+ /// <remarks>+ /// This should usually be <see cref="ChatRole.Assistant"/>+ /// </remarks>+ /// <param name="role">The role of the agent that is sending the message.</param>+ /// <returns>+ /// A <see cref="Microsoft.Extensions.AI.ChatMessage"/> that represents the <see cref="AgentEvent"/>.+ /// </returns>+ public abstract Microsoft.Extensions.AI.ChatMessage ToCompletionClientMessage(ChatRole role);+}++/// <summary>+/// Messages for agent-to-agent communication.+/// </summary>+public abstract class ChatMessage : AgentMessage+{+ /// <summary>+ /// Converts the <see cref="ChatMessage"/> to a <see cref="Microsoft.Extensions.AI.ChatMessage"/>.+ /// </summary>+ /// <param name="role">The role of the agent that is sending the message.</param>+ /// <returns>+ /// A <see cref="Microsoft.Extensions.AI.ChatMessage"/> that represents the <see cref="ChatMessage"/>.+ /// </returns>+ public abstract Microsoft.Extensions.AI.ChatMessage ToCompletionClientMessage(ChatRole role);+}++// Leaf Classes++/// <summary>+/// A text message.+/// </summary>+public class TextMessage : ChatMessage+{+ /// <summary>+ /// The content of the message.+ /// </summary>+ public required string Content { get; set; }++ /// <inheritdoc cref="ChatMessage.ToCompletionClientMessage(ChatRole)" />/>+ public override Microsoft.Extensions.AI.ChatMessage ToCompletionClientMessage(ChatRole role)+ {+ return new Microsoft.Extensions.AI.ChatMessage(role, this.Content) { AuthorName = this.Source };+ }+}++/// <summary>+/// The data inside of a multi-modal message. Can be either a <c>string</c> or an Image.+/// </summary>+/// <remarks>+/// This presents an API surface around the types that are supported by AgentChat, rather+/// than allowing any <see cref="Microsoft.Extensions.AI.AIContent"/>.+/// </remarks>+public struct MultiModalData+{+ /// <summary>+ /// Supported <c>Type</c>s of <see cref="Microsoft.Extensions.AI.AIContent"/>.+ /// </summary>+ public enum Type+ {+ String, Image+ }++ /// <summary>+ /// Checks the type of the <see cref="AIContent"/> and wraps it in a <see cref="MultiModalData"/> instance if+ /// it is a supported type.+ /// </summary>+ /// <param name="item">The <see cref="AIContent"/> to wrap.</param>+ /// <returns>A <see cref="MultiModalData"/> instance wrapping the <paramref name="item"/>.</returns>+ /// <exception cref="ArgumentException">+ /// Thrown if the <paramref name="item"/> is not a <see cref="TextContent"/> or <see cref="ImageContent"/>.+ /// </exception>+ public static MultiModalData CheckTypeAndCreate(AIContent item)+ {+ if (item is TextContent text)+ {+ return new MultiModalData(text);+ }+ else if (item is ImageContent image)+ {+ return new MultiModalData(image);+ }+ else+ {+ throw new ArgumentException("Only TextContent and ImageContent are allowed in MultiModalMessage");+ }+ }++ /// <summary>+ /// Initializes a new instance of the <see cref="MultiModalData"/> with a <see cref="string"/>.+ /// </summary>+ /// <param name="text">The text to wrap.</param>+ public MultiModalData(string text)+ {+ ContentType = Type.String;+ AIContent = new TextContent(text);+ }++ /// <summary>+ /// Initializes a new instance of the <see cref="MultiModalData"/> with a <see cref="TextContent"/>.+ /// </summary>+ /// <param name="textContent">The <see cref="TextContent"/> to wrap.</param>+ public MultiModalData(TextContent textContent)+ {+ ContentType = Type.String;+ AIContent = textContent;+ }++ /// <summary>+ /// Initializes a new instance of the <see cref="MultiModalData"/> with an <see cref="ImageContent"/>.+ /// </summary>+ /// <param name="image">The image to wrap.</param>+ public MultiModalData(ImageContent image)+ {+ ContentType = Type.Image;+ AIContent = image;+ }++ /// <summary>+ /// Gets the <see cref="AIContent"/> wrapped by this instance.+ /// </summary>+ public Type ContentType { get; }++ /// <summary>+ /// Gets the <see cref="AIContent"/> wrapped by this instance.+ /// </summary>+ public AIContent AIContent { get; }+}++/// <summary>+/// A multi-modal message.+/// </summary>+public class MultiModalMessage : ChatMessage, IList<AIContent>+{+ /// <inheritdoc cref="IList{T}.this" />"+ public AIContent this[int index]+ {+ get => this.Content[index].AIContent;+ set => this.Content[index] = MultiModalData.CheckTypeAndCreate(value);+ }++ /// <summary>+ /// The contents of the message.+ /// </summary>+ public List<MultiModalData> Content { get; private set; } = new List<MultiModalData>();++ /// <inheritdoc cref="ICollection{AIContent}.Count" />+ public int Count => this.Content.Count;++ /// <inheritdoc cref="ICollection{AIContent}.IsReadOnly" />+ public bool IsReadOnly => false;++ /// <summary>+ /// Adds a range of <see cref="MultiModalData"/> to the message. The type does not need+ /// to be checked because it was already validated when the <see cref="MultiModalData"/>+ /// was created.+ /// </summary>+ /// <param name="items">The items to add.</param>+ internal void AddRangeUnchecked(IEnumerable<MultiModalData> items)+ {+ this.Content.AddRange(items);+ }++ /// <summary>+ /// Checks and adds a range of <see cref="AIContent"/> to the message.+ /// </summary>+ /// <param name="items">The items to add.</param>+ public void AddRange(IEnumerable<AIContent> items)+ {+ foreach (AIContent item in items)+ {+ this.Content.Add(MultiModalData.CheckTypeAndCreate(item));+ }+ }++ /// <summary>+ /// Adds a range of <see cref="string"/> to the message.+ /// </summary>+ /// <param name="textItems">The items to add.</param>+ public void AddRange(IEnumerable<TextContent> textItems)+ {+ foreach (TextContent item in textItems)+ {+ this.Add(item);+ }+ }++ /// <summary>+ /// Adds a range of <see cref="string"/> to the message.+ /// </summary>+ /// <param name="textItems">The items to add.</param>+ public void AddRange(IEnumerable<string> textItems)+ {+ foreach (string item in textItems)+ {+ this.Add(item);+ }+ }++ /// <summary>+ /// Adds a range of <see cref="ImageContent"/> to the message.+ /// </summary>+ /// <param name="images">The items to add.</param>+ public void AddRange(IEnumerable<ImageContent> images)+ {+ foreach (ImageContent image in images)+ {+ this.Add(image);+ }+ }++ /// <summary>+ /// Checks and adds an <see cref="AIContent"/> to the message.+ /// </summary>+ /// <param name="item">The item to add.</param>+ public void Add(AIContent item)+ {+ this.Content.Add(MultiModalData.CheckTypeAndCreate(item));+ }++ /// <summary>+ /// Adds a <see cref="string"/> to the message.+ /// </summary>+ /// <param name="text">The text to add.</param>+ public void Add(string text)+ {+ this.Content.Add(new(text));+ }++ /// <summary>+ /// Adds a <see cref="TextContent"/> to the message.+ /// </summary>+ /// <param name="image">The image to add.</param>+ public void Add(ImageContent image)+ {+ this.Content.Add(new(image));+ }++ /// <summary>+ /// Adds a <see cref="TextContent"/> to the message.+ /// </summary>+ /// <param name="text">The <see cref="TextContent"/> to add.</param>+ public void Add(TextContent text)+ {+ this.Content.Add(new(text));+ }++ /// <inheritdoc cref="ICollection{AIContent}.Clear" />+ public void Clear()+ {+ this.Content.Clear();+ }++ /// <inheritdoc cref="ICollection{AIContent}.Contains" />+ public bool Contains(AIContent item)+ {+ return this.Content.Any(x => x.AIContent == item);+ }++ /// <inheritdoc cref="ICollection{AIContent}.CopyTo" />+ public void CopyTo(AIContent[] array, int arrayIndex)+ {+ if (array == null)+ {+ throw new ArgumentNullException(nameof(array));+ }++ if (arrayIndex < 0 || arrayIndex >= array.Length)+ {+ throw new ArgumentOutOfRangeException(nameof(arrayIndex));+ }++ if (array.Length - arrayIndex < this.Content.Count)+ {+ throw new ArgumentException("The number of elements in the source is greater than the available space from arrayIndex to the end of the destination array.");+ }++ for (var i = 0; i < this.Content.Count; i++)+ {+ array[arrayIndex + i] = this.Content[i].AIContent;+ }+ }++ /// <inheritdoc cref="IEnumerable{AIContent}.GetEnumerator" />+ public IEnumerator<AIContent> GetEnumerator()+ {+ return this.Content.Select(x => x.AIContent).GetEnumerator();+ }++ /// <inheritdoc cref="IList{AIContent}.IndexOf" />+ public int IndexOf(AIContent item)+ {+ return this.Content.FindIndex(x => x.AIContent == item);+ }++ /// <inheritdoc cref="IList{String}.IndexOf(String)"/>+ public int IndexOf(string text)+ {+ return this.Content.FindIndex(x => x.ContentType == MultiModalData.Type.String && ((TextContent)x.AIContent).Text == text);+ }++ /// <inheritdoc cref="IList{AIContent}.Insert" />/>+ public void Insert(int index, AIContent item)+ {+ this.Content.Insert(index, MultiModalData.CheckTypeAndCreate(item));+ }++ /// <inheritdoc cref="IList{String}.Insert(int, String)"/>+ public void Insert(int index, string text)+ {+ this.Content.Insert(index, new(text));+ }++ /// <inheritdoc cref="IList{TextContent}.Insert(int, TextContent)"/>+ public void Insert(int index, TextContent text)+ {+ this.Content.Insert(index, new(text));+ }++ /// <inheritdoc cref="IList{ImageContent}.Insert(int, ImageContent)"/>+ public void Insert(int index, ImageContent image)+ {+ this.Content.Insert(index, new(image));+ }++ /// <inheritdoc cref="ICollection{AIContent}.Remove" />+ public bool Remove(AIContent item)+ {+ int targetIndex = Content.FindIndex(x => x.AIContent == item);+ if (targetIndex == -1)+ {+ return false;+ }++ this.Content.RemoveAt(targetIndex);+ return true;+ }++ /// <inheritdoc cref="IList{AIContent}.RemoveAt" />+ public void RemoveAt(int index)+ {+ this.Content.RemoveAt(index);+ }++ /// <inheritdoc cref="IEnumerable.GetEnumerator" />+ IEnumerator IEnumerable.GetEnumerator()+ {+ return GetEnumerator();+ }++ /// <inheritdoc cref="ChatMessage.ToCompletionClientMessage(ChatRole)" />/>+ public override Microsoft.Extensions.AI.ChatMessage ToCompletionClientMessage(ChatRole role)+ {+ StringBuilder contentBuilder = new StringBuilder();+ foreach (MultiModalData item in this.Content)+ {+ if (item.ContentType == MultiModalData.Type.String)+ {+ contentBuilder.AppendLine(item.AIContent.RawRepresentation as string ?? "");+ }+ else if (item.ContentType == MultiModalData.Type.Image)+ {+ contentBuilder.AppendLine("[Image]");+ }+ }++ return new Microsoft.Extensions.AI.ChatMessage(role, contentBuilder.ToString()) { AuthorName = this.Source };+ }+}++/// <summary>+/// A message requesting stop of a conversation.+/// </summary>+public class StopMessage : ChatMessage+{+ public required string Content { get; set; }++ public override Microsoft.Extensions.AI.ChatMessage ToCompletionClientMessage(ChatRole role)+ {+ Debug.Assert(role == ChatRole.Assistant, "StopMessage can only come from agents in the Assistant Role");+ return new Microsoft.Extensions.AI.ChatMessage(ChatRole.Assistant, this.Content) { AuthorName = this.Source };+ }+}++/// <summary>+/// A message requesting handoff of a conversation to another agent.+/// </summary>+public class HandoffMessage : ChatMessage+{+ /// <summary>+ /// The name of the target agent to handoff to.+ /// </summary>+ public required string Target { get; set; }++ /// <summary>+ /// The handoff message to the target agent.+ /// </summary>+ public required string Context { get; set; }++ /// <inheritdoc cref="ChatMessage.ToCompletionClientMessage(ChatRole)" />/>+ public override Microsoft.Extensions.AI.ChatMessage ToCompletionClientMessage(ChatRole role)+ {+ Debug.Assert(role == ChatRole.Assistant, "HandoffMessage can only come from agents in the Assistant Role");+ return new Microsoft.Extensions.AI.ChatMessage(ChatRole.Assistant, this.Context) { AuthorName = this.Source };+ }+}++/// <summary>+/// A request to call a function.+/// </summary>+public class FunctionCall+{+ // TODO: Should this be part of the Autogen "Core" (and what does that even mean on the .NET side?)+ // It is unfortuante that we have to duplicate this type, but in order to be compatible with Python, it is necessary for+ // us to be able to process incoming FunctionCalls with parameters in the form of a JSON string. This means that without+ // knowing the target function, and unless the types are specified inline in the JSON, we cannot deserialize them in a+ // generic manner (or we need to have a central registry of function calls, which is undesirable).+ // The solution, for now, is to keep the representation as JSON and provide a helper that binds the JSON to a candidate+ // schema.++ /// <summary>+ /// An identifier representing this specific request. Responses will include this identifier.+ /// </summary>+ public required string Id { get; set; }++ /// <summary>+ /// The arguments to pass to the function in JSON format.+ /// </summary>+ public string? Arguments { get; set; }++ /// <summary>+ /// The name of the function to call.+ /// </summary>+ public required string Name { get; set; }+}++/// <summary>+/// The result of a function call.+/// </summary>+public class FunctionExecutionResult+{+ /// <summary>+ /// The identifier of the request that this result is for.+ /// </summary>+ public required string Id { get; set; }++ /// <summary>+ /// The result of calling the function.+ /// </summary>+ public required string Content { get; set; }+}++/// <summary>+/// An event signaling a request to use tools.+/// </summary>+public class ToolCallRequestEvent : AgentEvent+{+ /// <summary>+ /// The tool calls.+ /// </summary>+ public List<FunctionCall> Content { get; private set; } = new List<FunctionCall>();++ /// <inheritdoc cref="AgentEvent.ToCompletionClientMessage(ChatRole)" />/>+ public override Microsoft.Extensions.AI.ChatMessage ToCompletionClientMessage(ChatRole role)+ {+ Debug.Assert(role == ChatRole.Assistant, "ToolCallMessage can only come from agents in the Assistant Role");+ return new Microsoft.Extensions.AI.ChatMessage(ChatRole.Assistant, (IList<AIContent>)this.Content) { AuthorName = this.Source };+ }+}++/// <summary>+/// An event signaling the execution of tool calls.+/// </summary>+public class ToolCallExecutionEvent : AgentEvent+{+ /// <summary>+ /// The tool call results.+ /// </summary>+ public List<FunctionExecutionResult> Content { get; private set; } = new List<FunctionExecutionResult>();++ /// <inheritdoc cref="AgentEvent.ToCompletionClientMessage(ChatRole)" />/>+ public override Microsoft.Extensions.AI.ChatMessage ToCompletionClientMessage(ChatRole role)+ {+ Debug.Assert(role == ChatRole.Tool, "ToolCallResultMessage can only come from agents in the Tool Role");+ return new Microsoft.Extensions.AI.ChatMessage(ChatRole.Tool, (IList<AIContent>)this.Content) { AuthorName = this.Source };+ }+}++/// <summary>+/// A message summarizing the results of tool calls.+/// </summary>+public class ToolCallSummaryMessage : ChatMessage+{+ /// <summary>+ /// Summary of the tool call results.+ /// </summary>+ public required string Content { get; set; }++ public override Extensions.AI.ChatMessage ToCompletionClientMessage(ChatRole role)+ {+ Debug.Assert(role == ChatRole.Assistant, "ToolCallSummaryMessage can only come from agents in the Assistant Role");+ return new Microsoft.Extensions.AI.ChatMessage(ChatRole.Assistant, this.Content) { AuthorName = this.Source };+ }+}++/// <summary>+/// An event signaling that the user proxy has requested user input. Published prior to invoking the+/// input callback.+/// </summary>+public class UserInputRequestedEvent : AgentEvent+{+ /// <summary>+ /// Identifier for the user input request.+ /// </summary>+ public required string RequestId { get; set; }++ /// <inheritdoc cref="AgentEvent.ToCompletionClientMessage(ChatRole)" />/>+ public override Extensions.AI.ChatMessage ToCompletionClientMessage(ChatRole role)+ {+ throw new Exception("UserInputRequestedEvent should not be sent to the completion client");+ }+}++public static class CompletionChatMessageExtensions+{+ /// <summary>+ /// Flattens a <see cref="Microsoft.Extensions.AI.ChatMessage"/> into a single <see cref="Microsoft.Extensions.AI.ChatMessage"/>+ /// containing all of the content in the original message as a single string.+ /// </summary>+ /// <remarks>+ /// </remarks>+ /// <param name="msg">+ /// The <see cref="Microsoft.Extensions.AI.ChatMessage"/> to flatten.+ /// </param>+ /// <returns>+ /// A new <see cref="Microsoft.Extensions.AI.ChatMessage"/> that is a flattened version of the input.+ /// </returns>+ public static Microsoft.Extensions.AI.ChatMessage Flatten(this Microsoft.Extensions.AI.ChatMessage msg)+ {+ if (msg.Contents.Count == 1 && msg.Contents[0] is TextContent)+ {+ return msg;+ }++ StringBuilder contentBuilder = new StringBuilder();+ foreach (AIContent content in msg.Contents)+ {+ if (content is TextContent textContent)+ {+ contentBuilder.AppendLine(textContent.Text);+ }+ else if (content is ImageContent)+ {+ contentBuilder.AppendLine("[Image]");+ }+ else+ {+ contentBuilder.AppendLine($"[{content.GetType().Name}]");+ }+ }++ return new Microsoft.Extensions.AI.ChatMessage(msg.Role, contentBuilder.ToString())+ {+ AuthorName = msg.AuthorName,+ AdditionalProperties = msg.AdditionalProperties+ };+ }+}diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Tasks.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Tasks.csnew file mode 100644index 000000000..2b4d66d93--- /dev/null+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Tasks.cs@@ -0,0 +1,117 @@+// Copyright (c) Microsoft Corporation. All rights reserved.+// Tasks.cs++namespace Microsoft.AutoGen.AgentChat.Abstractions;++/// <summary>+/// Result of running a task.+/// </summary>+/// <param name="messages">Messages produced by the task.</param>+public struct TaskResult(List<AgentMessage> messages)+{+ /// <summary>+ /// Message produced by the task.+ /// </summary>+ public List<AgentMessage> Messages { get; } = messages;++ /// <summary>+ /// The reason the task stopped.+ /// </summary>+ public string? StopReason = null;+}++/// <summary>+/// The stream frame for <see cref="ITaskRunner.StreamAsync(string, CancellationToken)"/>.+/// </summary>+public class TaskFrame : StreamingFrame<TaskResult>+{+ /// <summary>+ /// Create a new <see cref="TaskFrame"/> with a response.+ /// </summary>+ /// <param name="response">Result of running a task.</param>+ public TaskFrame(TaskResult response)+ {+ this.Response = response;+ this.Type = TaskFrame.FrameType.Response;+ }++ /// <summary>+ /// Create a new <see cref="TaskFrame"/> with an internal message.+ /// </summary>+ /// <param name="message">The internal message.</param>+ public TaskFrame(AgentMessage message)+ {+ this.InternalMessage = message;+ this.Type = TaskFrame.FrameType.InternalMessage;+ }+}++/// <summary>+/// A task runner.+/// </summary>+public interface ITaskRunner+{+ private static ChatMessage ToMessage(string task) => new TextMessage { Content = task, Source = "user" };++ /// <summary>+ /// Run the task and return the result.+ /// </summary>+ /// <param name="task">The task definition in text form.</param>+ /// <param name="cancellationToken"></param>+ /// <returns>The result of running the task.</returns>+ async ValueTask<TaskResult> RunAsync(string task, CancellationToken cancellationToken = default) =>+ await this.RunAsync(ToMessage(task)!, cancellationToken);++ /// <summary>+ /// Run the task and return the result.+ /// </summary>+ /// <remarks>+ /// The runner is stateful and a subsequent call to this method will continue from where the previous+ /// call left off.If the task is not specified,the runner will continue with the current task.+ /// </remarks>+ /// <param name="task">The task definition as a message.</param>+ /// <param name="cancellationToken"></param>+ /// <returns>The result of running the task.</returns>+ /// <exception cref="InvalidOperationException">If no response is generated.</exception>+ async ValueTask<TaskResult> RunAsync(ChatMessage task, CancellationToken cancellationToken = default)+ {+ await foreach (TaskFrame frame in this.StreamAsync(task, cancellationToken))+ {+ if (frame.Type == TaskFrame.FrameType.Response)+ {+ return frame.Response!;+ }+ }++ throw new InvalidOperationException("The stream should have returned the final result.");+ }++ /// <summary>+ /// Run the task and produce a stream of <see cref="TaskFrame"/> and the final <see cref="TaskResult"/>+ /// is the last frame in the stream.+ /// </summary>+ /// <remarks>+ /// The runner is stateful and a subsequent call to this method will continue from where the previous+ /// call left off.If the task is not specified,the runner will continue with the current task.+ /// </remarks>+ /// <param name="task">The task definition as a string.</param>+ /// <param name="cancellationToken"></param>+ /// <returns>A stream of <see cref="TaskFrame"/> containing internal messages and intermediate results followed by+ /// the final <see cref="TaskResult"/></returns>+ IAsyncEnumerable<TaskFrame> StreamAsync(string task, CancellationToken cancellationToken = default) =>+ this.StreamAsync(ToMessage(task), cancellationToken);++ /// <summary>+ /// Run the task and produce a stream of <see cref="TaskFrame"/> and the final <see cref="TaskResult"/>+ /// is the last frame in the stream.+ /// </summary>+ /// <remarks>+ /// The runner is stateful and a subsequent call to this method will continue from where the previous+ /// call left off.If the task is not specified,the runner will continue with the current task.+ /// </remarks>+ /// <param name="task">The task definition as a message.</param>+ /// <param name="cancellationToken"></param>+ /// <returns>A stream of <see cref="TaskFrame"/> containing internal messages and intermediate results followed by+ /// the final <see cref="TaskResult"/></returns>+ IAsyncEnumerable<TaskFrame> StreamAsync(ChatMessage? task, CancellationToken cancellationToken = default);+}diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Termination.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Termination.csnew file mode 100644index 000000000..f5cb00cfe--- /dev/null+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Termination.cs@@ -0,0 +1,204 @@+// Copyright (c) Microsoft Corporation. All rights reserved.+// Termination.cs++namespace Microsoft.AutoGen.AgentChat.Abstractions;++/// <summary>+/// A stateful condition that determines when a conversation should be terminated.+///+/// A termination condition takes a sequences of <see cref="AgentMessage"/> objects since the last time the+/// condition was checked, and returns a <see cref="StopMessage"/> if the conversation should be terminated,+/// or <c>null</c> otherwise.+///+/// Once a termination condition has been reached, it must be <see cref="Reset()"/> before it can be used again.+///+/// Termination conditions can be combined using the <see cref="Or"/> and <see cref="And"/> methods.+/// </summary>+public interface ITerminationCondition+{+ /// <summary>+ /// Checks if the termination condition has been reached+ /// </summary>+ bool IsTerminated { get; }++ /// <summary>+ /// Check if the conversation should be terminated based on the messages received+ /// since the last time the condition was called.+ /// Return a <see cref="StopMessage"/> if the conversation should be terminated, or <c>null</c> otherwise.+ /// </summary>+ /// <param name="messages">The messages received since the last time the condition was called.</param>+ /// <returns>A <see cref="StopMessage"/> if the conversation should be terminated, or <c>null</c>+ /// otherwise.</returns>+ /// <exception cref="TerminatedException">If the termination condition has already been reached.</exception>+ ValueTask<StopMessage?> CheckAndUpdateAsync(IList<AgentMessage> messages);++ /// <summary>+ /// Resets the termination condition.+ /// </summary>+ void Reset();++ /// <summary>+ /// Combine this termination condition with another using a logical OR.+ /// </summary>+ /// <param name="other">Another termination condition.</param>+ /// <returns>The combined termination condition, with appropriate short-circuiting.</returns>+ ITerminationCondition Or(ITerminationCondition other)+ {+ return new CombinerCondition(CombinerCondition.Or, this, other);+ }++ /// <summary>+ /// Combine this termination condition with another using a logical AND.+ /// </summary>+ /// <param name="other">Another termination condition.</param>+ /// <returns>The combined termination condition, with appropriate short-circuiting.</returns>+ ITerminationCondition And(ITerminationCondition other)+ {+ return new CombinerCondition(CombinerCondition.And, this, other);+ }+}++/// <summary>+/// Exception thrown when a termination condition has already been reached.+/// </summary>+public sealed class TerminatedException : Exception+{+ public TerminatedException() : base("The termination condition has already been reached.")+ {+ }+}++/// <summary>+/// A termination condition that combines multiple termination conditions using a logical AND or OR.+/// </summary>+internal sealed class CombinerCondition : ITerminationCondition+{+ public const bool Conjunction = true;+ public const bool Disjunction = false;++ public const bool And = Conjunction;+ public const bool Or = Disjunction;++ private List<StopMessage> stopMessages = new List<StopMessage>();+ private List<ITerminationCondition> clauses;+ private readonly bool conjunction;++ /// <summary>+ /// Create a new <see cref="CombinerCondition"/> with the given conjunction and clauses.+ /// </summary>+ /// <param name="conjunction">The conjunction to use when combining the clauses.</param>+ /// <param name="clauses">The termination conditions to combine.</param>+ public CombinerCondition(bool conjunction, params IEnumerable<ITerminationCondition> clauses)+ {+ // Flatten the list of clauses by unwrapping included CombinerConditions if their+ // conjunctions match (since combiners with associative conjunctions can be hoisted).+ IEnumerable<ITerminationCondition> flattened =+ clauses.SelectMany(c =>+ (c is CombinerCondition combiner && combiner.conjunction == conjunction)+ ? (IEnumerable<ITerminationCondition>)combiner.clauses+ : new[] { c });++ this.conjunction = conjunction;++ this.clauses = flattened.ToList();+ }++ /// <inheritdoc cref="ITerminationCondition.IsTerminated" />+ public bool IsTerminated { get; private set; }++ /// <inheritdoc cref="ITerminationCondition.Reset" />+ public void Reset()+ {+ this.stopMessages.Clear();+ this.clauses.ForEach(c => c.Reset());++ this.IsTerminated = false;+ }++ /// <inheritdoc cref="ITerminationCondition.CheckAndUpdateAsync" />+ public async ValueTask<StopMessage?> CheckAndUpdateAsync(IList<AgentMessage> messages)+ {+ if (this.IsTerminated)+ {+ throw new TerminatedException();+ }++ // When operating as a conjunction, we may be accumulated terminating conditions, but we will not fire until+ // all of them are complete. In this case, we need to avoid continuing to interact with already terminated+ // clauses, because trying to update them will throw+ var candidateTerminations = this.conjunction ? this.clauses.Where(clause => !clause.IsTerminated) : clauses;++ // TODO: Do we really need these to be ValueTasks? (Alternatively: Do we really need to run them explicitly+ // on every invocation, or is a Worker pattern more appropriate?)+ List<Task<StopMessage?>> tasks = candidateTerminations.Select(c => c.CheckAndUpdateAsync(messages).AsTask()).ToList();+ StopMessage?[] results = await Task.WhenAll(tasks);++ bool raiseTermination = this.conjunction; // if or, we start with false until we observe a true+ // if and, we start with true until we observe a false++ foreach (StopMessage? maybeStop in results)+ {+ if (maybeStop != null)+ {+ this.stopMessages.Add(maybeStop);+ if (!this.conjunction)+ {+ // If any clause terminates, the disjunction terminates+ raiseTermination = true;+ }+ }+ else if (this.conjunction)+ {+ // If any clause does not terminate, the conjunction does not terminate+ raiseTermination = false;+ }+ }++ if (raiseTermination)+ {+ this.IsTerminated = true;++ return new StopMessage+ {+ Content = string.Join("; ", stopMessages.Select(sm => sm.Content)),+ Source = string.Join(", ", stopMessages.Select(sm => sm.Source))+ };+ }++ return null;+ }++ /// <inheritdoc cref="ITerminationCondition.Or" />+ /// <remarks>+ /// If this condition is already a disjunction, the new condition is added to the list of clauses.+ /// </remarks>+ ITerminationCondition ITerminationCondition.Or(ITerminationCondition other)+ {+ if (this.conjunction == Or)+ {+ this.clauses.Add(other);+ return this;+ }+ else+ {+ return new CombinerCondition(Or, this, new CombinerCondition(Or, other));+ }+ }++ /// <inheritdoc cref="ITerminationCondition.And" />+ /// <remarks>+ /// If this condition is already a conjunction, the new condition is added to the list of clauses.+ /// </remarks>+ ITerminationCondition ITerminationCondition.And(ITerminationCondition other)+ {+ if (this.conjunction == And)+ {+ this.clauses.Add(other);+ return this;+ }+ else+ {+ return new CombinerCondition(And, this, new CombinerCondition(And, other));+ }+ }+}diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Tools.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Tools.csnew file mode 100644index 000000000..fe10182d1--- /dev/null+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/Abstractions/Tools.cs@@ -0,0 +1,186 @@+// Copyright (c) Microsoft Corporation. All rights reserved.+// Tools.cs++using System.ComponentModel;+using System.Reflection;+using Microsoft.Extensions.AI;++namespace Microsoft.AutoGen.AgentChat.Abstractions;++// TODO: This likely should live as a "Component" in an Agent-building ClassLib?+// It seems like it could have applicability beyond AgentChat.++public static class ReflectionExtensions+{+ public static AIFunctionParameterMetadata ToAIFunctionMetadata(this ParameterInfo pi)+ {+ return new AIFunctionParameterMetadata(pi.Name!)+ {+ Description = pi.GetCustomAttribute<DescriptionAttribute>()?.Description,++ ParameterType = pi.ParameterType,++ HasDefaultValue = pi.HasDefaultValue,+ IsRequired = !pi.HasDefaultValue,+ DefaultValue = pi.DefaultValue,++ // Schema = JSONSchema of type+ };+ }++ public static AIFunctionReturnParameterMetadata ToAIFunctionReturnMetadata(this ParameterInfo rpi)+ {+ return new AIFunctionReturnParameterMetadata+ {+ Description = rpi.GetCustomAttribute<DescriptionAttribute>()?.Description,++ ParameterType = rpi.ParameterType++ //Schema = JSONSchema of type+ };+ }+}++public class ParameterSchema(string name, Type type, bool isRequired = false, object? defaultValue = default)+{+ public string Name { get; } = name;+ public Type Type { get; } = type;+ public bool IsRequired { get; } = isRequired;++ public object? DefaultValue { get; } = defaultValue;++ public static implicit operator ParameterSchema(ParameterInfo parameterInfo)+ {+ Type parameterType = parameterInfo.ParameterType;+ return ParameterSchema<object>.Create(parameterType, parameterInfo.Name!, parameterInfo.HasDefaultValue, parameterInfo.DefaultValue);+ }++ public static implicit operator ParameterSchema(AIFunctionParameterMetadata parameterMetadata)+ {+ Type parameterType = parameterMetadata.ParameterType!; // TODO: Deal with missing ParameterTypes+ return ParameterSchema<object>.Create(parameterType,+ parameterMetadata.Name,+ parameterMetadata.IsRequired,+ parameterMetadata.DefaultValue);+ }+}++// TODO: Can this be obviated by AIFunctionParameter?+public class ParameterSchema<T>(string name, bool isRequired = false, T? defaultValue = default)+ : ParameterSchema(name, typeof(T), isRequired, defaultValue)+{+ public static ParameterSchema Create(Type type, string name, bool isRequired = false, object? defaultValue = default)+ {+ Type parameterSchemaType = typeof(ParameterSchema<>).MakeGenericType(type);+ ParameterSchema? maybeResult = Activator.CreateInstance(parameterSchemaType, name, isRequired, defaultValue) as ParameterSchema;+ return maybeResult!;+ }+}++/// <summary>+/// A tool that can be executed by agents.+/// </summary>+public interface ITool+{+ string Name { get; }+ string Description { get; }++ public IEnumerable<ParameterSchema> Parameters { get; }+ public Type ReturnType { get; }++ // TODO: State serialization++ // TODO: Can we somehow make this a ValueTask?+ public Task<object> ExecuteAsync(IEnumerable<object> parameters, CancellationToken cancellationToken = default);++ /// <summary>+ /// This tool represented as an <see cref="AIFunction"/>.+ /// </summary>+ public AIFunction AIFunction+ {+ get+ {+ return CallableTool.CreateAIFunction(this.Name, this.Description, this.ExecuteAsync);+ }+ }+}++public static class TypeExtensions+{+ private static ISet<Type> TaskTypes = new HashSet<Type>([typeof(Task<>), typeof(ValueTask<>)]);++ public static Type UnwrapReturnIfAsync(this Type type)+ {+ if (type.IsGenericType && TaskTypes.Contains(type.GetGenericTypeDefinition()))+ {+ return type.GetGenericArguments()[0];+ }+ else if (type == typeof(Task) || type == typeof(ValueTask))+ {+ return typeof(void);+ }+ else+ {+ return type;+ }+ }+}++/// <summary>+/// Projects a <see cref="AIFunction"/> as an <see cref="ITool"/>.+/// </summary>+/// <param name="aiFunction">The <see cref="AIFunction"/> to wrap.</param>+public class AIFunctionTool(AIFunction aiFunction) : ITool+{+ /// <inheritdoc cref="ITool.AIFunction" />+ public AIFunction AIFunction { get; } = aiFunction;++ /// <inheritdoc cref="ITool.Name" />+ public string Name => this.AIFunction.Metadata.Name;++ /// <inheritdoc cref="ITool.Description" />+ public string Description => this.AIFunction.Metadata.Description;++ /// <inheritdoc cref="ITool.Parameters" />+ public IEnumerable<ParameterSchema> Parameters => from rawParameter in this.AIFunction.Metadata.Parameters+ select (ParameterSchema)rawParameter;++ /// <inheritdoc cref="ITool.ReturnType" />+ public Type ReturnType => this.AIFunction.Metadata.ReturnParameter.ParameterType!; // TODO: Deal with missing return types++ /// <inheritdoc cref="ITool.ExecuteAsync" />+ public Task<object> ExecuteAsync(IEnumerable<object> parameters, CancellationToken cancellationToken = default)+ => this.ExecuteAsync(parameters, cancellationToken);+}++/// <summary>+/// Projects a <c>delegate</c> as a <see cref="ITool"/> by wrapping it in <see cref="AIFunction"/>.+/// </summary>+/// <param name="name">The name of the tool.</param>+/// <param name="description">The description of the tool.</param>+/// <param name="callable">The <c>delegate</c> to wrap.</param>+public class CallableTool(string name, string description, Delegate callable)+ : AIFunctionTool(CreateAIFunction(name, description, callable))+{+ internal static AIFunction CreateAIFunction(string name, string description, Delegate callable)+ {+ MethodInfo methodInfo = callable.Method;++ IEnumerable<AIFunctionParameterMetadata> parameters =+ from parameterInfo in methodInfo.GetParameters()+ select parameterInfo.ToAIFunctionMetadata();++ AIFunctionReturnParameterMetadata returnParameter = methodInfo.ReturnParameter.ToAIFunctionReturnMetadata();++ AIFunctionFactoryCreateOptions createOptions = new()+ {+ Name = name,+ Description = description,+ Parameters = parameters.ToList(),+ ReturnParameter = returnParameter,+ // SerializerOptions = TODO: How do we maintain consistency with Python?+ };++ return AIFunctionFactory.Create(callable, createOptions);+ }+}diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/Agents/ChatAgentBase.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/Agents/ChatAgentBase.csnew file mode 100644index 000000000..1ddffad4a--- /dev/null+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/Agents/ChatAgentBase.cs@@ -0,0 +1,50 @@+// Copyright (c) Microsoft Corporation. All rights reserved.+// ChatAgentBase.cs++using System.Runtime.CompilerServices;+using Microsoft.AutoGen.AgentChat.Abstractions;++namespace Microsoft.AutoGen.AgentChat.Agents;++/// <summary>+/// Base class for a chat agent.+/// </summary>+public abstract class ChatAgentBase : IChatAgent+{+ public ChatAgentBase(string name, string description)+ {+ Name = new AgentName(name);+ Description = description;+ }++ /// <inheritdoc cref="IChatAgent.Name"/>+ public AgentName Name { get; }++ /// <inheritdoc cref="IChatAgent.Description"/>+ public string Description { get; }++ /// <inheritdoc cref="IHandleStream{TIn, TOut}.StreamAsync(TIn, CancellationToken)"/>+ public virtual async IAsyncEnumerable<ChatStreamFrame> StreamAsync(IEnumerable<ChatMessage> item, [EnumeratorCancellation] CancellationToken cancellationToken)+ {+ Response response = await (this).HandleAsync(item, cancellationToken);+ if (response.InnerMessages != null)+ {+ foreach (var message in response.InnerMessages)+ {+ // It would be really nice to have type unions in .NET; need to think about how to make this interface nicer.+ yield return new ChatStreamFrame { Type = ChatStreamFrame.FrameType.InternalMessage, InternalMessage = message };+ }+ }++ yield return new ChatStreamFrame { Type = ChatStreamFrame.FrameType.Response, Response = response };+ }++ /// <inheritdoc cref="IChatAgent.ProducedMessageTypes"/>+ public abstract IEnumerable<Type> ProducedMessageTypes { get; }++ /// <inheritdoc cref="IHandleChat{TIn, TOut}.HandleAsync(TIn, CancellationToken)"/>+ public abstract ValueTask<Response> HandleAsync(IEnumerable<ChatMessage> item, CancellationToken cancellationToken);++ /// <inheritdoc cref="IChatAgent.ResetAsync(CancellationToken)"/>+ public abstract ValueTask ResetAsync(CancellationToken cancellationToken);+}diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/ChatAgentRouter.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/ChatAgentRouter.csnew file mode 100644index 000000000..a195cd4d6--- /dev/null+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/ChatAgentRouter.cs@@ -0,0 +1,98 @@+// Copyright (c) Microsoft Corporation. All rights reserved.+// ChatAgentRouter.cs++using Microsoft.AutoGen.AgentChat.Abstractions;+using Microsoft.AutoGen.Contracts;+using Microsoft.AutoGen.Core;+using Microsoft.Extensions.Logging;++namespace Microsoft.AutoGen.AgentChat.GroupChat;++public struct AgentChatConfig(IChatAgent chatAgent, string parentTopicType, string outputTopicType)+{+ public string ParticipantTopicType => this.Name;+ public string ParentTopicType { get; } = parentTopicType;+ public string OutputTopicType { get; } = outputTopicType;++ public IChatAgent ChatAgent { get; } = chatAgent;++ public string Name => this.ChatAgent.Name;+ public string Description => this.ChatAgent.Description;+}++internal sealed class ChatAgentRouter : HostableAgentAdapter,+ IHandle<GroupChatStart>,+ IHandle<GroupChatAgentResponse>,+ IHandle<GroupChatRequestPublish>,+ IHandle<GroupChatReset>+{+ private readonly TopicId parentTopic;+ private readonly TopicId outputTopic;+ private readonly IChatAgent agent;++ public ChatAgentRouter(AgentInstantiationContext agentCtx, AgentChatConfig config, ILogger<BaseAgent>? logger = null) : base(agentCtx, config.Description, logger)+ {+ this.parentTopic = new TopicId(config.ParentTopicType, this.Id.Key);+ this.outputTopic = new TopicId(config.OutputTopicType, this.Id.Key);++ this.agent = config.ChatAgent;+ }++ public List<ChatMessage> MessageBuffer { get; private set; } = new();++ public ValueTask HandleAsync(GroupChatStart item, MessageContext messageContext)+ {+ if (item.Messages != null)+ {+ this.MessageBuffer.AddRange(item.Messages);+ }++ return ValueTask.CompletedTask;+ }++ public ValueTask HandleAsync(GroupChatAgentResponse item, MessageContext messageContext)+ {+ this.MessageBuffer.Add(item.AgentResponse.Message);++ return ValueTask.CompletedTask;+ }++ public async ValueTask HandleAsync(GroupChatRequestPublish item, MessageContext messageContext)+ {+ Response? response = null;++ // TODO: Is there a better abstraction here than IAsyncEnumerable? Though the akwardness mainly comes from+ // the lack of real type unions in C#, which is why we need to create the StreamingFrame type in the first+ // place.+ await foreach (ChatStreamFrame frame in this.agent.StreamAsync(this.MessageBuffer, messageContext.CancellationToken))+ {+ // TODO: call publish message+ switch (frame.Type)+ {+ case ChatStreamFrame.FrameType.Response:+ await this.PublishMessageAsync(new GroupChatMessage { Message = frame.Response!.Message }, this.outputTopic);+ response = frame.Response;+ break;+ case ChatStreamFrame.FrameType.InternalMessage:+ await this.PublishMessageAsync(new GroupChatMessage { Message = frame.InternalMessage! }, this.outputTopic);+ break;+ }+ }++ if (response == null)+ {+ throw new InvalidOperationException("The agent did not produce a final response. Check the agent's on_messages_stream method.");+ }++ this.MessageBuffer.Clear();++ await this.PublishMessageAsync(new GroupChatAgentResponse { AgentResponse = response }, this.parentTopic);+ }++ public ValueTask HandleAsync(GroupChatReset item, MessageContext messageContext)+ {+ this.MessageBuffer.Clear();+ return this.agent.ResetAsync(messageContext.CancellationToken);+ }+}+diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/Events.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/Events.csnew file mode 100644index 000000000..8eb88ddb3--- /dev/null+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/Events.cs@@ -0,0 +1,84 @@+// Copyright (c) Microsoft Corporation. All rights reserved.+// Events.cs++using Microsoft.AutoGen.AgentChat.Abstractions;++// using ProtobufTypeMarshal = Microsoft.AutoGen.AgentChat.WireProtocol.ProtobufTypeMarshal;++namespace Microsoft.AutoGen.AgentChat.GroupChat;++public class GroupChatEventBase /*: IWireable*/+{+ // public IMessage ToWire()+ // {+ // return this switch+ // {+ // GroupChatStart groupChatStart => ProtobufTypeMarshal.Convert<GroupChatStart, WireProtocol.GroupChatStart>(groupChatStart),+ // GroupChatAgentResponse groupChatAgentResponse => ProtobufTypeMarshal.Convert<GroupChatAgentResponse, WireProtocol.GroupChatResponse>(groupChatAgentResponse),+ // GroupChatRequestPublish groupChatRequestPublish => ProtobufTypeMarshal.Convert<GroupChatRequestPublish, WireProtocol.GroupChatRequestPublish>(groupChatRequestPublish),+ // GroupChatMessage groupChatMessage => ProtobufTypeMarshal.Convert<GroupChatMessage, WireProtocol.GroupChatMessage>(groupChatMessage),+ // GroupChatTermination groupChatTermination => ProtobufTypeMarshal.Convert<GroupChatTermination, WireProtocol.GroupChatTermination>(groupChatTermination),+ // GroupChatReset groupChatReset => ProtobufTypeMarshal.Convert<GroupChatReset, WireProtocol.GroupChatReset>(groupChatReset),+ // _ => throw new InvalidOperationException($"Unknown type {this.GetType().Name}"),+ // };+ // }+}++/// <summary>+/// A request to start a group chat.+/// </summary>+public class GroupChatStart : GroupChatEventBase+{+ /// <summary>+ /// An optional list of messages to start the group chat.+ /// </summary>+ public List<ChatMessage>? Messages { get; set; }+}++/// <summary>+/// A response published to a group chat.+/// </summary>+public class GroupChatAgentResponse : GroupChatEventBase+{+ /// <summary>+ /// The response from a agent.+ /// </summary>+ public required Response AgentResponse { get; set; }+}++/// <summary>+/// A request to publish a message to a group chat.+/// </summary>+public class GroupChatRequestPublish : GroupChatEventBase+{+}++/// <summary>+/// A message from a group chat.+/// </summary>+public class GroupChatMessage : GroupChatEventBase+{+ /// <summary>+ /// The message that was published.+ /// </summary>+ public required AgentMessage Message { get; set; }+}++/// <summary>+/// A message indicating that group chat was terminated.+/// </summary>+public class GroupChatTermination : GroupChatEventBase+{+ /// <summary>+ /// The stop message that indicates the reason of termination.+ /// </summary>+ public required StopMessage Message { get; set; }+}++/// <summary>+/// A request to reset the agents in the group chat.+/// </summary>+public class GroupChatReset : GroupChatEventBase+{+}+diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatBase.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatBase.csnew file mode 100644index 000000000..5192cac6d--- /dev/null+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatBase.cs@@ -0,0 +1,235 @@+// Copyright (c) Microsoft Corporation. All rights reserved.+// GroupChatBase.cs++using System.Diagnostics;+using System.Reflection;+using System.Runtime.CompilerServices;+using Microsoft.AutoGen.AgentChat.Abstractions;+using Microsoft.AutoGen.Contracts;+using Microsoft.AutoGen.Core;++namespace Microsoft.AutoGen.AgentChat.GroupChat;++internal static class AgentsRuntimeExtensions+{+ public static async ValueTask<AgentType> RegisterChatAgentAsync(this IAgentRuntime runtime, AgentChatConfig config)+ {+ AgentType type = config.Name;++ AgentType resultType = await runtime.RegisterAgentFactoryAsync(type,+ (id, runtime) =>+ {+ AgentInstantiationContext agentContext = new AgentInstantiationContext(id, runtime);+ return ValueTask.FromResult<IHostableAgent>(new ChatAgentRouter(agentContext, config));+ });++ await runtime.AddSubscriptionAsync(new TypeSubscription(config.ParticipantTopicType, type));+ await runtime.AddSubscriptionAsync(new TypeSubscription(config.ParentTopicType, type));++ return resultType;+ }++ public static async ValueTask<AgentType> RegisterGroupChatManagerAsync<TManager>(this IAgentRuntime runtime, GroupChatOptions options, string teamId, Func<GroupChatOptions, TManager> factory)+ where TManager : GroupChatManagerBase+ {+ AgentType type = GroupChatBase<TManager>.GroupChatManagerTopicType;+ AgentId expectedId = new AgentId(type, teamId);++ AgentType resultType = await runtime.RegisterAgentFactoryAsync(type,+ (id, runtime) =>+ {+ Debug.Assert(expectedId == id, $"Expecting the AgentId {expectedId} to be the teamId {id}");++ AgentInstantiationContext agentContext = new AgentInstantiationContext(id, runtime);+ TManager gcm = factory(options); // TODO: Should we allow this to be async?++ return ValueTask.FromResult<IHostableAgent>(new GroupChatHandlerRouter<TManager>(agentContext, gcm));+ });++ await runtime.AddSubscriptionAsync(new TypeSubscription(GroupChatBase<TManager>.GroupChatManagerTopicType, resultType));+ await runtime.AddSubscriptionAsync(new TypeSubscription(options.GroupChatTopicType, resultType));++ return resultType;+ }++ public static async ValueTask<AgentType> RegisterOutputCollectorAsync(this IAgentRuntime runtime, IOutputCollectionSink sink, string outputTopicType)+ {+ AgentType type = GroupChatBase<GroupChatManagerBase>.CollectorAgentType;+ AgentType resultType = await runtime.RegisterAgentFactoryAsync(type,+ (id, runtime) =>+ {+ AgentInstantiationContext agentContext = new AgentInstantiationContext(id, runtime);+ return ValueTask.FromResult<IHostableAgent>(new OutputCollectorAgent(agentContext, sink));+ });++ await runtime.AddSubscriptionAsync(new TypeSubscription(outputTopicType, type));++ return resultType;+ }+}++public abstract class GroupChatBase<TManager> : ITeam where TManager : GroupChatManagerBase+{+ // TODO: Where do these come from?+ internal const string GroupTopicType = "group_topic";+ internal const string OutputTopicType = "output_topic";+ internal const string GroupChatManagerTopicType = "group_chat_manager";+ internal const string CollectorAgentType = "collect_output_messages";++ private GroupChatOptions GroupChatOptions { get; }++ private readonly List<AgentMessage> messageThread = new();+ private Dictionary<string, AgentChatConfig> Participants { get; } = new();++ protected GroupChatBase(List<IChatAgent> participants, ITerminationCondition? terminationCondition = null, int? maxTurns = null)+ {+ this.GroupChatOptions = new GroupChatOptions(GroupTopicType, OutputTopicType)+ {+ TerminationCondition = terminationCondition,+ MaxTurns = maxTurns,+ };++ foreach (var participant in participants)+ {+ AgentChatConfig config = new AgentChatConfig(participant, GroupTopicType, OutputTopicType);+ this.Participants[participant.Name] = config;+ this.GroupChatOptions.Participants[participant.Name] = new GroupParticipant(config.ParticipantTopicType, participant.Description);+ }++ this.messageThread = new List<AgentMessage>(); // TODO: Allow injecting this++ this.TeamId = Guid.NewGuid().ToString().ToLowerInvariant();+ }++ public string TeamId+ {+ get;+ private set;+ }++ public virtual TManager CreateChatManager(GroupChatOptions options)+ {+ try+ {+ if (Activator.CreateInstance(typeof(TManager), options) is TManager result)+ {+ return result;+ };+ }+ catch (TargetInvocationException tie)+ {+ throw new Exception("Could not create chat manager", tie.InnerException);+ }+ catch (Exception ex)+ {+ throw new Exception("Could not create chat manager", ex);+ }++ throw new Exception("Could not create chat manager; make sure that it contains a ctor() or ctor(GroupChatOptions), or override the CreateChatManager method");+ }++ // TODO: Turn this into an IDisposable-based utility+ private int running; // = 0+ private bool EnsureSingleRun()+ {+ return Interlocked.CompareExchange(ref running, 1, 0) == 0;+ }++ private void EndRun()+ {+ this.running = 0;+ }++ public IAsyncEnumerable<TaskFrame> StreamAsync(string task, CancellationToken cancellationToken)+ {+ if (String.IsNullOrEmpty(task))+ {+ throw new ArgumentNullException(nameof(task));+ }++ // TODO: Send this on+ TextMessage taskStart = new()+ {+ Content = task,+ Source = "user"+ };++ return this.StreamAsync(taskStart, cancellationToken);+ }++ public ValueTask ResetAsync(CancellationToken cancel)+ {+ return ValueTask.CompletedTask;+ }++ public async IAsyncEnumerable<TaskFrame> StreamAsync(ChatMessage? task, [EnumeratorCancellation] CancellationToken cancellationToken = default)+ {+ if (task == null)+ {+ throw new ArgumentNullException(nameof(task));+ }++ if (!this.EnsureSingleRun())+ {+ throw new InvalidOperationException("The task is already running.");+ }++ // TODO: How do we allow the user to configure this?+ //AgentsAppBuilder builder = new AgentsAppBuilder().UseInProcessRuntime();+ InProcessRuntime runtime = new InProcessRuntime();++ foreach (AgentChatConfig config in this.Participants.Values)+ {+ await runtime.RegisterChatAgentAsync(config);+ }++ await runtime.RegisterGroupChatManagerAsync(this.GroupChatOptions, this.TeamId, this.CreateChatManager);++ OutputSink outputSink = new OutputSink();+ await runtime.RegisterOutputCollectorAsync(outputSink, this.GroupChatOptions.OutputTopicType);++ await runtime.StartAsync();++ Task shutdownTask = Task.CompletedTask;++ try+ {+ // TODO: Protos+ GroupChatStart taskMessage = new GroupChatStart+ {+ Messages = [task]+ };++ List<AgentMessage> runMessages = new();++ AgentId chatManagerId = new AgentId(GroupChatManagerTopicType, this.TeamId);+ await runtime.SendMessageAsync(taskMessage, chatManagerId, cancellationToken: cancellationToken);++ shutdownTask = Task.Run(runtime.RunUntilIdleAsync);++ while (true)+ {+ OutputSink.SinkFrame frame = await outputSink.WaitForDataAsync(cancellationToken);+ runMessages.AddRange(frame.Messages);++ foreach (AgentMessage message in frame.Messages)+ {+ yield return new TaskFrame(message);+ }++ if (frame.IsTerminal)+ {+ TaskResult result = new TaskResult(runMessages);+ yield return new TaskFrame(result);+ break;+ }+ }+ }+ finally+ {+ this.EndRun();++ await shutdownTask;+ }+ }+}diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatHandlerRouter.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatHandlerRouter.csnew file mode 100644index 000000000..9855dcafb--- /dev/null+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatHandlerRouter.cs@@ -0,0 +1,48 @@+// Copyright (c) Microsoft Corporation. All rights reserved.+// GroupChatHandlerRouter.cs++using Microsoft.AutoGen.Contracts;+using Microsoft.AutoGen.Core;+using Microsoft.Extensions.Logging;++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>+{+ void AttachMessagePublishServicer(MessagePublishServicer? servicer = null);+ void DetachMessagePublishServicer() => this.AttachMessagePublishServicer(null);+}++internal sealed class GroupChatHandlerRouter<TManager> : HostableAgentAdapter,+ IHandle<GroupChatStart>,+ IHandle<GroupChatAgentResponse>,+ IHandle<object>++ where TManager : GroupChatManagerBase, IGroupChatHandler+{+ public const string DefaultDescription = "Group chat manager";++ private TManager ChatManager { get; }++ public GroupChatHandlerRouter(AgentInstantiationContext agentCtx, TManager chatManager, ILogger<BaseAgent>? logger = null) : base(agentCtx, DefaultDescription, logger)+ {+ this.ChatManager = chatManager;+ this.ChatManager.AttachMessagePublishServicer(PublishMessageServicer);+ }++ private ValueTask PublishMessageServicer(GroupChatEventBase event_, string topicType, CancellationToken cancellation = default)+ {+ return this.PublishMessageAsync(event_, new TopicId(topicType, this.Id.Key), cancellationToken: cancellation);+ }++ public ValueTask HandleAsync(GroupChatStart item, MessageContext messageContext)+ => this.ChatManager.HandleAsync(item, messageContext);++ public ValueTask HandleAsync(GroupChatAgentResponse item, MessageContext messageContext)+ => this.ChatManager.HandleAsync(item, messageContext);++ public ValueTask HandleAsync(object item, MessageContext messageContext)+ => this.ChatManager.HandleAsync(item, messageContext);+}diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatManagerBase.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatManagerBase.csnew file mode 100644index 000000000..69c57e344--- /dev/null+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatManagerBase.cs@@ -0,0 +1,187 @@+// Copyright (c) Microsoft Corporation. All rights reserved.+// GroupChatManagerBase.cs++using Microsoft.AutoGen.AgentChat.Abstractions;+using Microsoft.AutoGen.Contracts;++namespace Microsoft.AutoGen.AgentChat.GroupChat;++public abstract class GroupChatManagerBase : IGroupChatHandler+{+ private GroupChatOptions options;++ // TODO: We may be able to abstract this out at the Core level+ private MessagePublishServicer? PublishServicer { get; set; }++ // It would be so awesome if we could avoid passing GroupChatOptions to the constructor+ // and use something like Python's context manager mechanism to pick up the options from+ // the logical stack. But that's very difficult in C#, because the user code could do all+ // sorts of weird things like shunt the execution to a different thread. We cannot even+ // assume that we are in an async context (much less that we are in the same async context)+ public GroupChatManagerBase(GroupChatOptions options) : base()+ {+ this.options = options;++ this.MessageThread = new List<AgentMessage>();+ }++ protected string GroupChatTopicType => this.options.GroupChatTopicType;+ protected string OutputTopicType => this.options.OutputTopicType;++ protected Dictionary<string, GroupParticipant> Participants => this.options.Participants;++ protected ITerminationCondition? TerminationCondition => this.options.TerminationCondition;+ protected int? MaxTurns => this.options.MaxTurns;++ private int CurrentTurn { get; set; }++ protected List<AgentMessage> MessageThread;++ void IGroupChatHandler.AttachMessagePublishServicer(MessagePublishServicer? servicer)+ {+ this.PublishServicer = servicer;+ }++ private ValueTask PublishMessageAsync(GroupChatEventBase message, string topicType, CancellationToken cancellation = default)+ {+ return this.PublishServicer?.Invoke(message, topicType, cancellation) ?? ValueTask.CompletedTask;+ }++ protected ValueTask PublishMessageAsync(ChatMessage message, string topicType, CancellationToken cancellation = default)+ {+ return this.PublishMessageAsync(new GroupChatMessage { Message = message }, topicType, cancellation);+ }++ protected virtual async ValueTask ValidateGroupState(List<ChatMessage>? messages)+ {+ }++ public abstract ValueTask<string> SelectSpeakerAsync(List<AgentMessage> thread);++ public async ValueTask HandleAsync(GroupChatStart item, MessageContext messageContext)+ {+ if (this.TerminationCondition != null && this.TerminationCondition.IsTerminated)+ {+ // skipReset is used here to match the Python code+ await this.TerminateAsync("The chat has already terminated", skipReset: true);++ StopMessage earlyStop = new StopMessage+ {+ Content = "The chat has already terminated",+ Source = GroupChatBase<GroupChatManagerBase>.GroupChatManagerTopicType+ };++ await this.PublishMessageAsync(new GroupChatTermination { Message = earlyStop }, this.OutputTopicType);++ return;+ }++ if (item.Messages != null)+ {+ this.MessageThread.AddRange(item.Messages);+ }++ await this.ValidateGroupState(item.Messages);++ if (item.Messages != null)+ {+ await this.PublishMessageAsync(item, this.OutputTopicType);+ await this.PublishMessageAsync(item, this.GroupChatTopicType);++ // item.Messages is IList<ChatMessage> but we need IList<AgentMessage>+ // Unfortunately, IList does not support type variance, so we have to do this rather ugly thing+ // TODO: Check if we really need to have AgentMessage on the interface of ITerminationCondition+ List<AgentMessage> converted = [.. item.Messages.Cast<AgentMessage>()];++ if (await this.TerminateIfNeededAsync(converted))+ {+ return;+ }+ }++ await this.ProcessNextSpeakerAsync();+ }++ public async ValueTask HandleAsync(GroupChatAgentResponse item, MessageContext messageContext)+ {+ List<AgentMessage> delta = new List<AgentMessage>();++ if (item.AgentResponse.InnerMessages != null)+ {+ this.MessageThread.AddRange(item.AgentResponse.InnerMessages);+ delta.AddRange(item.AgentResponse.InnerMessages);+ }++ this.MessageThread.Add(item.AgentResponse.Message);+ delta.Add(item.AgentResponse.Message);++ if (await this.TerminateIfNeededAsync(delta))+ {+ return;+ }++ this.CurrentTurn++;+ if (this.MaxTurns.HasValue && this.MaxTurns.Value <= this.CurrentTurn)+ {+ await this.TerminateAsync($"Maximum number of turns ({this.MaxTurns.Value}) reached.");+ return;+ }++ await this.ProcessNextSpeakerAsync();+ }++ private ValueTask TerminateAsync(string message, bool skipReset = false)+ {+ StopMessage stopMessage = new StopMessage+ {+ Content = message,+ Source = GroupChatBase<GroupChatManagerBase>.GroupChatManagerTopicType+ };++ return this.TerminateAsync(stopMessage, skipReset);+ }++ private async ValueTask TerminateAsync(StopMessage stopMessage, bool skipReset = false)+ {+ await this.PublishMessageAsync(new GroupChatTermination { Message = stopMessage }, this.OutputTopicType);++ if (!skipReset)+ {+ this.TerminationCondition?.Reset();+ this.CurrentTurn = 0;+ }+ }++ private async ValueTask<bool> TerminateIfNeededAsync(params IList<AgentMessage> incomingMessages)+ {+ if (this.TerminationCondition == null)+ {+ return false;+ }++ StopMessage? stopMessage = await this.TerminationCondition.CheckAndUpdateAsync(incomingMessages);+ if (stopMessage != null)+ {+ await this.TerminateAsync(stopMessage);++ return true;+ }++ return false;+ }++ // TODO: Figure out how to route this to the right method+ //private ValueTask ProcessNextSpeakerAsync(params IList<AgentMessage> incomingMessages)+ // => this.ProcessNextSpeakerAsync(incomingMessages);++ private async ValueTask ProcessNextSpeakerAsync()+ {+ string nextSpeakerTopic = await this.SelectSpeakerAsync(this.MessageThread);+ await this.PublishMessageAsync(new GroupChatRequestPublish { }, nextSpeakerTopic);+ }++ public ValueTask HandleAsync(object item, MessageContext messageContext)+ {+ throw new InvalidOperationException($"Unhandled message in group chat manager: {item.GetType()}");+ }+}diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatOptions.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatOptions.csnew file mode 100644index 000000000..e0907e523--- /dev/null+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/GroupChatOptions.cs@@ -0,0 +1,38 @@+// Copyright (c) Microsoft Corporation. All rights reserved.+// GroupChatOptions.cs++using Microsoft.AutoGen.AgentChat.Abstractions;++namespace Microsoft.AutoGen.AgentChat.GroupChat;++public struct GroupParticipant(string topicType, string description)+{+ public string TopicType { get; } = topicType;+ public string Description { get; } = description;++ // Destructuring from a tuple+ public GroupParticipant((string topicType, string description) tuple) : this(tuple.topicType, tuple.description)+ {+ }++ // Destructuring to a tuple+ public void Deconstruct(out string topicType, out string description)+ {+ topicType = this.TopicType;+ description = this.Description;+ }++ public static implicit operator GroupParticipant((string topicType, string description) tuple) => new GroupParticipant(tuple);+ public static implicit operator (string topicType, string description)(GroupParticipant participant) => (participant.TopicType, participant.Description);+}++public class GroupChatOptions(string groupTopicType, string outputTopicType)+{+ public string GroupChatTopicType { get; } = groupTopicType;+ public string OutputTopicType { get; } = outputTopicType;++ public ITerminationCondition? TerminationCondition { get; set; }+ public int? MaxTurns { get; set; }++ public Dictionary<string, GroupParticipant> Participants { get; } = new Dictionary<string, GroupParticipant>();+}diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/HostableAgentAdapter.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/HostableAgentAdapter.csnew file mode 100644index 000000000..86f20607c--- /dev/null+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/HostableAgentAdapter.cs@@ -0,0 +1,26 @@+// Copyright (c) Microsoft Corporation. All rights reserved.+// HostableAgentAdapter.cs++using Microsoft.AutoGen.Contracts;+using Microsoft.AutoGen.Core;+using Microsoft.Extensions.Logging;++namespace Microsoft.AutoGen.AgentChat.GroupChat;++public class AgentInstantiationContext(AgentId id, IAgentRuntime runtime)+{+ public AgentId Id { get; } = id;+ public IAgentRuntime Runtime { get; } = runtime;+}++internal class HostableAgentAdapter : BaseAgent+{+ public HostableAgentAdapter(AgentId id, IAgentRuntime runtime, string description, ILogger<BaseAgent>? logger = null) : base(id, runtime, description, logger)+ {+ }++ public HostableAgentAdapter(AgentInstantiationContext agentCtx, string description, ILogger<BaseAgent>? logger = null) : base(agentCtx.Id, agentCtx.Runtime, description, logger)+ {+ }+}+diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/OutputCollectorAgent.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/OutputCollectorAgent.csnew file mode 100644index 000000000..d17fa266b--- /dev/null+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/OutputCollectorAgent.cs@@ -0,0 +1,133 @@+// Copyright (c) Microsoft Corporation. All rights reserved.+// OutputCollectorAgent.cs++using System.Diagnostics;+using Microsoft.AutoGen.AgentChat.GroupChat;+using Microsoft.AutoGen.Contracts;+using Microsoft.AutoGen.Core;+using Microsoft.Extensions.Logging;++namespace Microsoft.AutoGen.AgentChat.Abstractions;++internal interface IOutputCollectionSink+{+ void CollectMessage(AgentMessage message);+ void Terminate(StopMessage message);+}++internal sealed class OutputSink : IOutputCollectionSink+{+ public sealed class SinkFrame+ {+ public StopMessage? Termination { get; set; }+ public List<AgentMessage> Messages { get; } = new();++ public bool IsTerminal => this.Termination != null;+ }++ private readonly object sync = new();+ private SemaphoreSlim semapohre = new SemaphoreSlim(1, 1);++ private SinkFrame? receivingSinkFrame;++ private void RunSynchronized(Action<SinkFrame> frameAction)+ {+ // Make sure we do not overlap with Terminate+ lock (this.sync)+ {+ if (this.receivingSinkFrame == null)+ {+ this.receivingSinkFrame = new SinkFrame();+ }++ frameAction(this.receivingSinkFrame);+ }++ semapohre.Release();+ }++ public void CollectMessage(AgentMessage message)+ {+ this.RunSynchronized(+ frame =>+ {+ frame.Messages.Add(message);+ });+ }++ public void Terminate(StopMessage message)+ {+ this.RunSynchronized(+ frame =>+ {+ frame.Termination = message;+ });+ }++ public async Task<SinkFrame> WaitForDataAsync(CancellationToken cancellation)+ {+ while (true)+ {+ SinkFrame? lastFrame;+ lock (this.sync)+ {+ lastFrame = Interlocked.Exchange(ref this.receivingSinkFrame, null);++ if (lastFrame != null)+ {+ return lastFrame;+ }+ }++ await this.semapohre.WaitAsync(cancellation);+ }+ }+}++// TODO: Abstract the core logic of this out into the equivalent of ClosureAgent, because that seems like a+// useful facility to have in Core+internal sealed class OutputCollectorAgent : BaseAgent,+ IHandle<GroupChatStart>,+ IHandle<GroupChatMessage>,+ IHandle<GroupChatTermination>+{+ private IOutputCollectionSink Sink { get; }++ public OutputCollectorAgent(AgentInstantiationContext ctx, IOutputCollectionSink sink, ILogger<OutputCollectorAgent>? logger = null) : base(ctx.Id, ctx.Runtime, string.Empty, logger)+ {+ this.Sink = sink;+ }++ private void ForwardMessageInternal(ChatMessage message, CancellationToken cancel = default)+ {+ if (!cancel.IsCancellationRequested)+ {+ this.Sink.CollectMessage(message);+ }+ }++ public ValueTask HandleAsync(GroupChatStart item, MessageContext context)+ {+ item.Messages?.ForEach(item => this.ForwardMessageInternal(item, context.CancellationToken));++ return ValueTask.CompletedTask;+ }++ public ValueTask HandleAsync(GroupChatMessage item, MessageContext context)+ {+ Debug.Assert(item.Message is ChatMessage, "We should never receive internal messages into the output queue?");+ if (item.Message is ChatMessage chatMessage)+ {+ this.ForwardMessageInternal(chatMessage, context.CancellationToken);+ }++ return ValueTask.CompletedTask;+ }++ public ValueTask HandleAsync(GroupChatTermination item, MessageContext context)+ {+ this.Sink.Terminate(item.Message);++ return ValueTask.CompletedTask;+ }+}diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/RoundRobinGroupChat.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/RoundRobinGroupChat.csnew file mode 100644index 000000000..daa715063--- /dev/null+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/RoundRobinGroupChat.cs@@ -0,0 +1,57 @@+// Copyright (c) Microsoft Corporation. All rights reserved.+// RoundRobinGroupChat.cs++using Microsoft.AutoGen.AgentChat.Abstractions;++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+{+ private readonly List<string> participantTopicTypes;+ private int nextSpeakerIndex;++ public RoundRobinGroupChatManager(GroupChatOptions options) : base(options)+ {+ this.participantTopicTypes = [.. from candidateTopic in options.Participants.Values+ select candidateTopic.TopicType];+ this.nextSpeakerIndex = 0;+ }++ public override ValueTask<string> SelectSpeakerAsync(List<AgentMessage> thread)+ {+ string result = this.participantTopicTypes[this.nextSpeakerIndex].ToString();++ this.nextSpeakerIndex = (this.nextSpeakerIndex + 1) % this.participantTopicTypes.Count;++ return ValueTask.FromResult(result);+ }+}++/// <summary>+/// A team that runs a group chat with a participants taking turns in a round-robin fashion to publish+/// a message to all.+///+/// If a single participant is in the team, the participant will be the only speaker.+/// </summary>+public class RoundRobinGroupChat : GroupChatBase<RoundRobinGroupChatManager>+{+ /// <summary>+ /// Initializes a new round-robin group chat.+ /// </summary>+ /// <param name="participants">The participants in the group chat.</param>+ /// <param name="terminationCondition">+ /// The termination condition for the group chat. Defaults to <c>null</c>. Without a termination+ /// condition, the group chat will run indefinitely.+ /// </param>+ /// <param name="maxTurns">+ /// The maximum number of turns for the group chat. Defaults to <c>null</c>, meaning no limit.+ /// Note that the <see cref="ITerminationCondition"/> gets first priority for checking the termination+ /// if both are provided.+ /// </param>+ public RoundRobinGroupChat(List<IChatAgent> participants, ITerminationCondition? terminationCondition = null, int? maxTurns = null) : base(participants, terminationCondition, maxTurns)+ {+ }+}diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/Microsoft.AutoGen.AgentChat.csproj b/dotnet/src/Microsoft.AutoGen/AgentChat/Microsoft.AutoGen.AgentChat.csprojnew file mode 100644index 000000000..6d2cb3fbe--- /dev/null+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/Microsoft.AutoGen.AgentChat.csproj@@ -0,0 +1,23 @@+<Project Sdk="Microsoft.NET.Sdk">++ <PropertyGroup>+ <TargetFramework>net8.0</TargetFramework>+ <ImplicitUsings>enable</ImplicitUsings>+ <Nullable>enable</Nullable>+ </PropertyGroup>++ <Import Project="$(RepoRoot)/nuget/nuget-package.props" />++ <ItemGroup>+ <ProjectReference Include="..\Contracts\Microsoft.AutoGen.Contracts.csproj" />+ <ProjectReference Include="..\Core\Microsoft.AutoGen.Core.csproj" />+ </ItemGroup>++ <ItemGroup>+ <PackageReference Include="Microsoft.Extensions.AI" />+ <PackageReference Include="Microsoft.Extensions.Hosting" />+ <PackageReference Include="Microsoft.Extensions.Logging" />+ <PackageReference Include="Microsoft.Extensions.DependencyInjection" />+ <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" />+ </ItemGroup>+</Project>diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/Terminations/StopMessageTermination.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/Terminations/StopMessageTermination.csnew file mode 100644index 000000000..194fe1afe--- /dev/null+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/Terminations/StopMessageTermination.cs@@ -0,0 +1,40 @@+// Copyright (c) Microsoft Corporation. All rights reserved.+// StopMessageTermination.cs++using Microsoft.AutoGen.AgentChat.Abstractions;++namespace Microsoft.AutoGen.AgentChat.Terminations;++/// <summary>+/// Terminate a conversation if a <see cref="StopMessage"/> is received.+/// </summary>+public class StopMessageTermination : ITerminationCondition+{+ public bool IsTerminated { get; private set; }++ public ValueTask<StopMessage?> CheckAndUpdateAsync(IList<AgentMessage> messages)+ {+ if (this.IsTerminated)+ {+ throw new TerminatedException();+ }++ foreach (AgentMessage item in messages)+ {+ if (item is StopMessage)+ {+ this.IsTerminated = true;++ StopMessage result = new() { Content = "Stop message received", Source = nameof(StopMessageTermination) };+ return ValueTask.FromResult<StopMessage?>(result);+ }+ }++ return ValueTask.FromResult<StopMessage?>(null);+ }++ public void Reset()+ {+ this.IsTerminated = false;+ }+}diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/AgentId.cs b/dotnet/src/Microsoft.AutoGen/Contracts/AgentId.csindex 309854723..da5c5aa65 100644--- a/dotnet/src/Microsoft.AutoGen/Contracts/AgentId.cs+++ b/dotnet/src/Microsoft.AutoGen/Contracts/AgentId.cs@@ -14,7 +14,7 @@ namespace Microsoft.AutoGen.Contracts;/// See the Python equivalent:/// <see href="https://microsoft.github.io/autogen/stable/reference/python/autogen_core.html#autogen_core.AgentId">AgentId in AutoGen (Python)</see>./// </remarks>-[DebuggerDisplay($"AgentId(type=\"{nameof(Type)}\", key=\"{nameof(Key)}\")")]+[DebuggerDisplay($"AgentId(type=\"{{{nameof(Type)}}}\", key=\"{{{nameof(Key)}}}\")")]public struct AgentId{private static readonly Regex TypeRegex = new(@"^[a-zA-Z_][a-zA-Z0-9_]*$", RegexOptions.Compiled);diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/MessageContext.cs b/dotnet/src/Microsoft.AutoGen/Contracts/MessageContext.csindex e99f0c42d..58b580fee 100644--- a/dotnet/src/Microsoft.AutoGen/Contracts/MessageContext.cs+++ b/dotnet/src/Microsoft.AutoGen/Contracts/MessageContext.cs@@ -9,6 +9,9 @@ namespace Microsoft.AutoGen.Contracts;/// </summary>public class MessageContext(string messageId, CancellationToken cancellationToken){+ public MessageContext(CancellationToken cancellation) : this(Guid.NewGuid().ToString(), cancellation)+ { }+/// <summary>/// Gets or sets the unique identifier for this message./// </summary>diff --git a/dotnet/test/Microsoft.AutoGen.AgentChat.Tests/AgentChatSmokeTest.cs b/dotnet/test/Microsoft.AutoGen.AgentChat.Tests/AgentChatSmokeTest.csnew file mode 100644index 000000000..018f80cae--- /dev/null+++ b/dotnet/test/Microsoft.AutoGen.AgentChat.Tests/AgentChatSmokeTest.cs@@ -0,0 +1,106 @@+// Copyright (c) Microsoft Corporation. All rights reserved.+// AgentChatSmokeTest.cs++using Microsoft.AutoGen.AgentChat.Abstractions;+using Microsoft.AutoGen.AgentChat.Agents;+using Microsoft.AutoGen.AgentChat.GroupChat;+using Microsoft.AutoGen.AgentChat.Terminations;+using Xunit;++namespace Microsoft.AutoGen.AgentChat.Tests;++public class AgentChatSmokeTest+{+ public class SpeakMessageAgent : ChatAgentBase+ {+ public SpeakMessageAgent(string name, string description, string content) : base(name, description)+ {+ this.Content = content;+ }++ public string Content { get; private set; }++ public override IEnumerable<Type> ProducedMessageTypes => [typeof(HandoffMessage)];++ public override ValueTask<Response> HandleAsync(IEnumerable<ChatMessage> item, CancellationToken cancellationToken)+ {+ Response result = new()+ {+ Message = new TextMessage { Content = this.Content, Source = this.Name }+ };++ return ValueTask.FromResult(result);+ }++ public override ValueTask ResetAsync(CancellationToken cancellationToken)+ {+ return ValueTask.CompletedTask;+ }+ }++ public class TerminatingAgent : ChatAgentBase+ {+ public List<ChatMessage>? IncomingMessages { get; private set; }++ public TerminatingAgent(string name, string description) : base(name, description)+ {+ }++ public override IEnumerable<Type> ProducedMessageTypes => [typeof(StopMessage)];++ public override ValueTask<Response> HandleAsync(IEnumerable<ChatMessage> item, CancellationToken cancellationToken)+ {+ this.IncomingMessages = item.ToList();++ string content = "Terminating";+ if (item.Any())+ {+ ChatMessage lastMessage = item.Last();++ switch (lastMessage)+ {+ case TextMessage textMessage:+ content = $"Terminating; got: {textMessage.Content}";+ break;+ case HandoffMessage handoffMessage:+ content = $"Terminating; got handoff: {handoffMessage.Context}";+ break;+ }+ }++ Response result = new()+ {+ Message = new StopMessage { Content = content, Source = this.Name }+ };++ return ValueTask.FromResult(result);+ }++ public override ValueTask ResetAsync(CancellationToken cancellationToken)+ {+ this.IncomingMessages = null;++ return ValueTask.CompletedTask;+ }+ }++ [Fact]+ public async Task Test_RoundRobin_SpeakAndTerminating()+ {+ TerminatingAgent terminatingAgent = new("Terminate", "Terminate");++ ITeam chat = new RoundRobinGroupChat(+ [+ new SpeakMessageAgent("Speak", "Speak", "Hello"),+ terminatingAgent+ ],+ terminationCondition: new StopMessageTermination());++ TaskResult result = await chat.RunAsync("");++ Assert.Equal(3, result.Messages.Count);+ Assert.Equal("", 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);+ }+}diff --git a/dotnet/test/Microsoft.AutoGen.AgentChat.Tests/Microsoft.AutoGen.AgentChat.Tests.csproj b/dotnet/test/Microsoft.AutoGen.AgentChat.Tests/Microsoft.AutoGen.AgentChat.Tests.csprojnew file mode 100644index 000000000..e505771e6--- /dev/null+++ b/dotnet/test/Microsoft.AutoGen.AgentChat.Tests/Microsoft.AutoGen.AgentChat.Tests.csproj@@ -0,0 +1,15 @@+<Project Sdk="Microsoft.NET.Sdk">++ <PropertyGroup>+ <TargetFrameworks>$(TestTargetFrameworks)</TargetFrameworks>+ <ImplicitUsings>enable</ImplicitUsings>+ <Nullable>enable</Nullable>+ <IsTestProject>True</IsTestProject>+ </PropertyGroup>++ <ItemGroup>+ <ProjectReference Include="..\..\src\Microsoft.AutoGen\AgentChat\Microsoft.AutoGen.AgentChat.csproj" />+ <PackageReference Include="Microsoft.Extensions.Hosting" />+ </ItemGroup>++</Project>