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 Agents - Update Templating Pattern #10633

Merged
merged 6 commits into from
Feb 21, 2025
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -86,8 +86,8 @@ Always state the requested style of the poem.

private async Task InvokeAssistantAgentWithTemplateAsync(
string instructionTemplate,
string? templateFormat = null,
IPromptTemplateFactory? templateFactory = null)
string templateFormat,
IPromptTemplateFactory templateFactory)
{
PromptTemplateConfig config = new()
{
Expand All @@ -103,7 +103,7 @@ await this.AssistantClient.CreateAssistantFromTemplateAsync(
metadata: SampleMetadata);

// Create the agent
OpenAIAssistantAgent agent = new(assistant, this.AssistantClient, plugins: null, config, templateFactory)
OpenAIAssistantAgent agent = new(assistant, this.AssistantClient, plugins: null, templateFactory, templateFormat)
{
Arguments =
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,19 @@ public async Task UseTemplateForAzureAgentAsync()
// Define the agent
string generateStoryYaml = EmbeddedResource.Read("GenerateStory.yaml");
PromptTemplateConfig templateConfig = KernelFunctionYaml.ToPromptTemplateConfig(generateStoryYaml);

// Instructions, Name and Description properties defined via the PromptTemplateConfig.
Agent definition = await this.AgentsClient.CreateAgentAsync("gpt-4o", templateConfig.Name, templateConfig.Description, templateConfig.Template);
// Instructions, Name and Description properties defined via the config.
AzureAIAgent agent = new(definition, this.AgentsClient)
AzureAIAgent agent = new(
definition,
this.AgentsClient,
templateFactory: new KernelPromptTemplateFactory(),
templateFormat: PromptTemplateConfig.SemanticKernelTemplateFormat)
{
Arguments =
{
{ "topic", "Dog" },
{ "length", "3" },
},
{ "length", "3" }
}
};

// Create a thread for the agent conversation.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,19 @@ public async Task UseTemplateForAssistantAgentAsync()
// Define the agent
string generateStoryYaml = EmbeddedResource.Read("GenerateStory.yaml");
PromptTemplateConfig templateConfig = KernelFunctionYaml.ToPromptTemplateConfig(generateStoryYaml);

// Instructions, Name and Description properties defined via the config.
// Instructions, Name and Description properties defined via the PromptTemplateConfig.
Assistant definition = await this.AssistantClient.CreateAssistantFromTemplateAsync(this.Model, templateConfig, metadata: SampleMetadata);
OpenAIAssistantAgent agent = new(definition, this.AssistantClient)
OpenAIAssistantAgent agent = new(
definition,
this.AssistantClient,
templateFactory: new KernelPromptTemplateFactory(),
templateFormat: PromptTemplateConfig.SemanticKernelTemplateFormat)
{
Arguments =
{
{ "topic", "Dog" },
{ "length", "3" },
},
{ "length", "3" }
}
};

// Create a thread for the agent conversation.
Expand Down
10 changes: 5 additions & 5 deletions dotnet/src/Agents/Abstractions/KernelAgent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,14 @@ public abstract class KernelAgent : Agent
/// <returns>The formatted system instructions for the agent.</returns>
protected async Task<string?> FormatInstructionsAsync(Kernel kernel, KernelArguments? arguments, CancellationToken cancellationToken)
{
// Use the provided template as the instructions
if (this.Template is not null)
if (this.Template is null)
{
return await this.Template.RenderAsync(kernel, arguments, cancellationToken).ConfigureAwait(false);
// Use the instructions as-is
return this.Instructions;
}

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

/// <summary>
Expand Down
29 changes: 21 additions & 8 deletions dotnet/src/Agents/AzureAI/AzureAIAgent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,25 +54,38 @@ public static class Tools
/// </summary>
/// <param name="model">The agent model definition.</param>
/// <param name="client">An <see cref="AgentsClient"/> instance.</param>
/// <param name="templateConfig">The prompt template configuration.</param>
/// <param name="templateFactory">An optional template factory.</param>
/// <param name="plugins">Optional collection of plugins to add to the kernel.</param>
/// <param name="templateFactory">An optional factory to produce the <see cref="IPromptTemplate"/> for the agent.</param>
/// <param name="templateFormat">The format of the prompt template used when "templateFactory" parameter is supplied.</param>
public AzureAIAgent(
Azure.AI.Projects.Agent model,
AgentsClient client,
PromptTemplateConfig? templateConfig = null,
IPromptTemplateFactory? templateFactory = null)
IEnumerable<KernelPlugin>? plugins = null,
IPromptTemplateFactory? templateFactory = null,
string? templateFormat = null)
{
this.Client = client;
this.Definition = model;
this.Description = this.Definition.Description;
this.Id = this.Definition.Id;
this.Name = this.Definition.Name;
this.Instructions = templateConfig?.Template ?? this.Definition.Instructions;
this.Instructions = this.Definition.Instructions;

if (templateConfig is not null)
if (templateFactory != null)
{
this.Template = templateFactory?.Create(templateConfig)
?? throw new KernelException($"Invalid prompt template factory {templateFactory} for format {templateConfig.TemplateFormat}");
Verify.NotNullOrWhiteSpace(templateFormat);

PromptTemplateConfig templateConfig = new(this.Instructions)
{
TemplateFormat = templateFormat
};

this.Template = templateFactory.Create(templateConfig);
}

if (plugins != null)
{
this.Kernel.Plugins.AddRange(plugins);
}
}

Expand Down
9 changes: 5 additions & 4 deletions dotnet/src/Agents/Core/ChatCompletionAgent.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// Copyright (c) Microsoft. All rights reserved.

using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
Expand Down Expand Up @@ -62,7 +63,7 @@ public override IAsyncEnumerable<ChatMessageContent> InvokeAsync(
Kernel? kernel = null,
CancellationToken cancellationToken = default)
{
var agentName = this.GetDisplayName();
string agentName = this.GetDisplayName();

return ActivityExtensions.RunWithActivityAsync(
() => ModelDiagnostics.StartAgentInvocationActivity(this.Id, agentName, this.Description),
Expand All @@ -77,7 +78,7 @@ public override IAsyncEnumerable<StreamingChatMessageContent> InvokeStreamingAsy
Kernel? kernel = null,
CancellationToken cancellationToken = default)
{
var agentName = this.GetDisplayName();
string agentName = this.GetDisplayName();

return ActivityExtensions.RunWithActivityAsync(
() => ModelDiagnostics.StartAgentInvocationActivity(this.Id, agentName, this.Description),
Expand Down Expand Up @@ -143,7 +144,7 @@ private async IAsyncEnumerable<ChatMessageContent> InternalInvokeAsync(

int messageCount = chat.Count;

var serviceType = chatCompletionService.GetType();
Type serviceType = chatCompletionService.GetType();

this.Logger.LogAgentChatServiceInvokingAgent(nameof(InvokeAsync), this.Id, agentName, serviceType);

Expand Down Expand Up @@ -190,7 +191,7 @@ private async IAsyncEnumerable<StreamingChatMessageContent> InternalInvokeStream

int messageCount = chat.Count;

var serviceType = chatCompletionService.GetType();
Type serviceType = chatCompletionService.GetType();

this.Logger.LogAgentChatServiceInvokingAgent(nameof(InvokeAsync), this.Id, agentName, serviceType);

Expand Down
20 changes: 13 additions & 7 deletions dotnet/src/Agents/OpenAI/OpenAIAssistantAgent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,14 @@ public sealed partial class OpenAIAssistantAgent : KernelAgent
/// <param name="definition">The assistant definition.</param>
/// <param name="client">The OpenAI provider for accessing the Assistant API service.</param>
/// <param name="plugins">Optional collection of plugins to add to the kernel.</param>
/// <param name="templateConfig">The prompt template configuration.</param>
/// <param name="templateFactory">An optional factory to produce the <see cref="IPromptTemplate"/> for the agent.</param>
/// <param name="templateFormat">The format of the prompt template used when "templateFactory" parameter is supplied.</param>
public OpenAIAssistantAgent(
Assistant definition,
AssistantClient client,
IEnumerable<KernelPlugin>? plugins = null,
PromptTemplateConfig? templateConfig = null,
IPromptTemplateFactory? templateFactory = null)
IPromptTemplateFactory? templateFactory = null,
string? templateFormat = null)
{
this.Client = client;

Expand All @@ -51,12 +51,18 @@ public OpenAIAssistantAgent(
this.Description = this.Definition.Description;
this.Id = this.Definition.Id;
this.Name = this.Definition.Name;
this.Instructions = templateConfig?.Template ?? this.Definition.Instructions;
this.Instructions = this.Definition.Instructions;

if (templateConfig is not null)
if (templateFactory != null)
{
this.Template = templateFactory?.Create(templateConfig)
?? throw new KernelException($"Invalid prompt template factory {templateFactory} for format {templateConfig.TemplateFormat}");
Verify.NotNullOrWhiteSpace(templateFormat);

PromptTemplateConfig templateConfig = new(this.Instructions)
{
TemplateFormat = templateFormat
};

this.Template = templateFactory.Create(templateConfig);
}

if (plugins != null)
Expand Down
Loading