Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

.Net: Removing KernelAgent.cs and moving its functionality into Agent.cs #11244

Merged
merged 9 commits into from
Apr 2, 2025
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ Always state the requested style of the poem.
// Create the agent
OpenAIAssistantAgent agent = new(assistant, this.AssistantClient)
{
Arguments =
Arguments = new()
{
{"style", "haiku"}
},
Expand Down Expand Up @@ -105,7 +105,7 @@ await this.AssistantClient.CreateAssistantFromTemplateAsync(
// Create the agent
OpenAIAssistantAgent agent = new(assistant, this.AssistantClient, plugins: null, templateFactory, templateFormat)
{
Arguments =
Arguments = new()
{
{"style", "haiku"}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public async Task UseTemplateForAzureAgentAsync()
templateFactory: new KernelPromptTemplateFactory(),
templateFormat: PromptTemplateConfig.SemanticKernelTemplateFormat)
{
Arguments =
Arguments = new()
{
{ "topic", "Dog" },
{ "length", "3" }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public async Task UseTemplateForAssistantAgentAsync()
templateFactory: new KernelPromptTemplateFactory(),
templateFormat: PromptTemplateConfig.SemanticKernelTemplateFormat)
{
Arguments =
Arguments = new()
{
{ "topic", "Dog" },
{ "length", "3" }
Expand Down
2 changes: 1 addition & 1 deletion dotnet/samples/GettingStartedWithAgents/Step01_Agent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ public async Task UseTemplateForChatCompletionAgentAsync()
new(templateConfig, templateFactory)
{
Kernel = this.CreateKernelWithChatCompletion(),
Arguments =
Arguments = new()
{
{ "topic", "Dog" },
{ "length", "3" },
Expand Down
48 changes: 6 additions & 42 deletions dotnet/src/Agents/Abstractions/Agent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.SemanticKernel.Arguments.Extensions;
using Microsoft.SemanticKernel.ChatCompletion;

namespace Microsoft.SemanticKernel.Agents;
Expand Down Expand Up @@ -51,7 +51,7 @@ public abstract class Agent
/// <remarks>
/// Also includes <see cref="PromptExecutionSettings"/>.
/// </remarks>
public KernelArguments Arguments { get; init; } = [];
public KernelArguments? Arguments { get; init; }

/// <summary>
/// Gets the instructions for the agent (optional).
Expand Down Expand Up @@ -256,16 +256,18 @@ public abstract IAsyncEnumerable<AgentResponseItem<StreamingChatMessageContent>>
/// <param name="arguments">Optional arguments to pass to the agents's invocation, including any <see cref="PromptExecutionSettings"/>.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>The formatted system instructions for the agent.</returns>
protected async Task<string?> FormatInstructionsAsync(Kernel kernel, KernelArguments? arguments, CancellationToken cancellationToken)
protected async Task<string?> RenderInstructionsAsync(Kernel kernel, KernelArguments? arguments, CancellationToken cancellationToken)
{
if (this.Template is null)
{
// Use the instructions as-is
return this.Instructions;
}

var mergedArguments = this.Arguments.Merge(arguments);

// Use the provided template as the instructions
return await this.Template.RenderAsync(kernel, arguments, cancellationToken).ConfigureAwait(false);
return await this.Template.RenderAsync(kernel, mergedArguments, cancellationToken).ConfigureAwait(false);
}

/// <summary>
Expand Down Expand Up @@ -382,42 +384,4 @@ protected Task NotifyThreadOfNewMessage(AgentThread thread, ChatMessageContent m
{
return thread.OnNewMessageAsync(message, cancellationToken);
}

/// <summary>
/// Provides a merged instance of <see cref="KernelArguments"/> with precedence for override arguments.
/// </summary>
/// <param name="arguments">The override arguments.</param>
/// <remarks>
/// This merge preserves original <see cref="PromptExecutionSettings"/> and <see cref="KernelArguments"/> parameters.
/// It allows for incremental addition or replacement of specific parameters while also preserving the ability
/// to override the execution settings.
/// </remarks>
protected KernelArguments MergeArguments(KernelArguments? arguments)
{
// Avoid merge when override arguments are not set.
if (arguments == null)
{
return this.Arguments;
}

// Both instances are not null, merge with precedence for override arguments.

// Merge execution settings with precedence for override arguments.
Dictionary<string, PromptExecutionSettings>? settings =
(arguments.ExecutionSettings ?? s_emptySettings)
.Concat(this.Arguments.ExecutionSettings ?? s_emptySettings)
.GroupBy(entry => entry.Key)
.ToDictionary(entry => entry.Key, entry => entry.First().Value);

// Merge parameters with precedence for override arguments.
Dictionary<string, object?>? parameters =
arguments
.Concat(this.Arguments)
.GroupBy(entry => entry.Key)
.ToDictionary(entry => entry.Key, entry => entry.First().Value);

return new KernelArguments(parameters, settings);
}

private static readonly Dictionary<string, PromptExecutionSettings> s_emptySettings = [];
}
3 changes: 2 additions & 1 deletion dotnet/src/Agents/Abstractions/Agents.Abstractions.csproj
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<!-- THIS PROPERTY GROUP MUST COME FIRST -->
Expand All @@ -21,6 +21,7 @@
<Compile Include="$(RepoRoot)/dotnet/src/InternalUtilities/src/Diagnostics/*" Link="%(RecursiveDir)Utilities/%(Filename)%(Extension)" />
<Compile Include="$(RepoRoot)/dotnet/src/InternalUtilities/src/System/AppContextSwitchHelper.cs" Link="%(RecursiveDir)Utilities/%(Filename)%(Extension)" />
<Compile Include="$(RepoRoot)/dotnet/src/InternalUtilities/agents/Extensions/AgentExtensions.cs" Link="%(RecursiveDir)Utilities/%(Filename)%(Extension)" />
<Compile Include="$(RepoRoot)/dotnet/src/InternalUtilities/arguments/Extensions/KernelArgumentsExtensions.cs" Link="%(RecursiveDir)Utilities/%(Filename)%(Extension)" />
</ItemGroup>

<ItemGroup>
Expand Down
10 changes: 3 additions & 7 deletions dotnet/src/Agents/AzureAI/AzureAIAgent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ async IAsyncEnumerable<ChatMessageContent> InternalInvokeAsync()
options?.ToAzureAIInvocationOptions(),
this.Logger,
options?.Kernel ?? this.Kernel,
this.MergeArguments(options?.KernelArguments),
options?.KernelArguments,
cancellationToken).ConfigureAwait(false))
{
// The thread and the caller should be notified of all messages regardless of visibility.
Expand Down Expand Up @@ -252,8 +252,6 @@ public IAsyncEnumerable<ChatMessageContent> InvokeAsync(
async IAsyncEnumerable<ChatMessageContent> InternalInvokeAsync()
{
kernel ??= this.Kernel;
arguments = this.MergeArguments(arguments);

await foreach ((bool isVisible, ChatMessageContent message) in AgentThreadActions.InvokeAsync(this, this.Client, threadId, options, this.Logger, kernel, arguments, cancellationToken).ConfigureAwait(false))
{
if (isVisible)
Expand Down Expand Up @@ -311,7 +309,7 @@ public async IAsyncEnumerable<AgentResponseItem<StreamingChatMessageContent>> In
var invokeResults = this.InvokeStreamingAsync(
azureAIAgentThread.Id!,
options?.ToAzureAIInvocationOptions(),
this.MergeArguments(options?.KernelArguments),
options?.KernelArguments,
options?.Kernel ?? this.Kernel,
newMessagesReceiver,
cancellationToken);
Expand Down Expand Up @@ -388,8 +386,6 @@ public IAsyncEnumerable<StreamingChatMessageContent> InvokeStreamingAsync(
IAsyncEnumerable<StreamingChatMessageContent> InternalInvokeStreamingAsync()
{
kernel ??= this.Kernel;
arguments = this.MergeArguments(arguments);

return AgentThreadActions.InvokeStreamingAsync(this, this.Client, threadId, messages, options, this.Logger, kernel, arguments, cancellationToken);
}
}
Expand Down Expand Up @@ -425,7 +421,7 @@ protected override async Task<AgentChannel> CreateChannelAsync(CancellationToken

internal Task<string?> GetInstructionsAsync(Kernel kernel, KernelArguments? arguments, CancellationToken cancellationToken)
{
return this.FormatInstructionsAsync(kernel, arguments, cancellationToken);
return this.RenderInstructionsAsync(kernel, arguments, cancellationToken);
}

/// <inheritdoc/>
Expand Down
14 changes: 4 additions & 10 deletions dotnet/src/Agents/Bedrock/BedrockAgent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,7 @@ public override async IAsyncEnumerable<AgentResponseItem<ChatMessageContent>> In
});

// Invoke the agent
var arguments = this.MergeArguments(options?.KernelArguments);
var invokeResults = this.InvokeInternalAsync(invokeAgentRequest, arguments, cancellationToken);
var invokeResults = this.InvokeInternalAsync(invokeAgentRequest, options?.KernelArguments, cancellationToken);

// Return the results to the caller in AgentResponseItems.
await foreach (var result in invokeResults.ConfigureAwait(false))
Expand Down Expand Up @@ -180,8 +179,6 @@ public async IAsyncEnumerable<AgentResponseItem<ChatMessageContent>> InvokeAsync
AgentInvokeOptions? options = null,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
var arguments = this.MergeArguments(options?.KernelArguments);

// The provided thread is used to continue the conversation. If the thread is not provided and the session id is provided,
// a new thread is created with the provided session id. If neither is provided, a new thread is created.
if (thread is null && invokeAgentRequest.SessionId is not null)
Expand All @@ -200,7 +197,7 @@ public async IAsyncEnumerable<AgentResponseItem<ChatMessageContent>> InvokeAsync
invokeAgentRequest = this.ConfigureAgentRequest(options, () => invokeAgentRequest);

// Invoke the agent
var invokeResults = this.InvokeInternalAsync(invokeAgentRequest, arguments, cancellationToken);
var invokeResults = this.InvokeInternalAsync(invokeAgentRequest, options?.KernelArguments, cancellationToken);

// Return the results to the caller in AgentResponseItems.
await foreach (var result in invokeResults.ConfigureAwait(false))
Expand Down Expand Up @@ -368,8 +365,7 @@ public override async IAsyncEnumerable<AgentResponseItem<StreamingChatMessageCon
});

// Invoke the agent
var arguments = this.MergeArguments(options?.KernelArguments);
var invokeResults = this.InvokeStreamingInternalAsync(invokeAgentRequest, bedrockThread, arguments, cancellationToken);
var invokeResults = this.InvokeStreamingInternalAsync(invokeAgentRequest, bedrockThread, options?.KernelArguments, cancellationToken);

// Return the results to the caller in AgentResponseItems.
await foreach (var result in invokeResults.ConfigureAwait(false))
Expand Down Expand Up @@ -413,8 +409,6 @@ public async IAsyncEnumerable<AgentResponseItem<StreamingChatMessageContent>> In
AgentInvokeOptions? options = null,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
var arguments = this.MergeArguments(options?.KernelArguments);

// The provided thread is used to continue the conversation. If the thread is not provided and the session id is provided,
// a new thread is created with the provided session id. If neither is provided, a new thread is created.
if (thread is null && invokeAgentRequest.SessionId is not null)
Expand All @@ -432,7 +426,7 @@ public async IAsyncEnumerable<AgentResponseItem<StreamingChatMessageContent>> In
invokeAgentRequest.SessionId = bedrockThread.Id;
invokeAgentRequest = this.ConfigureAgentRequest(options, () => invokeAgentRequest);

var invokeResults = this.InvokeStreamingInternalAsync(invokeAgentRequest, bedrockThread, arguments, cancellationToken);
var invokeResults = this.InvokeStreamingInternalAsync(invokeAgentRequest, bedrockThread, options?.KernelArguments, cancellationToken);

// The Bedrock agent service has the same API for both streaming and non-streaming responses.
// We are invoking the same method as the non-streaming response with the streaming configuration set,
Expand Down
4 changes: 1 addition & 3 deletions dotnet/src/Agents/Core/ChatCompletionAgent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ private async Task<ChatHistory> SetupAgentChatHistoryAsync(
{
ChatHistory chat = [];

string? instructions = await this.FormatInstructionsAsync(kernel, arguments, cancellationToken).ConfigureAwait(false);
string? instructions = await this.RenderInstructionsAsync(kernel, arguments, cancellationToken).ConfigureAwait(false);

if (!string.IsNullOrWhiteSpace(instructions))
{
Expand All @@ -267,7 +267,6 @@ private async IAsyncEnumerable<ChatMessageContent> InternalInvokeAsync(
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
kernel ??= this.Kernel;
arguments = this.MergeArguments(arguments);

(IChatCompletionService chatCompletionService, PromptExecutionSettings? executionSettings) = GetChatCompletionService(kernel, arguments);

Expand Down Expand Up @@ -317,7 +316,6 @@ private async IAsyncEnumerable<StreamingChatMessageContent> InternalInvokeStream
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
kernel ??= this.Kernel;
arguments = this.MergeArguments(arguments);

(IChatCompletionService chatCompletionService, PromptExecutionSettings? executionSettings) = GetChatCompletionService(kernel, arguments);

Expand Down
10 changes: 3 additions & 7 deletions dotnet/src/Agents/OpenAI/OpenAIAssistantAgent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,7 @@ async IAsyncEnumerable<ChatMessageContent> InternalInvokeAsync()
internalOptions,
this.Logger,
options?.Kernel ?? this.Kernel,
this.MergeArguments(options?.KernelArguments),
options?.KernelArguments,
cancellationToken).ConfigureAwait(false))
{
// The thread and the caller should be notified of all messages regardless of visibility.
Expand Down Expand Up @@ -496,8 +496,6 @@ public IAsyncEnumerable<ChatMessageContent> InvokeAsync(
async IAsyncEnumerable<ChatMessageContent> InternalInvokeAsync()
{
kernel ??= this.Kernel;
arguments = this.MergeArguments(arguments);

await foreach ((bool isVisible, ChatMessageContent message) in AssistantThreadActions.InvokeAsync(this, this.Client, threadId, options, this.Logger, kernel, arguments, cancellationToken).ConfigureAwait(false))
{
if (isVisible)
Expand Down Expand Up @@ -563,7 +561,7 @@ public async IAsyncEnumerable<AgentResponseItem<StreamingChatMessageContent>> In
var invokeResults = this.InvokeStreamingAsync(
openAIAssistantAgentThread.Id!,
internalOptions,
this.MergeArguments(options?.KernelArguments),
options?.KernelArguments,
options?.Kernel ?? this.Kernel,
newMessagesReceiver,
cancellationToken);
Expand Down Expand Up @@ -640,8 +638,6 @@ public IAsyncEnumerable<StreamingChatMessageContent> InvokeStreamingAsync(
IAsyncEnumerable<StreamingChatMessageContent> InternalInvokeStreamingAsync()
{
kernel ??= this.Kernel;
arguments = this.MergeArguments(arguments);

return AssistantThreadActions.InvokeStreamingAsync(this, this.Client, threadId, messages, options, this.Logger, kernel, arguments, cancellationToken);
}
}
Expand Down Expand Up @@ -678,7 +674,7 @@ protected override async Task<AgentChannel> CreateChannelAsync(CancellationToken
}

internal Task<string?> GetInstructionsAsync(Kernel kernel, KernelArguments? arguments, CancellationToken cancellationToken) =>
this.FormatInstructionsAsync(kernel, arguments, cancellationToken);
this.RenderInstructionsAsync(kernel, arguments, cancellationToken);

/// <inheritdoc/>
[Experimental("SKEXP0110")]
Expand Down
Loading
Loading