-
Notifications
You must be signed in to change notification settings - Fork 4.6k
Expand file tree
/
Copy pathAIFunctionKernelFunctionTests.cs
More file actions
308 lines (250 loc) · 9.46 KB
/
AIFunctionKernelFunctionTests.cs
File metadata and controls
308 lines (250 loc) · 9.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Xunit;
namespace SemanticKernel.UnitTests.AI.ChatCompletion;
public class AIFunctionKernelFunctionTests
{
[Fact]
public void ShouldAssignIsRequiredParameterMetadataPropertyCorrectly()
{
// Arrange and Act
AIFunction aiFunction = AIFunctionFactory.Create((string p1, int? p2 = null) => p1,
new AIFunctionFactoryOptions { JsonSchemaCreateOptions = new AIJsonSchemaCreateOptions { TransformOptions = new() { RequireAllProperties = false } } });
AIFunctionKernelFunction sut = new(aiFunction);
// Assert
KernelParameterMetadata? p1Metadata = sut.Metadata.Parameters.FirstOrDefault(p => p.Name == "p1");
Assert.True(p1Metadata?.IsRequired);
KernelParameterMetadata? p2Metadata = sut.Metadata.Parameters.FirstOrDefault(p => p.Name == "p2");
Assert.False(p2Metadata?.IsRequired);
}
[Fact]
private void AIFunctionKernelFunctionFromAIFunctionShouldHavePluginName()
{
AIFunction aiFunc = AIFunctionFactory.Create(() => { }, "f1");
Assert.Equal("f1", aiFunc.Name);
KernelFunction kernelFunction = aiFunc.AsKernelFunction();
Assert.Equal("f1", kernelFunction.Name);
Assert.Null(kernelFunction.PluginName);
Kernel kernel = new();
kernel.Plugins.AddFromFunctions("Tools", [kernelFunction]);
KernelFunction pluginFunction = kernel.Plugins.ElementAt(0).ElementAt(0);
Assert.Equal("f1", pluginFunction.Name);
Assert.Equal("Tools", pluginFunction.PluginName);
}
[Fact]
public void ShouldUseKernelFunctionNameWhenWrappingKernelFunction()
{
// Arrange
var kernelFunction = KernelFunctionFactory.CreateFromMethod(() => "Test", "TestFunction");
// Act
AIFunctionKernelFunction sut = new(kernelFunction);
// Assert
Assert.Equal("TestFunction", sut.Name);
}
[Fact]
public void ShouldUseKernelFunctionPluginAndNameWhenWrappingKernelFunction()
{
// Arrange
var kernelFunction = KernelFunctionFactory.CreateFromMethod(() => "Test", "TestFunction")
.Clone("TestPlugin"); // Simulate a plugin name
// Act
AIFunctionKernelFunction sut = new(kernelFunction);
// Assert
Assert.Equal("TestPlugin_TestFunction", sut.Name);
Assert.Null(sut.PluginName);
}
[Fact]
public void ShouldUseNameOnlyInToStringWhenWrappingKernelFunctionWithPlugin()
{
// Arrange
var kernelFunction = KernelFunctionFactory.CreateFromMethod(() => "Test", "TestFunction")
.Clone("TestPlugin");
// Act
AIFunctionKernelFunction sut = new(kernelFunction);
// Assert
Assert.Equal("TestPlugin_TestFunction", sut.ToString());
}
[Fact]
public void ShouldUseAIFunctionNameWhenWrappingNonKernelFunction()
{
// Arrange
var aiFunction = new TestAIFunction("CustomName");
// Act
AIFunctionKernelFunction sut = new(aiFunction);
// Assert
Assert.Equal("CustomName", sut.Name);
Assert.Null(sut.PluginName);
}
[Fact]
public void ShouldPreserveDescriptionFromAIFunction()
{
// Arrange
var aiFunction = new TestAIFunction("TestFunction", "This is a test description");
// Act
AIFunctionKernelFunction sut = new(aiFunction);
// Assert
Assert.Equal("This is a test description", sut.Description);
}
[Fact]
public void ShouldPreserveRootLevelSchemaDefinitionsFromAIFunction()
{
// Arrange
var aiFunction = new TestAIFunctionWithSchema("TestFunction", """
{
"type": "object",
"properties": {
"node": {
"$ref": "#/$defs/Node"
}
},
"$defs": {
"Node": {
"type": "object",
"properties": {
"name": {
"type": "string"
}
}
}
}
}
""");
// Act
AIFunctionKernelFunction sut = new(aiFunction);
var schema = sut.JsonSchema;
// Assert
Assert.True(schema.TryGetProperty("$defs", out var defs));
Assert.True(defs.TryGetProperty("Node", out _));
Assert.Equal("#/$defs/Node", schema.GetProperty("properties").GetProperty("node").GetProperty("$ref").GetString());
}
[Fact]
public async Task ShouldInvokeUnderlyingAIFunctionWhenInvoked()
{
// Arrange
var testAIFunction = new TestAIFunction("TestFunction");
AIFunctionKernelFunction sut = new(testAIFunction);
var kernel = new Kernel();
var arguments = new KernelArguments();
// Act
await sut.InvokeAsync(kernel, arguments);
// Assert
Assert.True(testAIFunction.WasInvoked);
}
[Fact]
public async Task ShouldInvokeUnderlyingAIFunctionWhenInvokedAsStreaming()
{
// Arrange
var testAIFunction = new TestAIFunction("TestFunction");
AIFunctionKernelFunction sut = new(testAIFunction);
var kernel = new Kernel();
var streamed = new List<string>();
// Act
await foreach (var chunk in sut.InvokeStreamingAsync<string>(kernel, []))
{
streamed.Add(chunk);
}
// Assert
Assert.True(testAIFunction.WasInvoked);
Assert.Single(streamed);
Assert.Equal("Test result", streamed[0]);
}
[Fact]
public void ShouldCloneCorrectlyWithNewPluginName()
{
// Arrange
var aiFunction = new TestAIFunction("TestFunction");
AIFunctionKernelFunction original = new(aiFunction);
// Act
var cloned = original.Clone("NewPlugin");
// Assert
Assert.Equal("NewPlugin", cloned.PluginName);
Assert.Equal("TestFunction", cloned.Name);
Assert.Equal("NewPlugin.TestFunction", cloned.ToString());
}
[Fact]
public async Task ClonedFunctionShouldInvokeOriginalAIFunction()
{
// Arrange
var testAIFunction = new TestAIFunction("TestFunction");
AIFunctionKernelFunction original = new(testAIFunction);
var cloned = original.Clone("NewPlugin");
var kernel = new Kernel();
var arguments = new KernelArguments();
// Act
await cloned.InvokeAsync(kernel, arguments);
// Assert
Assert.True(testAIFunction.WasInvoked);
}
[Fact]
public async Task ShouldUseProvidedKernelWhenInvoking()
{
// Arrange
var kernel1 = new Kernel();
var kernel2 = new Kernel();
// Create a function that returns the kernel's hash code
var function = KernelFunctionFactory.CreateFromMethod(
(Kernel k) => k.GetHashCode().ToString(),
"GetKernelHashCode");
var aiFunction = new AIFunctionKernelFunction(function);
// Clone with a new plugin name
var clonedFunction = aiFunction.Clone("NewPlugin");
// Act
var result1 = await clonedFunction.InvokeAsync(kernel1, []);
var result2 = await clonedFunction.InvokeAsync(kernel2, []);
// Assert - verify that the results are different when using different kernels
var result1Str = result1.GetValue<object>()?.ToString();
var result2Str = result2.GetValue<object>()?.ToString();
Assert.NotNull(result1Str);
Assert.NotNull(result2Str);
Assert.NotEqual(result1Str, result2Str);
}
[Fact]
public void ShouldThrowWhenPluginNameIsNullOrWhitespace()
{
// Arrange
var aiFunction = new TestAIFunction("TestFunction");
AIFunctionKernelFunction original = new(aiFunction);
// Act & Assert
Assert.Throws<ArgumentException>(() => original.Clone(string.Empty));
Assert.Throws<ArgumentException>(() => original.Clone(" "));
}
private sealed class TestAIFunction : AIFunction
{
public bool WasInvoked { get; private set; }
public TestAIFunction(string name, string description = "")
{
this.Name = name;
this.Description = description;
}
public override string Name { get; }
public override string Description { get; }
protected override ValueTask<object?> InvokeCoreAsync(AIFunctionArguments? arguments = null, CancellationToken cancellationToken = default)
{
this.WasInvoked = true;
return ValueTask.FromResult<object?>("Test result");
}
}
private sealed class TestAIFunctionWithSchema : AIFunction
{
private readonly JsonElement _schema;
public TestAIFunctionWithSchema(string name, string jsonSchema)
{
this.Name = name;
this._schema = JsonDocument.Parse(jsonSchema).RootElement.Clone();
}
public override string Name { get; }
public override JsonElement JsonSchema => this._schema;
protected override ValueTask<object?> InvokeCoreAsync(AIFunctionArguments? arguments = null, CancellationToken cancellationToken = default)
{
return ValueTask.FromResult<object?>("Test result");
}
}
}