Skip to content

Commit 6181ccc

Browse files
committed
Add fix for plugin naming collisions
1 parent 2a78664 commit 6181ccc

2 files changed

Lines changed: 33 additions & 1 deletion

File tree

dotnet/src/SemanticKernel.Core/Memory/AIContextExtensions.cs

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,20 @@ public static class AIContextExtensions
1818
/// </summary>
1919
/// <param name="plugins">The plugins collection to register the <see cref="AIFunction"/> objects on.</param>
2020
/// <param name="aiContext">The <see cref="AIContext"/> to get plugins from.</param>
21-
/// <param name="pluginName">The name to give to the plugin.</param>
21+
/// <param name="pluginName">The name to give to the plugin. This will be appended with _x where x is an ascending number, until a unique plugin name is found.</param>
2222
public static void AddFromAIContext(this ICollection<KernelPlugin> plugins, AIContext aiContext, string pluginName)
2323
{
2424
if (aiContext.AIFunctions is { Count: > 0 })
2525
{
26+
var originalPluginName = pluginName;
27+
var counter = 1;
28+
29+
// Find a unique plugin name by appending a counter if necessary.
30+
while (plugins.Any(x => x.Name == pluginName))
31+
{
32+
pluginName = $"{originalPluginName}_{counter}";
33+
}
34+
2635
plugins.AddFromFunctions(pluginName, aiContext.AIFunctions.Select(x => x.AsKernelFunction()));
2736
}
2837
}

dotnet/src/SemanticKernel.UnitTests/Memory/AIContextProviderTests.cs

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Copyright (c) Microsoft. All rights reserved.
22

3+
using System.Collections.Generic;
34
using System.Threading;
45
using System.Threading.Tasks;
56
using Microsoft.Extensions.AI;
@@ -64,4 +65,26 @@ public async Task ResumingAsyncBaseImplementationSucceeds()
6465
// Act & Assert.
6566
await mockPart.Object.ResumingAsync("threadId", CancellationToken.None);
6667
}
68+
69+
[Fact]
70+
public void ExtensionCanAddPluginsFromAIContextProvider()
71+
{
72+
var plugins = new List<KernelPlugin>();
73+
74+
var aiContext = new AIContext
75+
{
76+
AIFunctions = new List<AIFunction>
77+
{
78+
AIFunctionFactory.Create(() => Task.FromResult("Function1 Result"), "Function1"),
79+
AIFunctionFactory.Create(() => Task.FromResult("Function2 Result"), "Function2")
80+
}
81+
};
82+
83+
plugins.AddFromAIContext(aiContext, "TestPlugin");
84+
plugins.AddFromAIContext(aiContext, "TestPlugin");
85+
86+
Assert.Equal(2, plugins.Count);
87+
Assert.Contains(plugins, p => p.Name == "TestPlugin");
88+
Assert.Contains(plugins, p => p.Name == "TestPlugin_1");
89+
}
6790
}

0 commit comments

Comments
 (0)