|
| 1 | +// Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +using System; |
| 4 | +using System.Collections.Generic; |
| 5 | +using System.Diagnostics.CodeAnalysis; |
| 6 | +using System.Linq; |
| 7 | +using System.Runtime.CompilerServices; |
| 8 | +using System.Text.Json; |
| 9 | +using System.Threading; |
| 10 | +using System.Threading.Tasks; |
| 11 | +using Microsoft.Extensions.AI; |
| 12 | +using MAAI = Microsoft.Agents.AI; |
| 13 | + |
| 14 | +namespace Microsoft.SemanticKernel.Agents; |
| 15 | + |
| 16 | +/// <summary> |
| 17 | +/// Exposes a Semantic Kernel Agent Framework <see cref="Agent"/> as a Microsoft Agent Framework <see cref="MAAI.AIAgent"/>. |
| 18 | +/// </summary> |
| 19 | +[Experimental("SKEXP0110")] |
| 20 | +internal sealed class SemanticKernelAIAgent : MAAI.AIAgent |
| 21 | +{ |
| 22 | + private readonly Agent _innerAgent; |
| 23 | + private readonly Func<AgentThread> _threadFactory; |
| 24 | + private readonly Func<JsonElement, JsonSerializerOptions?, AgentThread> _threadDeserializationFactory; |
| 25 | + private readonly Func<AgentThread, JsonSerializerOptions?, JsonElement> _threadSerializer; |
| 26 | + |
| 27 | + /// <summary> |
| 28 | + /// Initializes a new instance of the <see cref="SemanticKernelAIAgent"/> class. |
| 29 | + /// </summary> |
| 30 | + /// <param name="semanticKernelAgent">The Semantic Kernel <see cref="Agent"/> to expose as a Microsoft Agent Framework <see cref="MAAI.AIAgent"/>.</param> |
| 31 | + /// <param name="threadFactory">A factory method to create the required <see cref="AgentThread"/> type to use with the agent.</param> |
| 32 | + /// <param name="threadDeserializationFactory">A factory method to deserialize the required <see cref="AgentThread"/> type.</param> |
| 33 | + /// <param name="threadSerializer">A method to serialize the <see cref="AgentThread"/> type.</param> |
| 34 | + public SemanticKernelAIAgent( |
| 35 | + Agent semanticKernelAgent, |
| 36 | + Func<AgentThread> threadFactory, |
| 37 | + Func<JsonElement, JsonSerializerOptions?, AgentThread> threadDeserializationFactory, |
| 38 | + Func<AgentThread, JsonSerializerOptions?, JsonElement> threadSerializer) |
| 39 | + { |
| 40 | + Throw.IfNull(semanticKernelAgent); |
| 41 | + Throw.IfNull(threadFactory); |
| 42 | + Throw.IfNull(threadDeserializationFactory); |
| 43 | + Throw.IfNull(threadSerializer); |
| 44 | + |
| 45 | + this._innerAgent = semanticKernelAgent; |
| 46 | + this._threadFactory = threadFactory; |
| 47 | + this._threadDeserializationFactory = threadDeserializationFactory; |
| 48 | + this._threadSerializer = threadSerializer; |
| 49 | + } |
| 50 | + |
| 51 | + /// <inheritdoc /> |
| 52 | + public override MAAI.AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null) |
| 53 | + => new SemanticKernelAIAgentThread(this._threadDeserializationFactory(serializedThread, jsonSerializerOptions), this._threadSerializer); |
| 54 | + |
| 55 | + /// <inheritdoc /> |
| 56 | + public override MAAI.AgentThread GetNewThread() => new SemanticKernelAIAgentThread(this._threadFactory(), this._threadSerializer); |
| 57 | + |
| 58 | + /// <inheritdoc /> |
| 59 | + public override async Task<MAAI.AgentRunResponse> RunAsync(IEnumerable<ChatMessage> messages, MAAI.AgentThread? thread = null, MAAI.AgentRunOptions? options = null, CancellationToken cancellationToken = default) |
| 60 | + { |
| 61 | + thread ??= this.GetNewThread(); |
| 62 | + if (thread is not SemanticKernelAIAgentThread typedThread) |
| 63 | + { |
| 64 | + throw new InvalidOperationException("The provided thread is not compatible with the agent. Only threads created by the agent can be used."); |
| 65 | + } |
| 66 | + |
| 67 | + List<ChatMessage> responseMessages = []; |
| 68 | + var invokeOptions = new AgentInvokeOptions() |
| 69 | + { |
| 70 | + OnIntermediateMessage = (msg) => |
| 71 | + { |
| 72 | + responseMessages.Add(msg.ToChatMessage()); |
| 73 | + return Task.CompletedTask; |
| 74 | + } |
| 75 | + }; |
| 76 | + |
| 77 | + AgentResponseItem<ChatMessageContent>? lastResponseItem = null; |
| 78 | + ChatMessage? lastResponseMessage = null; |
| 79 | + await foreach (var responseItem in this._innerAgent.InvokeAsync(messages.Select(x => x.ToChatMessageContent()).ToList(), typedThread.InnerThread, invokeOptions, cancellationToken).ConfigureAwait(false)) |
| 80 | + { |
| 81 | + lastResponseItem = responseItem; |
| 82 | + lastResponseMessage = responseItem.Message.ToChatMessage(); |
| 83 | + responseMessages.Add(lastResponseMessage); |
| 84 | + } |
| 85 | + |
| 86 | + return new MAAI.AgentRunResponse(responseMessages) |
| 87 | + { |
| 88 | + AgentId = this._innerAgent.Id, |
| 89 | + RawRepresentation = lastResponseItem, |
| 90 | + AdditionalProperties = lastResponseMessage?.AdditionalProperties, |
| 91 | + CreatedAt = lastResponseMessage?.CreatedAt, |
| 92 | + }; |
| 93 | + } |
| 94 | + |
| 95 | + /// <inheritdoc /> |
| 96 | + public override async IAsyncEnumerable<MAAI.AgentRunResponseUpdate> RunStreamingAsync( |
| 97 | + IEnumerable<ChatMessage> messages, |
| 98 | + MAAI.AgentThread? thread = null, |
| 99 | + MAAI.AgentRunOptions? options = null, |
| 100 | + [EnumeratorCancellation] CancellationToken cancellationToken = default) |
| 101 | + { |
| 102 | + thread ??= this.GetNewThread(); |
| 103 | + if (thread is not SemanticKernelAIAgentThread typedThread) |
| 104 | + { |
| 105 | + throw new InvalidOperationException("The provided thread is not compatible with the agent. Only threads created by the agent can be used."); |
| 106 | + } |
| 107 | + |
| 108 | + await foreach (var responseItem in this._innerAgent.InvokeStreamingAsync(messages.Select(x => x.ToChatMessageContent()).ToList(), typedThread.InnerThread, cancellationToken: cancellationToken).ConfigureAwait(false)) |
| 109 | + { |
| 110 | + var update = responseItem.Message.ToChatResponseUpdate(); |
| 111 | + |
| 112 | + yield return new MAAI.AgentRunResponseUpdate |
| 113 | + { |
| 114 | + AuthorName = update.AuthorName, |
| 115 | + AgentId = this._innerAgent.Id, |
| 116 | + RawRepresentation = responseItem, |
| 117 | + AdditionalProperties = update.AdditionalProperties, |
| 118 | + MessageId = update.MessageId, |
| 119 | + Role = update.Role, |
| 120 | + ResponseId = update.ResponseId, |
| 121 | + CreatedAt = update.CreatedAt, |
| 122 | + Contents = update.Contents |
| 123 | + }; |
| 124 | + } |
| 125 | + } |
| 126 | +} |
0 commit comments