-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
KernelFunctionFromPromptTests.cs
701 lines (570 loc) · 35 KB
/
KernelFunctionFromPromptTests.cs
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using Microsoft.SemanticKernel.TextGeneration;
using Moq;
using Xunit;
// ReSharper disable StringLiteralTypo
namespace SemanticKernel.UnitTests.Functions;
public class KernelFunctionFromPromptTests
{
[Fact]
public void ItAddsMissingVariablesForPrompt()
{
// Arrange & Act
var function = KernelFunctionFromPrompt.Create("This {{$x11}} {{$a}}{{$missing}} test template {{p.bar $b}} and {{p.foo c='literal \"c\"' d = $d}} and {{p.baz ename=$e}}");
// Assert
Assert.NotNull(function);
Assert.NotNull(function.Metadata);
Assert.NotNull(function.Metadata.Parameters);
Assert.Equal(6, function.Metadata.Parameters.Count);
Assert.Equal("x11", function.Metadata.Parameters[0].Name);
Assert.Equal("a", function.Metadata.Parameters[1].Name);
Assert.Equal("missing", function.Metadata.Parameters[2].Name);
Assert.Equal("b", function.Metadata.Parameters[3].Name);
Assert.Equal("d", function.Metadata.Parameters[4].Name);
Assert.Equal("e", function.Metadata.Parameters[5].Name);
}
[Fact]
public void ItProvidesAccessToFunctionsViaFunctionCollection()
{
// Arrange
var factory = new Mock<Func<IServiceProvider, ITextGenerationService>>();
IKernelBuilder builder = Kernel.CreateBuilder();
builder.Services.AddSingleton(factory.Object);
Kernel kernel = builder.Build();
kernel.ImportPluginFromFunctions("jk", functions: [kernel.CreateFunctionFromPrompt(promptTemplate: "Tell me a joke", functionName: "joker", description: "Nice fun")]);
// Act & Assert - 3 functions, var name is not case sensitive
Assert.True(kernel.Plugins.TryGetFunction("jk", "joker", out _));
Assert.True(kernel.Plugins.TryGetFunction("JK", "JOKER", out _));
}
[Theory]
[InlineData(null, null)]
[InlineData("My Chat Prompt", "My Chat Prompt")]
public async Task ItUsesChatSystemPromptWhenProvidedAsync(string? providedSystemChatPrompt, string? expectedSystemChatPrompt)
{
// Arrange
var mockTextGeneration = new Mock<ITextGenerationService>();
var fakeTextContent = new TextContent("llmResult");
mockTextGeneration.Setup(c => c.GetTextContentsAsync(It.IsAny<string>(), It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>())).ReturnsAsync([fakeTextContent]);
IKernelBuilder builder = Kernel.CreateBuilder();
builder.Services.AddKeyedSingleton("x", mockTextGeneration.Object);
Kernel kernel = builder.Build();
var openAIExecutionSettings = providedSystemChatPrompt is null
? new OpenAIPromptExecutionSettings()
: new OpenAIPromptExecutionSettings
{
ChatSystemPrompt = providedSystemChatPrompt
};
var promptConfig = new PromptTemplateConfig("template");
promptConfig.AddExecutionSettings(openAIExecutionSettings);
var func = kernel.CreateFunctionFromPrompt(promptConfig);
// Act
await kernel.InvokeAsync(func);
// Assert
mockTextGeneration.Verify(a => a.GetTextContentsAsync("template", It.Is<OpenAIPromptExecutionSettings>(c => c.ChatSystemPrompt == expectedSystemChatPrompt), It.IsAny<Kernel>(), It.IsAny<CancellationToken>()), Times.Once());
}
[Fact]
public async Task ItUsesServiceIdWhenProvidedAsync()
{
// Arrange
var mockTextGeneration1 = new Mock<ITextGenerationService>();
var mockTextGeneration2 = new Mock<ITextGenerationService>();
var fakeTextContent = new TextContent("llmResult");
mockTextGeneration1.Setup(c => c.GetTextContentsAsync(It.IsAny<string>(), It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>())).ReturnsAsync([fakeTextContent]);
mockTextGeneration2.Setup(c => c.GetTextContentsAsync(It.IsAny<string>(), It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>())).ReturnsAsync([fakeTextContent]);
IKernelBuilder builder = Kernel.CreateBuilder();
builder.Services.AddKeyedSingleton("service1", mockTextGeneration1.Object);
builder.Services.AddKeyedSingleton("service2", mockTextGeneration2.Object);
Kernel kernel = builder.Build();
var promptConfig = new PromptTemplateConfig("template");
promptConfig.AddExecutionSettings(new PromptExecutionSettings(), "service1");
var func = kernel.CreateFunctionFromPrompt(promptConfig);
// Act
await kernel.InvokeAsync(func);
// Assert
mockTextGeneration1.Verify(a => a.GetTextContentsAsync("template", It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>()), Times.Once());
mockTextGeneration2.Verify(a => a.GetTextContentsAsync("template", It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>()), Times.Never());
}
[Fact]
public async Task ItFailsIfInvalidServiceIdIsProvidedAsync()
{
// Arrange
var mockTextGeneration1 = new Mock<ITextGenerationService>();
var mockTextGeneration2 = new Mock<ITextGenerationService>();
IKernelBuilder builder = Kernel.CreateBuilder();
builder.Services.AddKeyedSingleton("service1", mockTextGeneration1.Object);
builder.Services.AddKeyedSingleton("service2", mockTextGeneration2.Object);
Kernel kernel = builder.Build();
var promptConfig = new PromptTemplateConfig("template");
promptConfig.AddExecutionSettings(new PromptExecutionSettings(), "service3");
var func = kernel.CreateFunctionFromPrompt(promptConfig);
// Act
var exception = await Assert.ThrowsAsync<KernelException>(() => kernel.InvokeAsync(func));
// Assert
Assert.Equal("Required service of type Microsoft.SemanticKernel.TextGeneration.ITextGenerationService not registered. Expected serviceIds: service3.", exception.Message);
}
[Fact]
public async Task ItParsesStandardizedPromptWhenServiceIsChatCompletionAsync()
{
var fakeService = new FakeChatAsTextService();
IKernelBuilder builder = Kernel.CreateBuilder();
builder.Services.AddTransient<ITextGenerationService>((sp) => fakeService);
Kernel kernel = builder.Build();
KernelFunction function = KernelFunctionFactory.CreateFromPrompt("""
<message role="system">You are a helpful assistant.</message>
<message role="user">How many 20 cents can I get from 1 dollar?</message>
""");
// Act + Assert
await kernel.InvokeAsync(function);
Assert.NotNull(fakeService.ChatHistory);
Assert.Equal(2, fakeService.ChatHistory.Count);
Assert.Equal("You are a helpful assistant.", fakeService.ChatHistory[0].Content);
Assert.Equal("How many 20 cents can I get from 1 dollar?", fakeService.ChatHistory[1].Content);
}
[Fact]
public async Task ItParsesStandardizedPromptWhenServiceIsStreamingChatCompletionAsync()
{
var fakeService = new FakeChatAsTextService();
IKernelBuilder builder = Kernel.CreateBuilder();
builder.Services.AddTransient<ITextGenerationService>((sp) => fakeService);
Kernel kernel = builder.Build();
KernelFunction function = KernelFunctionFactory.CreateFromPrompt("""
<message role="system">You are a helpful assistant.</message>
<message role="user">How many 20 cents can I get from 1 dollar?</message>
""");
// Act + Assert
await foreach (var chunk in kernel.InvokeStreamingAsync(function))
{
}
Assert.NotNull(fakeService.ChatHistory);
Assert.Equal(2, fakeService.ChatHistory.Count);
Assert.Equal("You are a helpful assistant.", fakeService.ChatHistory[0].Content);
Assert.Equal("How many 20 cents can I get from 1 dollar?", fakeService.ChatHistory[1].Content);
}
[Fact]
public async Task ItNotParsesStandardizedPromptWhenServiceIsOnlyTextCompletionAsync()
{
var mockService = new Mock<ITextGenerationService>();
var mockResult = mockService.Setup(s => s.GetTextContentsAsync(It.IsAny<string>(), It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>()))
.ReturnsAsync([new("something")]);
IKernelBuilder builder = Kernel.CreateBuilder();
builder.Services.AddTransient<ITextGenerationService>((sp) => mockService.Object);
Kernel kernel = builder.Build();
var inputPrompt = """
<message role="system">You are a helpful assistant.</message>
<message role="user">How many 20 cents can I get from 1 dollar?</message>
""";
KernelFunction function = KernelFunctionFactory.CreateFromPrompt(inputPrompt);
// Act + Assert
mockResult.Callback((string prompt, PromptExecutionSettings _, Kernel _, CancellationToken _) =>
{
Assert.NotNull(prompt);
Assert.Equal(inputPrompt, prompt);
});
await kernel.InvokeAsync(function);
}
[Fact]
public async Task ItNotParsesStandardizedPromptWhenStreamingWhenServiceIsOnlyTextCompletionAsync()
{
var mockService = new Mock<ITextGenerationService>();
var mockResult = mockService.Setup(s => s.GetStreamingTextContentsAsync(It.IsAny<string>(), It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>()))
.Returns((new List<StreamingTextContent>() { new("something") }).ToAsyncEnumerable());
IKernelBuilder builder = Kernel.CreateBuilder();
builder.Services.AddTransient<ITextGenerationService>((sp) => mockService.Object);
Kernel kernel = builder.Build();
var inputPrompt = """
<message role="system">You are a helpful assistant.</message>
<message role="user">How many 20 cents can I get from 1 dollar?</message>
""";
KernelFunction function = KernelFunctionFactory.CreateFromPrompt(inputPrompt);
// Act + Assert
mockResult.Callback((string prompt, PromptExecutionSettings _, Kernel _, CancellationToken _) =>
{
Assert.NotNull(prompt);
Assert.Equal(inputPrompt, prompt);
});
await foreach (var chunk in kernel.InvokeStreamingAsync(function))
{
}
}
[Fact]
public async Task InvokeAsyncReturnsTheConnectorResultWhenInServiceIsOnlyTextCompletionAsync()
{
var mockService = new Mock<ITextGenerationService>();
var mockResult = mockService.Setup(s => s.GetTextContentsAsync(It.IsAny<string>(), It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>()))
.ReturnsAsync([new("something")]);
KernelBuilder builder = new();
builder.Services.AddTransient<ITextGenerationService>((sp) => mockService.Object);
Kernel kernel = builder.Build();
KernelFunction function = KernelFunctionFactory.CreateFromPrompt("Anything");
var result = await kernel.InvokeAsync(function);
Assert.Equal("something", result.GetValue<string>());
Assert.Equal("something", result.GetValue<TextContent>()!.Text);
Assert.Equal("something", result.GetValue<KernelContent>()!.ToString());
}
[Fact]
public async Task InvokeAsyncReturnsTheConnectorChatResultWhenInServiceIsOnlyChatCompletionAsync()
{
var mockService = new Mock<IChatCompletionService>();
var mockResult = mockService.Setup(s => s.GetChatMessageContentsAsync(It.IsAny<ChatHistory>(), It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>()))
.ReturnsAsync([new(AuthorRole.User, "something")]);
KernelBuilder builder = new();
builder.Services.AddTransient<IChatCompletionService>((sp) => mockService.Object);
Kernel kernel = builder.Build();
KernelFunction function = KernelFunctionFactory.CreateFromPrompt("Anything");
var result = await kernel.InvokeAsync(function);
Assert.Equal("something", result.GetValue<string>());
Assert.Equal("something", result.GetValue<ChatMessageContent>()!.Content);
Assert.Equal(AuthorRole.User, result.GetValue<ChatMessageContent>()!.Role);
Assert.Equal("something", result.GetValue<KernelContent>()!.ToString());
}
[Fact]
public async Task InvokeAsyncReturnsTheConnectorChatResultWhenInServiceIsChatAndTextCompletionAsync()
{
var fakeService = new FakeChatAsTextService();
KernelBuilder builder = new();
builder.Services.AddTransient<ITextGenerationService>((sp) => fakeService);
Kernel kernel = builder.Build();
KernelFunction function = KernelFunctionFactory.CreateFromPrompt("Anything");
var result = await kernel.InvokeAsync(function);
Assert.Equal("Something", result.GetValue<string>());
Assert.Equal("Something", result.GetValue<ChatMessageContent>()!.Content);
Assert.Equal(AuthorRole.Assistant, result.GetValue<ChatMessageContent>()!.Role);
Assert.Equal("Something", result.GetValue<KernelContent>()!.ToString());
}
[Fact]
public async Task InvokeAsyncOfTGivesBackTheExpectedResultTypeFromTheConnectorWhenStreamingWhenServiceIsOnlyTextCompletionAsync()
{
var expectedContent = new StreamingTextContent("something");
var mockService = new Mock<ITextGenerationService>();
var mockResult = mockService.Setup(s => s.GetStreamingTextContentsAsync(It.IsAny<string>(), It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>()))
.Returns((new List<StreamingTextContent>() { expectedContent }).ToAsyncEnumerable());
KernelBuilder builder = new();
builder.Services.AddTransient<ITextGenerationService>((sp) => mockService.Object);
Kernel kernel = builder.Build();
KernelFunction function = KernelFunctionFactory.CreateFromPrompt("Anything");
await foreach (var chunk in kernel.InvokeStreamingAsync<StreamingKernelContent>(function))
{
Assert.Equal(expectedContent, chunk);
}
await foreach (var chunk in kernel.InvokeStreamingAsync<StreamingTextContent>(function))
{
Assert.Equal(expectedContent, chunk);
}
}
[Fact]
public async Task InvokeAsyncOfTGivesBackTheExpectedResultTypeFromTheConnectorWhenStreamingWhenerviceIsOnlyChatCompletionAsync()
{
var expectedContent = new StreamingChatMessageContent(AuthorRole.Assistant, "Something");
var mockService = new Mock<IChatCompletionService>();
var mockResult = mockService.Setup(s => s.GetStreamingChatMessageContentsAsync(It.IsAny<ChatHistory>(), It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>()))
.Returns((new List<StreamingChatMessageContent>() { expectedContent }).ToAsyncEnumerable());
KernelBuilder builder = new();
builder.Services.AddTransient<IChatCompletionService>((sp) => mockService.Object);
Kernel kernel = builder.Build();
KernelFunction function = KernelFunctionFactory.CreateFromPrompt("Anything");
await foreach (var chunk in kernel.InvokeStreamingAsync<StreamingKernelContent>(function))
{
Assert.Equal(expectedContent, chunk);
Assert.Equal("Something", chunk.ToString());
}
await foreach (var chunk in kernel.InvokeStreamingAsync<StreamingChatMessageContent>(function))
{
Assert.Equal(expectedContent, chunk);
Assert.Equal("Something", chunk.Content);
Assert.Equal(AuthorRole.Assistant, chunk.Role);
}
}
[Fact]
public async Task InvokeAsyncOfTGivesBackTheExpectedResultTypeFromTheConnectorWhenStreamingWhenServiceIsTextAndChatCompletionAsync()
{
var fakeService = new FakeChatAsTextService();
KernelBuilder builder = new();
builder.Services.AddTransient<ITextGenerationService>((sp) => fakeService);
Kernel kernel = builder.Build();
KernelFunction function = KernelFunctionFactory.CreateFromPrompt("Anything");
await foreach (var chunk in kernel.InvokeStreamingAsync<StreamingKernelContent>(function))
{
Assert.Equal("Something", chunk.ToString());
}
await foreach (var chunk in kernel.InvokeStreamingAsync<StreamingChatMessageContent>(function))
{
Assert.Equal(AuthorRole.Assistant, chunk.Role);
Assert.Equal("Something", chunk.Content);
}
}
[Fact]
public async Task InvokeAsyncUsesPromptExecutionSettingsAsync()
{
// Arrange
var mockTextContent = new TextContent("Result");
var mockTextCompletion = new Mock<ITextGenerationService>();
mockTextCompletion.Setup(m => m.GetTextContentsAsync(It.IsAny<string>(), It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>())).ReturnsAsync([mockTextContent]);
KernelBuilder builder = new();
builder.Services.AddTransient<ITextGenerationService>((sp) => mockTextCompletion.Object);
Kernel kernel = builder.Build();
KernelFunction function = KernelFunctionFactory.CreateFromPrompt("Anything", new OpenAIPromptExecutionSettings { MaxTokens = 1000 });
// Act
var result = await kernel.InvokeAsync(function);
// Assert
Assert.Equal("Result", result.GetValue<string>());
mockTextCompletion.Verify(m => m.GetTextContentsAsync("Anything", It.Is<OpenAIPromptExecutionSettings>(settings => settings.MaxTokens == 1000), It.IsAny<Kernel>(), It.IsAny<CancellationToken>()), Times.Once());
}
[Fact]
public async Task InvokeAsyncUsesKernelArgumentsExecutionSettingsAsync()
{
// Arrange
var mockTextContent = new TextContent("Result");
var mockTextCompletion = new Mock<ITextGenerationService>();
mockTextCompletion.Setup(m => m.GetTextContentsAsync(It.IsAny<string>(), It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>())).ReturnsAsync([mockTextContent]);
KernelBuilder builder = new();
builder.Services.AddTransient<ITextGenerationService>((sp) => mockTextCompletion.Object);
Kernel kernel = builder.Build();
KernelFunction function = KernelFunctionFactory.CreateFromPrompt("Anything", new OpenAIPromptExecutionSettings { MaxTokens = 1000 });
// Act
var result = await kernel.InvokeAsync(function, new KernelArguments(new OpenAIPromptExecutionSettings { MaxTokens = 2000 }));
// Assert
Assert.Equal("Result", result.GetValue<string>());
mockTextCompletion.Verify(m => m.GetTextContentsAsync("Anything", It.Is<OpenAIPromptExecutionSettings>(settings => settings.MaxTokens == 2000), It.IsAny<Kernel>(), It.IsAny<CancellationToken>()), Times.Once());
}
[Fact]
public async Task InvokeAsyncWithServiceIdUsesKernelArgumentsExecutionSettingsAsync()
{
// Arrange
var mockTextContent = new TextContent("Result");
var mockTextCompletion = new Mock<ITextGenerationService>();
mockTextCompletion.Setup(m => m.GetTextContentsAsync(It.IsAny<string>(), It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>())).ReturnsAsync([mockTextContent]);
KernelBuilder builder = new();
builder.Services.AddKeyedSingleton<ITextGenerationService>("service1", mockTextCompletion.Object);
Kernel kernel = builder.Build();
KernelFunction function = KernelFunctionFactory.CreateFromPrompt("Anything", new OpenAIPromptExecutionSettings { MaxTokens = 1000 });
// Act
var result = await kernel.InvokeAsync(function, new KernelArguments(new OpenAIPromptExecutionSettings { MaxTokens = 2000 }));
// Assert
Assert.Equal("Result", result.GetValue<string>());
mockTextCompletion.Verify(m => m.GetTextContentsAsync("Anything", It.Is<OpenAIPromptExecutionSettings>(settings => settings.MaxTokens == 2000), It.IsAny<Kernel>(), It.IsAny<CancellationToken>()), Times.Once());
}
[Fact]
public async Task InvokeAsyncWithMultipleServicesUsesKernelArgumentsExecutionSettingsAsync()
{
// Arrange
var mockTextContent1 = new TextContent("Result1");
var mockTextCompletion1 = new Mock<ITextGenerationService>();
mockTextCompletion1.Setup(m => m.GetTextContentsAsync(It.IsAny<string>(), It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>())).ReturnsAsync([mockTextContent1]);
var mockTextContent2 = new TextContent("Result2");
var mockTextCompletion2 = new Mock<ITextGenerationService>();
mockTextCompletion2.Setup(m => m.GetTextContentsAsync(It.IsAny<string>(), It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>())).ReturnsAsync([mockTextContent2]);
KernelBuilder builder = new();
builder.Services.AddKeyedSingleton<ITextGenerationService>("service1", mockTextCompletion1.Object);
builder.Services.AddKeyedSingleton<ITextGenerationService>("service2", mockTextCompletion2.Object);
Kernel kernel = builder.Build();
KernelFunction function1 = KernelFunctionFactory.CreateFromPrompt(new PromptTemplateConfig { Template = "Prompt1", ExecutionSettings = new() { ["service1"] = new OpenAIPromptExecutionSettings { MaxTokens = 1000 } } });
KernelFunction function2 = KernelFunctionFactory.CreateFromPrompt(new PromptTemplateConfig { Template = "Prompt2", ExecutionSettings = new() { ["service2"] = new OpenAIPromptExecutionSettings { MaxTokens = 2000 } } });
// Act
var result1 = await kernel.InvokeAsync(function1);
var result2 = await kernel.InvokeAsync(function2);
// Assert
Assert.Equal("Result1", result1.GetValue<string>());
mockTextCompletion1.Verify(m => m.GetTextContentsAsync("Prompt1", It.Is<OpenAIPromptExecutionSettings>(settings => settings.MaxTokens == 1000), It.IsAny<Kernel>(), It.IsAny<CancellationToken>()), Times.Once());
Assert.Equal("Result2", result2.GetValue<string>());
mockTextCompletion2.Verify(m => m.GetTextContentsAsync("Prompt2", It.Is<OpenAIPromptExecutionSettings>(settings => settings.MaxTokens == 2000), It.IsAny<Kernel>(), It.IsAny<CancellationToken>()), Times.Once());
}
[Fact]
public async Task InvokeAsyncWithMultipleServicesUsesServiceFromKernelArgumentsExecutionSettingsAsync()
{
// Arrange
var mockTextContent1 = new TextContent("Result1");
var mockTextCompletion1 = new Mock<ITextGenerationService>();
mockTextCompletion1.Setup(m => m.GetTextContentsAsync(It.IsAny<string>(), It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>())).ReturnsAsync([mockTextContent1]);
var mockTextContent2 = new TextContent("Result2");
var mockTextCompletion2 = new Mock<ITextGenerationService>();
mockTextCompletion2.Setup(m => m.GetTextContentsAsync(It.IsAny<string>(), It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>())).ReturnsAsync([mockTextContent2]);
KernelBuilder builder = new();
builder.Services.AddKeyedSingleton<ITextGenerationService>("service1", mockTextCompletion1.Object);
builder.Services.AddKeyedSingleton<ITextGenerationService>("service2", mockTextCompletion2.Object);
Kernel kernel = builder.Build();
KernelFunction function = KernelFunctionFactory.CreateFromPrompt("Prompt");
// Act
KernelArguments arguments1 = [];
arguments1.ExecutionSettings = new Dictionary<string, PromptExecutionSettings>()
{
{ "service1", new OpenAIPromptExecutionSettings { MaxTokens = 1000 } }
};
var result1 = await kernel.InvokeAsync(function, arguments1);
KernelArguments arguments2 = [];
arguments2.ExecutionSettings = new Dictionary<string, PromptExecutionSettings>()
{
{ "service2", new OpenAIPromptExecutionSettings { MaxTokens = 2000 } }
};
var result2 = await kernel.InvokeAsync(function, arguments2);
// Assert
Assert.Equal("Result1", result1.GetValue<string>());
mockTextCompletion1.Verify(m => m.GetTextContentsAsync("Prompt", It.Is<OpenAIPromptExecutionSettings>(settings => settings.MaxTokens == 1000), It.IsAny<Kernel>(), It.IsAny<CancellationToken>()), Times.Once());
Assert.Equal("Result2", result2.GetValue<string>());
mockTextCompletion2.Verify(m => m.GetTextContentsAsync("Prompt", It.Is<OpenAIPromptExecutionSettings>(settings => settings.MaxTokens == 2000), It.IsAny<Kernel>(), It.IsAny<CancellationToken>()), Times.Once());
}
[Fact]
public async Task InvokeAsyncWithMultipleServicesUsesKernelArgumentsExecutionSettingsOverrideAsync()
{
// Arrange
var mockTextContent1 = new TextContent("Result1");
var mockTextCompletion1 = new Mock<ITextGenerationService>();
mockTextCompletion1.Setup(m => m.GetTextContentsAsync(It.IsAny<string>(), It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>())).ReturnsAsync([mockTextContent1]);
var mockTextContent2 = new TextContent("Result2");
var mockTextCompletion2 = new Mock<ITextGenerationService>();
mockTextCompletion2.Setup(m => m.GetTextContentsAsync(It.IsAny<string>(), It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>())).ReturnsAsync([mockTextContent2]);
KernelBuilder builder = new();
builder.Services.AddKeyedSingleton<ITextGenerationService>("service1", mockTextCompletion1.Object);
builder.Services.AddKeyedSingleton<ITextGenerationService>("service2", mockTextCompletion2.Object);
Kernel kernel = builder.Build();
KernelFunction function1 = KernelFunctionFactory.CreateFromPrompt(new PromptTemplateConfig { Template = "Prompt1", ExecutionSettings = new() { ["service1"] = new OpenAIPromptExecutionSettings { MaxTokens = 1000 } } });
KernelFunction function2 = KernelFunctionFactory.CreateFromPrompt(new PromptTemplateConfig { Template = "Prompt2", ExecutionSettings = new() { ["service2"] = new OpenAIPromptExecutionSettings { MaxTokens = 2000 } } });
// Act
KernelArguments arguments1 = [];
arguments1.ExecutionSettings = new Dictionary<string, PromptExecutionSettings>()
{
{ "service2", new OpenAIPromptExecutionSettings { MaxTokens = 2000 } }
};
var result1 = await kernel.InvokeAsync(function1, arguments1);
KernelArguments arguments2 = [];
arguments2.ExecutionSettings = new Dictionary<string, PromptExecutionSettings>()
{
{ "service1", new OpenAIPromptExecutionSettings { MaxTokens = 1000 } }
};
var result2 = await kernel.InvokeAsync(function2, arguments2);
// Assert
Assert.Equal("Result2", result1.GetValue<string>());
mockTextCompletion2.Verify(m => m.GetTextContentsAsync("Prompt1", It.Is<OpenAIPromptExecutionSettings>(settings => settings.MaxTokens == 2000), It.IsAny<Kernel>(), It.IsAny<CancellationToken>()), Times.Once());
Assert.Equal("Result1", result2.GetValue<string>());
mockTextCompletion1.Verify(m => m.GetTextContentsAsync("Prompt2", It.Is<OpenAIPromptExecutionSettings>(settings => settings.MaxTokens == 1000), It.IsAny<Kernel>(), It.IsAny<CancellationToken>()), Times.Once());
}
[Fact]
public async Task InvokeAsyncWithNestedPromptsSelectsCorrectServiceAsync()
{
// Arrange
var mockTextContent1 = new TextContent("Result1");
var mockTextCompletion1 = new Mock<ITextGenerationService>();
mockTextCompletion1.Setup(m => m.GetTextContentsAsync(It.IsAny<string>(), It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>())).ReturnsAsync([mockTextContent1]);
var mockTextContent2 = new TextContent("Result2");
var mockTextCompletion2 = new Mock<ITextGenerationService>();
mockTextCompletion2.Setup(m => m.GetTextContentsAsync(It.IsAny<string>(), It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>())).ReturnsAsync([mockTextContent2]);
KernelBuilder builder = new();
builder.Services.AddKeyedSingleton<ITextGenerationService>("service1", mockTextCompletion1.Object);
builder.Services.AddKeyedSingleton<ITextGenerationService>("service2", mockTextCompletion2.Object);
Kernel kernel = builder.Build();
KernelFunction function1 = KernelFunctionFactory.CreateFromPrompt(new PromptTemplateConfig { Name = "Prompt1", Template = "Prompt1", ExecutionSettings = new() { ["service1"] = new OpenAIPromptExecutionSettings { MaxTokens = 1000 } } });
KernelFunction function2 = KernelFunctionFactory.CreateFromPrompt(new PromptTemplateConfig { Name = "Prompt2", Template = "Prompt2 {{MyPrompts.Prompt1}}", ExecutionSettings = new() { ["service2"] = new OpenAIPromptExecutionSettings { MaxTokens = 2000 } } });
kernel.ImportPluginFromFunctions("MyPrompts", [function1, function2]);
// Act
var result = await kernel.InvokeAsync(function2);
// Assert
Assert.Equal("Result2", result.GetValue<string>());
mockTextCompletion1.Verify(m => m.GetTextContentsAsync("Prompt1", It.Is<OpenAIPromptExecutionSettings>(settings => settings.MaxTokens == 1000), It.IsAny<Kernel>(), It.IsAny<CancellationToken>()), Times.Once());
mockTextCompletion2.Verify(m => m.GetTextContentsAsync("Prompt2 Result1", It.Is<OpenAIPromptExecutionSettings>(settings => settings.MaxTokens == 2000), It.IsAny<Kernel>(), It.IsAny<CancellationToken>()), Times.Once());
}
[Fact]
public async Task InvokeAsyncWithPromptRenderedHooksExecutesModifiedPromptAsync()
{
// Arrange
var mockTextContent = new TextContent("Result");
var mockTextCompletion = new Mock<ITextGenerationService>();
mockTextCompletion.Setup(m => m.GetTextContentsAsync(It.IsAny<string>(), It.IsAny<PromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>())).ReturnsAsync(new List<TextContent> { mockTextContent });
#pragma warning disable CS0618 // Events are deprecated
static void MyRenderedHandler(object? sender, PromptRenderedEventArgs e)
{
e.RenderedPrompt += " USE SHORT, CLEAR, COMPLETE SENTENCES.";
}
KernelBuilder builder = new();
builder.Services.AddKeyedSingleton<ITextGenerationService>("service", mockTextCompletion.Object);
Kernel kernel = builder.Build();
kernel.PromptRendered += MyRenderedHandler;
#pragma warning restore CS0618 // Events are deprecated
KernelFunction function = KernelFunctionFactory.CreateFromPrompt("Prompt");
// Act
var result1 = await kernel.InvokeAsync(function);
// Assert
mockTextCompletion.Verify(m => m.GetTextContentsAsync("Prompt USE SHORT, CLEAR, COMPLETE SENTENCES.", It.IsAny<OpenAIPromptExecutionSettings>(), It.IsAny<Kernel>(), It.IsAny<CancellationToken>()), Times.Once());
}
[Theory]
[InlineData(KernelInvocationType.InvokePrompt)]
[InlineData(KernelInvocationType.InvokePromptStreaming)]
[InlineData(KernelInvocationType.InvokeFunction)]
[InlineData(KernelInvocationType.InvokeFunctionStreaming)]
public async Task ItUsesPromptAsUserMessageAsync(KernelInvocationType invocationType)
{
// Arrange
const string Prompt = "Test prompt as user message";
var fakeService = new FakeChatAsTextService();
IKernelBuilder builder = Kernel.CreateBuilder();
builder.Services.AddTransient<IChatCompletionService>((sp) => fakeService);
Kernel kernel = builder.Build();
var function = KernelFunctionFactory.CreateFromPrompt(Prompt);
// Act
switch (invocationType)
{
case KernelInvocationType.InvokePrompt:
await kernel.InvokePromptAsync(Prompt);
break;
case KernelInvocationType.InvokePromptStreaming:
await foreach (var result in kernel.InvokePromptStreamingAsync(Prompt)) { }
break;
case KernelInvocationType.InvokeFunction:
await kernel.InvokeAsync(function);
break;
case KernelInvocationType.InvokeFunctionStreaming:
await foreach (var result in kernel.InvokeStreamingAsync(function)) { }
break;
}
// Assert
Assert.NotNull(fakeService.ChatHistory);
Assert.Single(fakeService.ChatHistory);
var messageContent = fakeService.ChatHistory[0];
Assert.Equal(AuthorRole.User, messageContent.Role);
Assert.Equal("Test prompt as user message", messageContent.Content);
}
public enum KernelInvocationType
{
InvokePrompt,
InvokePromptStreaming,
InvokeFunction,
InvokeFunctionStreaming
}
#region private
private sealed class FakeChatAsTextService : ITextGenerationService, IChatCompletionService
{
public IReadOnlyDictionary<string, object?> Attributes => throw new NotImplementedException();
public ChatHistory? ChatHistory { get; private set; }
public Task<IReadOnlyList<ChatMessageContent>> GetChatMessageContentsAsync(ChatHistory chatHistory, PromptExecutionSettings? executionSettings = null, Kernel? kernel = null, CancellationToken cancellationToken = default)
{
this.ChatHistory = chatHistory;
return Task.FromResult<IReadOnlyList<ChatMessageContent>>([new(AuthorRole.Assistant, "Something")]);
}
#pragma warning disable IDE0036 // Order modifiers
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
public async IAsyncEnumerable<StreamingChatMessageContent> GetStreamingChatMessageContentsAsync(ChatHistory chatHistory, PromptExecutionSettings? executionSettings = null, Kernel? kernel = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
#pragma warning restore IDE0036 // Order modifiers
{
this.ChatHistory = chatHistory;
yield return new StreamingChatMessageContent(AuthorRole.Assistant, "Something");
}
public IAsyncEnumerable<StreamingTextContent> GetStreamingTextContentsAsync(string prompt, PromptExecutionSettings? executionSettings = null, Kernel? kernel = null, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
public Task<IReadOnlyList<TextContent>> GetTextContentsAsync(string prompt, PromptExecutionSettings? executionSettings = null, Kernel? kernel = null, CancellationToken cancellationToken = default)
{
throw new NotImplementedException();
}
}
#endregion
}