forked from microsoft/semantic-kernel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKernelFunctionFromMethod.cs
1167 lines (1036 loc) · 57.4 KB
/
KernelFunctionFromMethod.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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace Microsoft.SemanticKernel;
/// <summary>
/// Provides factory methods for creating <see cref="KernelFunction"/> instances backed by a .NET method.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
internal sealed partial class KernelFunctionFromMethod : KernelFunction
{
private static readonly Dictionary<Type, Func<string, object>> s_jsonStringParsers = new(12)
{
{ typeof(bool), s => bool.Parse(s) },
{ typeof(int), s => int.Parse(s) },
{ typeof(uint), s => uint.Parse(s) },
{ typeof(long), s => long.Parse(s) },
{ typeof(ulong), s => ulong.Parse(s) },
{ typeof(float), s => float.Parse(s) },
{ typeof(double), s => double.Parse(s) },
{ typeof(decimal), s => decimal.Parse(s) },
{ typeof(short), s => short.Parse(s) },
{ typeof(ushort), s => ushort.Parse(s) },
{ typeof(byte), s => byte.Parse(s) },
{ typeof(sbyte), s => sbyte.Parse(s) }
};
/// <summary>
/// Creates a <see cref="KernelFunction"/> instance for a method, specified via an <see cref="MethodInfo"/> instance
/// and an optional target object if the method is an instance method.
/// </summary>
/// <param name="method">The method to be represented via the created <see cref="KernelFunction"/>.</param>
/// <param name="target">The target object for the <paramref name="method"/> if it represents an instance method. This should be null if and only if <paramref name="method"/> is a static method.</param>
/// <param name="functionName">The name to use for the function. If null, it will default to one derived from the method represented by <paramref name="method"/>.</param>
/// <param name="description">The description to use for the function. If null, it will default to one derived from the method represented by <paramref name="method"/>, if possible (e.g. via a <see cref="DescriptionAttribute"/> on the method).</param>
/// <param name="parameters">Optional parameter descriptions. If null, it will default to one derived from the method represented by <paramref name="method"/>.</param>
/// <param name="returnParameter">Optional return parameter description. If null, it will default to one derived from the method represented by <paramref name="method"/>.</param>
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/> to use for logging. If null, no logging will be performed.</param>
/// <returns>The created <see cref="KernelFunction"/> wrapper for <paramref name="method"/>.</returns>
[RequiresUnreferencedCode("Uses reflection to handle various aspects of the function creation and invocation, making it incompatible with AOT scenarios.")]
[RequiresDynamicCode("Uses reflection to handle various aspects of the function creation and invocation, making it incompatible with AOT scenarios.")]
public static KernelFunction Create(
MethodInfo method,
object? target = null,
string? functionName = null,
string? description = null,
IEnumerable<KernelParameterMetadata>? parameters = null,
KernelReturnParameterMetadata? returnParameter = null,
ILoggerFactory? loggerFactory = null)
{
return Create(
method,
target,
new KernelFunctionFromMethodOptions
{
FunctionName = functionName,
Description = description,
Parameters = parameters,
ReturnParameter = returnParameter,
LoggerFactory = loggerFactory
});
}
/// <summary>
/// Creates a <see cref="KernelFunction"/> instance for a method, specified via an <see cref="MethodInfo"/> instance
/// and an optional target object if the method is an instance method.
/// </summary>
/// <param name="method">The method to be represented via the created <see cref="KernelFunction"/>.</param>
/// <param name="jsonSerializerOptions">The <see cref="JsonSerializerOptions"/> to use for serialization and deserialization of various aspects of the function.</param>
/// <param name="target">The target object for the <paramref name="method"/> if it represents an instance method. This should be null if and only if <paramref name="method"/> is a static method.</param>
/// <param name="functionName">The name to use for the function. If null, it will default to one derived from the method represented by <paramref name="method"/>.</param>
/// <param name="description">The description to use for the function. If null, it will default to one derived from the method represented by <paramref name="method"/>, if possible (e.g. via a <see cref="DescriptionAttribute"/> on the method).</param>
/// <param name="parameters">Optional parameter descriptions. If null, it will default to one derived from the method represented by <paramref name="method"/>.</param>
/// <param name="returnParameter">Optional return parameter description. If null, it will default to one derived from the method represented by <paramref name="method"/>.</param>
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/> to use for logging. If null, no logging will be performed.</param>
/// <returns>The created <see cref="KernelFunction"/> wrapper for <paramref name="method"/>.</returns>
public static KernelFunction Create(
MethodInfo method,
JsonSerializerOptions jsonSerializerOptions,
object? target = null,
string? functionName = null,
string? description = null,
IEnumerable<KernelParameterMetadata>? parameters = null,
KernelReturnParameterMetadata? returnParameter = null,
ILoggerFactory? loggerFactory = null)
{
return Create(
method,
jsonSerializerOptions,
target,
new KernelFunctionFromMethodOptions
{
FunctionName = functionName,
Description = description,
Parameters = parameters,
ReturnParameter = returnParameter,
LoggerFactory = loggerFactory
});
}
/// <summary>
/// Creates a <see cref="KernelFunction"/> instance for a method, specified via an <see cref="MethodInfo"/> instance
/// and an optional target object if the method is an instance method.
/// </summary>
/// <param name="method">The method to be represented via the created <see cref="KernelFunction"/>.</param>
/// <param name="target">The target object for the <paramref name="method"/> if it represents an instance method. This should be null if and only if <paramref name="method"/> is a static method.</param>
/// <param name="options">Optional function creation options.</param>
/// <returns>The created <see cref="KernelFunction"/> wrapper for <paramref name="method"/>.</returns>
[RequiresUnreferencedCode("Uses reflection to handle various aspects of the function creation and invocation, making it incompatible with AOT scenarios.")]
[RequiresDynamicCode("Uses reflection to handle various aspects of the function creation and invocation, making it incompatible with AOT scenarios.")]
public static KernelFunction Create(
MethodInfo method,
object? target = null,
KernelFunctionFromMethodOptions? options = default)
{
Verify.NotNull(method);
if (!method.IsStatic && target is null)
{
throw new ArgumentNullException(nameof(target), "Target must not be null for an instance method.");
}
MethodDetails methodDetails = GetMethodDetails(options?.FunctionName, method, target);
var result = new KernelFunctionFromMethod(
method,
methodDetails.Function,
methodDetails.Name,
options?.Description ?? methodDetails.Description,
options?.Parameters?.ToList() ?? methodDetails.Parameters,
options?.ReturnParameter ?? methodDetails.ReturnParameter,
options?.AdditionalMetadata);
if (options?.LoggerFactory?.CreateLogger(method.DeclaringType ?? typeof(KernelFunctionFromPrompt)) is ILogger logger &&
logger.IsEnabled(LogLevel.Trace))
{
logger.LogTrace("Created KernelFunction '{Name}' for '{MethodName}'", result.Name, method.Name);
}
return result;
}
/// <summary>
/// Creates a <see cref="KernelFunction"/> instance for a method, specified via an <see cref="MethodInfo"/> instance
/// and an optional target object if the method is an instance method.
/// </summary>
/// <param name="method">The method to be represented via the created <see cref="KernelFunction"/>.</param>
/// <param name="jsonSerializerOptions">The <see cref="JsonSerializerOptions"/> to use for serialization and deserialization of various aspects of the function.</param>
/// <param name="target">The target object for the <paramref name="method"/> if it represents an instance method. This should be null if and only if <paramref name="method"/> is a static method.</param>
/// <param name="options">Optional function creation options.</param>
/// <returns>The created <see cref="KernelFunction"/> wrapper for <paramref name="method"/>.</returns>
public static KernelFunction Create(
MethodInfo method,
JsonSerializerOptions jsonSerializerOptions,
object? target = null,
KernelFunctionFromMethodOptions? options = default)
{
Verify.NotNull(method);
Verify.NotNull(jsonSerializerOptions);
if (!method.IsStatic && target is null)
{
throw new ArgumentNullException(nameof(target), "Target must not be null for an instance method.");
}
MethodDetails methodDetails = GetMethodDetails(options?.FunctionName, method, jsonSerializerOptions, target);
var result = new KernelFunctionFromMethod(
method,
methodDetails.Function,
methodDetails.Name,
options?.Description ?? methodDetails.Description,
options?.Parameters?.ToList() ?? methodDetails.Parameters,
options?.ReturnParameter ?? methodDetails.ReturnParameter,
jsonSerializerOptions,
options?.AdditionalMetadata);
if (options?.LoggerFactory?.CreateLogger(method.DeclaringType ?? typeof(KernelFunctionFromPrompt)) is ILogger logger &&
logger.IsEnabled(LogLevel.Trace))
{
logger.LogTrace("Created KernelFunction '{Name}' for '{MethodName}'", result.Name, method.Name);
}
return result;
}
/// <summary>
/// Creates a <see cref="KernelFunctionMetadata"/> instance for a method, specified via an <see cref="MethodInfo"/> instance.
/// </summary>
/// <param name="method">The method to be represented via the created <see cref="KernelFunction"/>.</param>
/// <param name="functionName">The name to use for the function. If null, it will default to one derived from the method represented by <paramref name="method"/>.</param>
/// <param name="description">The description to use for the function. If null, it will default to one derived from the method represented by <paramref name="method"/>, if possible (e.g. via a <see cref="DescriptionAttribute"/> on the method).</param>
/// <param name="parameters">Optional parameter descriptions. If null, it will default to one derived from the method represented by <paramref name="method"/>.</param>
/// <param name="returnParameter">Optional return parameter description. If null, it will default to one derived from the method represented by <paramref name="method"/>.</param>
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/> to use for logging. If null, no logging will be performed.</param>
/// <returns>The created <see cref="KernelFunction"/> wrapper for <paramref name="method"/>.</returns>
[RequiresUnreferencedCode("Uses reflection to handle various aspects of the function creation and invocation, making it incompatible with AOT scenarios.")]
[RequiresDynamicCode("Uses reflection to handle various aspects of the function creation and invocation, making it incompatible with AOT scenarios.")]
public static KernelFunctionMetadata CreateMetadata(
MethodInfo method,
string? functionName = null,
string? description = null,
IEnumerable<KernelParameterMetadata>? parameters = null,
KernelReturnParameterMetadata? returnParameter = null,
ILoggerFactory? loggerFactory = null)
=> CreateMetadata(
method,
new KernelFunctionFromMethodOptions
{
FunctionName = functionName,
Description = description,
Parameters = parameters,
ReturnParameter = returnParameter,
LoggerFactory = loggerFactory
});
/// <summary>
/// Creates a <see cref="KernelFunctionMetadata"/> instance for a method, specified via an <see cref="MethodInfo"/> instance.
/// </summary>
/// <param name="method">The method to be represented via the created <see cref="KernelFunction"/>.</param>
/// <param name="jsonSerializerOptions">The <see cref="JsonSerializerOptions"/> to use for serialization and deserialization of various aspects of the function.</param>
/// <param name="functionName">The name to use for the function. If null, it will default to one derived from the method represented by <paramref name="method"/>.</param>
/// <param name="description">The description to use for the function. If null, it will default to one derived from the method represented by <paramref name="method"/>, if possible (e.g. via a <see cref="DescriptionAttribute"/> on the method).</param>
/// <param name="parameters">Optional parameter descriptions. If null, it will default to one derived from the method represented by <paramref name="method"/>.</param>
/// <param name="returnParameter">Optional return parameter description. If null, it will default to one derived from the method represented by <paramref name="method"/>.</param>
/// <param name="loggerFactory">The <see cref="ILoggerFactory"/> to use for logging. If null, no logging will be performed.</param>
/// <returns>The created <see cref="KernelFunction"/> wrapper for <paramref name="method"/>.</returns>
public static KernelFunctionMetadata CreateMetadata(
MethodInfo method,
JsonSerializerOptions jsonSerializerOptions,
string? functionName = null,
string? description = null,
IEnumerable<KernelParameterMetadata>? parameters = null,
KernelReturnParameterMetadata? returnParameter = null,
ILoggerFactory? loggerFactory = null)
=> CreateMetadata(
method,
jsonSerializerOptions,
new KernelFunctionFromMethodOptions
{
FunctionName = functionName,
Description = description,
Parameters = parameters,
ReturnParameter = returnParameter,
LoggerFactory = loggerFactory
});
/// <summary>
/// Creates a <see cref="KernelFunctionMetadata"/> instance for a method, specified via an <see cref="MethodInfo"/> instance.
/// </summary>
/// <param name="method">The method to be represented via the created <see cref="KernelFunction"/>.</param>
/// <param name="options">Optional function creation options.</param>
/// <returns>The created <see cref="KernelFunction"/> wrapper for <paramref name="method"/>.</returns>
[RequiresUnreferencedCode("Uses reflection to handle various aspects of the function creation and invocation, making it incompatible with AOT scenarios.")]
[RequiresDynamicCode("Uses reflection to handle various aspects of the function creation and invocation, making it incompatible with AOT scenarios.")]
public static KernelFunctionMetadata CreateMetadata(
MethodInfo method,
KernelFunctionFromMethodOptions? options = default)
{
Verify.NotNull(method);
MethodDetails methodDetails = GetMethodDetails(options?.FunctionName, method, null);
var result = new KernelFunctionFromMethod(
method,
methodDetails.Function,
methodDetails.Name,
options?.Description ?? methodDetails.Description,
options?.Parameters?.ToList() ?? methodDetails.Parameters,
options?.ReturnParameter ?? methodDetails.ReturnParameter,
options?.AdditionalMetadata);
if (options?.LoggerFactory?.CreateLogger(method.DeclaringType ?? typeof(KernelFunctionFromPrompt)) is ILogger logger &&
logger.IsEnabled(LogLevel.Trace))
{
logger.LogTrace("Created KernelFunctionMetadata '{Name}' for '{MethodName}'", result.Name, method.Name);
}
return result.Metadata;
}
/// <summary>
/// Creates a <see cref="KernelFunctionMetadata"/> instance for a method, specified via an <see cref="MethodInfo"/> instance.
/// </summary>
/// <param name="method">The method to be represented via the created <see cref="KernelFunction"/>.</param>
/// <param name="jsonSerializerOptions">The <see cref="JsonSerializerOptions"/> to use for serialization and deserialization of various aspects of the function.</param>
/// <param name="options">Optional function creation options.</param>
/// <returns>The created <see cref="KernelFunction"/> wrapper for <paramref name="method"/>.</returns>
public static KernelFunctionMetadata CreateMetadata(
MethodInfo method,
JsonSerializerOptions jsonSerializerOptions,
KernelFunctionFromMethodOptions? options = default)
{
Verify.NotNull(method);
MethodDetails methodDetails = GetMethodDetails(options?.FunctionName, method, jsonSerializerOptions, target: null);
var result = new KernelFunctionFromMethod(
method,
methodDetails.Function,
methodDetails.Name,
options?.Description ?? methodDetails.Description,
options?.Parameters?.ToList() ?? methodDetails.Parameters,
options?.ReturnParameter ?? methodDetails.ReturnParameter,
jsonSerializerOptions,
options?.AdditionalMetadata);
if (options?.LoggerFactory?.CreateLogger(method.DeclaringType ?? typeof(KernelFunctionFromPrompt)) is ILogger logger &&
logger.IsEnabled(LogLevel.Trace))
{
logger.LogTrace("Created KernelFunctionMetadata '{Name}' for '{MethodName}'", result.Name, method.Name);
}
return result.Metadata;
}
/// <inheritdoc/>
protected override ValueTask<FunctionResult> InvokeCoreAsync(
Kernel kernel,
KernelArguments arguments,
CancellationToken cancellationToken)
{
return this._function(kernel, this, arguments, cancellationToken);
}
/// <inheritdoc/>
protected override async IAsyncEnumerable<TResult> InvokeStreamingCoreAsync<TResult>(
Kernel kernel,
KernelArguments arguments,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
FunctionResult functionResult = await this.InvokeCoreAsync(kernel, arguments, cancellationToken).ConfigureAwait(false);
if (functionResult.Value is TResult result)
{
yield return result;
yield break;
}
// If the function returns an IAsyncEnumerable<T>, we can stream the results directly.
// This helps to enable composition, with a KernelFunctionFromMethod that returns an
// Invoke{Prompt}StreamingAsync and returns its result enumerable directly.
if (functionResult.Value is IAsyncEnumerable<TResult> asyncEnumerable)
{
await foreach (TResult item in asyncEnumerable.WithCancellation(cancellationToken).ConfigureAwait(false))
{
yield return item;
}
yield break;
}
// Supports the following provided T types for Method streaming
if (typeof(TResult) == typeof(StreamingKernelContent) ||
typeof(TResult) == typeof(StreamingMethodContent))
{
if (functionResult.Value is not null)
{
yield return (TResult)(object)new StreamingMethodContent(functionResult.Value, functionResult.Metadata);
}
yield break;
}
throw new NotSupportedException($"Streaming function {this.Name} does not support type {typeof(TResult)}");
}
/// <inheritdoc/>
public override KernelFunction Clone(string pluginName)
{
Verify.NotNullOrWhiteSpace(pluginName, nameof(pluginName));
if (base.JsonSerializerOptions is not null)
{
return new KernelFunctionFromMethod(
this.UnderlyingMethod!,
this._function,
this.Name,
pluginName,
this.Description,
this.Metadata.Parameters,
this.Metadata.ReturnParameter,
base.JsonSerializerOptions,
this.Metadata.AdditionalProperties);
}
[UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "Non AOT scenario.")]
[UnconditionalSuppressMessage("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "Non AOT scenario.")]
KernelFunctionFromMethod Clone()
{
return new KernelFunctionFromMethod(
this.UnderlyingMethod!,
this._function,
this.Name,
pluginName,
this.Description,
this.Metadata.Parameters,
this.Metadata.ReturnParameter,
this.Metadata.AdditionalProperties);
}
return Clone();
}
/// <summary>Delegate used to invoke the underlying delegate.</summary>
private delegate ValueTask<FunctionResult> ImplementationFunc(
Kernel kernel,
KernelFunction function,
KernelArguments arguments,
CancellationToken cancellationToken);
private static readonly object[] s_cancellationTokenNoneArray = [CancellationToken.None];
private readonly ImplementationFunc _function;
private record struct MethodDetails(string Name, string Description, ImplementationFunc Function, List<KernelParameterMetadata> Parameters, KernelReturnParameterMetadata ReturnParameter);
[RequiresUnreferencedCode("Uses reflection to handle various aspects of the function creation and invocation, making it incompatible with AOT scenarios.")]
[RequiresDynamicCode("Uses reflection to handle various aspects of the function creation and invocation, making it incompatible with AOT scenarios.")]
private KernelFunctionFromMethod(
MethodInfo method,
ImplementationFunc implementationFunc,
string functionName,
string description,
IReadOnlyList<KernelParameterMetadata> parameters,
KernelReturnParameterMetadata returnParameter,
ReadOnlyDictionary<string, object?>? additionalMetadata = null) :
this(method, implementationFunc, functionName, null, description, parameters, returnParameter, additionalMetadata)
{
}
private KernelFunctionFromMethod(
MethodInfo method,
ImplementationFunc implementationFunc,
string functionName,
string description,
IReadOnlyList<KernelParameterMetadata> parameters,
KernelReturnParameterMetadata returnParameter,
JsonSerializerOptions jsonSerializerOptions,
ReadOnlyDictionary<string, object?>? additionalMetadata = null) :
this(method, implementationFunc, functionName, null, description, parameters, returnParameter, jsonSerializerOptions, additionalMetadata)
{
}
[RequiresUnreferencedCode("Uses reflection to handle various aspects of the function creation and invocation, making it incompatible with AOT scenarios.")]
[RequiresDynamicCode("Uses reflection to handle various aspects of the function creation and invocation, making it incompatible with AOT scenarios.")]
private KernelFunctionFromMethod(
MethodInfo method,
ImplementationFunc implementationFunc,
string functionName,
string? pluginName,
string description,
IReadOnlyList<KernelParameterMetadata> parameters,
KernelReturnParameterMetadata returnParameter,
ReadOnlyDictionary<string, object?>? additionalMetadata = null) :
base(functionName, pluginName, description, parameters, returnParameter, additionalMetadata: additionalMetadata)
{
Verify.ValidFunctionName(functionName);
this._function = implementationFunc;
this.UnderlyingMethod = method;
}
private KernelFunctionFromMethod(
MethodInfo method,
ImplementationFunc implementationFunc,
string functionName,
string? pluginName,
string description,
IReadOnlyList<KernelParameterMetadata> parameters,
KernelReturnParameterMetadata returnParameter,
JsonSerializerOptions jsonSerializerOptions,
ReadOnlyDictionary<string, object?>? additionalMetadata = null) :
base(functionName, pluginName, description, parameters, jsonSerializerOptions, returnParameter, additionalMetadata: additionalMetadata)
{
Verify.ValidFunctionName(functionName);
this._function = implementationFunc;
this.UnderlyingMethod = method;
}
[UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "This method is AOT save.")]
[UnconditionalSuppressMessage("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "This method is AOT safe.")]
private static MethodDetails GetMethodDetails(string? functionName, MethodInfo method, JsonSerializerOptions jsonSerializerOptions, object? target)
{
Verify.NotNull(jsonSerializerOptions);
return GetMethodDetails(functionName, method, target, jsonSerializerOptions);
}
[RequiresUnreferencedCode("Uses reflection to handle various aspects of the function creation and invocation, making it incompatible with AOT scenarios.")]
[RequiresDynamicCode("Uses reflection to handle various aspects of the function creation and invocation, making it incompatible with AOT scenarios.")]
private static MethodDetails GetMethodDetails(string? functionName, MethodInfo method, object? target, JsonSerializerOptions? jsonSerializerOptions = null)
{
ThrowForInvalidSignatureIf(method.ContainsGenericParameters, method, "Open generic methods are not supported");
if (functionName is null)
{
// Get the name to use for the function. If the function has a KernelFunction attribute and it contains a name, we use that.
// Otherwise, we use the name of the method, but strip off any "Async" suffix if it's {Value}Task-returning.
// We don't apply any heuristics to the value supplied by KernelFunction's Name so that it can always be used
// as a definitive override.
functionName = method.GetCustomAttribute<KernelFunctionAttribute>(inherit: true)?.Name?.Trim();
if (string.IsNullOrEmpty(functionName))
{
functionName = SanitizeMetadataName(method.Name!);
if (IsAsyncMethod(method) &&
functionName.EndsWith("Async", StringComparison.Ordinal) &&
functionName.Length > "Async".Length)
{
functionName = functionName.Substring(0, functionName.Length - "Async".Length);
}
}
}
Verify.ValidFunctionName(functionName);
// Build up a list of KernelParameterMetadata for the parameters we expect to be populated
// from arguments. Some arguments are populated specially, not from arguments, and thus
// we don't want to advertize their metadata, e.g. CultureInfo, ILoggerFactory, etc.
List<KernelParameterMetadata> argParameterViews = [];
// Get marshaling funcs for parameters and build up the parameter metadata.
var parameters = method.GetParameters();
var parameterFuncs = new Func<KernelFunction, Kernel, KernelArguments, CancellationToken, object?>[parameters.Length];
bool sawFirstParameter = false;
for (int i = 0; i < parameters.Length; i++)
{
(parameterFuncs[i], KernelParameterMetadata? parameterView) = GetParameterMarshalerDelegate(method, parameters[i], ref sawFirstParameter, jsonSerializerOptions);
if (parameterView is not null)
{
argParameterViews.Add(parameterView);
}
}
// Check for param names conflict
Verify.ParametersUniqueness(argParameterViews);
// Get the return type and a marshaling func for the return value.
(Type returnType, Func<Kernel, KernelFunction, object?, ValueTask<FunctionResult>> returnFunc) = GetReturnValueMarshalerDelegate(method);
if (Nullable.GetUnderlyingType(returnType) is Type underlying)
{
// Unwrap the U from a Nullable<U> since everything is going through object, at which point Nullable<U> and a boxed U are indistinguishable.
returnType = underlying;
}
// Create the func
ValueTask<FunctionResult> Function(Kernel kernel, KernelFunction function, KernelArguments arguments, CancellationToken cancellationToken)
{
// Create the arguments.
object?[] args = parameterFuncs.Length != 0 ? new object?[parameterFuncs.Length] : [];
for (int i = 0; i < args.Length; i++)
{
args[i] = parameterFuncs[i](function, kernel, arguments, cancellationToken);
}
// Invoke the method.
object? result = Invoke(method, target, args);
// Extract and return the result.
return returnFunc(kernel, function, result);
}
KernelReturnParameterMetadata returnParameterMetadata;
if (jsonSerializerOptions is not null)
{
returnParameterMetadata = new KernelReturnParameterMetadata(jsonSerializerOptions)
{
ParameterType = returnType,
Description = method.ReturnParameter.GetCustomAttribute<DescriptionAttribute>(inherit: true)?.Description,
};
}
else
{
returnParameterMetadata = new KernelReturnParameterMetadata()
{
ParameterType = returnType,
Description = method.ReturnParameter.GetCustomAttribute<DescriptionAttribute>(inherit: true)?.Description,
};
}
// And return the details.
return new MethodDetails
{
Function = Function,
Name = functionName!,
Description = method.GetCustomAttribute<DescriptionAttribute>(inherit: true)?.Description ?? "",
Parameters = argParameterViews,
ReturnParameter = returnParameterMetadata
};
}
/// <summary>Gets whether a method has a known async return type.</summary>
private static bool IsAsyncMethod(MethodInfo method)
{
Type t = method.ReturnType;
if (t == typeof(Task) || t == typeof(ValueTask))
{
return true;
}
if (t.IsGenericType)
{
t = t.GetGenericTypeDefinition();
if (t == typeof(Task<>) || t == typeof(ValueTask<>) || t == typeof(IAsyncEnumerable<>))
{
return true;
}
}
return false;
}
/// <summary>
/// Gets a delegate for handling the marshaling of a parameter.
/// </summary>
[RequiresUnreferencedCode("Uses reflection to handle various aspects of the function creation and invocation, making it incompatible with AOT scenarios.")]
[RequiresDynamicCode("Uses reflection to handle various aspects of the function creation and invocation, making it incompatible with AOT scenarios.")]
private static (Func<KernelFunction, Kernel, KernelArguments, CancellationToken, object?>, KernelParameterMetadata?) GetParameterMarshalerDelegate(
MethodInfo method, ParameterInfo parameter, ref bool sawFirstParameter, JsonSerializerOptions? jsonSerializerOptions)
{
Type type = parameter.ParameterType;
// Handle special types.
// These are not reported as part of KernelParameterMetadata because they're not satisfied from arguments.
if (type == typeof(KernelFunction))
{
return (static (KernelFunction func, Kernel _, KernelArguments _, CancellationToken _) => func, null);
}
if (type == typeof(Kernel))
{
return (static (KernelFunction _, Kernel kernel, KernelArguments _, CancellationToken _) => kernel, null);
}
if (type == typeof(KernelArguments))
{
return (static (KernelFunction _, Kernel _, KernelArguments arguments, CancellationToken _) => arguments, null);
}
if (type == typeof(ILoggerFactory))
{
return ((KernelFunction _, Kernel kernel, KernelArguments _, CancellationToken _) => kernel.LoggerFactory, null);
}
if (type == typeof(ILogger))
{
return ((KernelFunction _, Kernel kernel, KernelArguments _, CancellationToken _) => kernel.LoggerFactory.CreateLogger(method?.DeclaringType ?? typeof(KernelFunctionFromPrompt)) ?? NullLogger.Instance, null);
}
if (type == typeof(IAIServiceSelector))
{
return ((KernelFunction _, Kernel kernel, KernelArguments _, CancellationToken _) => kernel.ServiceSelector, null);
}
if (type == typeof(CultureInfo) || type == typeof(IFormatProvider))
{
return (static (KernelFunction _, Kernel kernel, KernelArguments _, CancellationToken _) => kernel.Culture, null);
}
if (type == typeof(CancellationToken))
{
return (static (KernelFunction _, Kernel _, KernelArguments _, CancellationToken cancellationToken) => cancellationToken, null);
}
// Handle the special FromKernelServicesAttribute, which indicates that the parameter should be sourced from the kernel's services.
// As with the above, these are not reported as part of KernelParameterMetadata because they're not satisfied from arguments.
if (parameter.GetCustomAttribute<FromKernelServicesAttribute>() is FromKernelServicesAttribute fromKernelAttr)
{
return ((KernelFunction _, Kernel kernel, KernelArguments _, CancellationToken _) =>
{
// Try to resolve the service from kernel.Services, using the attribute's key if one was provided.
object? service = kernel.Services is IKeyedServiceProvider keyedServiceProvider ?
keyedServiceProvider.GetKeyedService(type, fromKernelAttr.ServiceKey) :
kernel.Services.GetService(type);
if (service is not null)
{
return service;
}
// The service wasn't available. If the parameter has a default value (typically null), use that.
if (parameter.HasDefaultValue)
{
return parameter.DefaultValue;
}
// Otherwise, fail.
throw new KernelException($"Missing service for function parameter '{parameter.Name}'",
new ArgumentException("Missing service for function parameter", parameter.Name));
}, null);
}
// Handle parameters to be satisfied from KernelArguments.
string name = SanitizeMetadataName(parameter.Name ?? "");
ThrowForInvalidSignatureIf(string.IsNullOrWhiteSpace(name), method, $"Parameter {parameter.Name}'s attribute defines an invalid name.");
var converter = GetConverter(type);
object? parameterFunc(KernelFunction _, Kernel kernel, KernelArguments arguments, CancellationToken __)
{
// 1. Use the value of the variable if it exists.
if (arguments.TryGetValue(name, out object? value))
{
return Process(value);
}
// 2. Otherwise, use the default value if there is one, sourced either from an attribute or the parameter's default.
if (parameter.HasDefaultValue)
{
return parameter.DefaultValue;
}
// 3. Otherwise, fail.
throw new KernelException($"Missing argument for function parameter '{name}'",
new ArgumentException("Missing argument for function parameter", name));
object? Process(object? value)
{
if (type.IsAssignableFrom(value?.GetType()))
{
return value;
}
if (converter is not null && value is not JsonElement or JsonDocument or JsonNode)
{
try
{
return converter(value, kernel.Culture);
}
catch (Exception e) when (!e.IsCriticalException())
{
throw new ArgumentOutOfRangeException(name, value, e.Message);
}
}
if (value is JsonElement element && element.ValueKind == JsonValueKind.String
&& s_jsonStringParsers.TryGetValue(type, out var jsonStringParser))
{
return jsonStringParser(element.GetString()!);
}
if (value is not null && TryToDeserializeValue(value, type, jsonSerializerOptions, out var deserializedValue))
{
return deserializedValue;
}
return value;
}
}
sawFirstParameter = true;
KernelParameterMetadata? parameterView;
if (jsonSerializerOptions is not null)
{
parameterView = new KernelParameterMetadata(name, jsonSerializerOptions)
{
Description = parameter.GetCustomAttribute<DescriptionAttribute>(inherit: true)?.Description,
DefaultValue = parameter.HasDefaultValue ? parameter.DefaultValue?.ToString() : null,
IsRequired = !parameter.IsOptional,
ParameterType = type,
};
}
else
{
parameterView = new KernelParameterMetadata(name)
{
Description = parameter.GetCustomAttribute<DescriptionAttribute>(inherit: true)?.Description,
DefaultValue = parameter.HasDefaultValue ? parameter.DefaultValue?.ToString() : null,
IsRequired = !parameter.IsOptional,
ParameterType = type,
};
}
return (parameterFunc, parameterView);
}
/// <summary>
/// Tries to deserialize the given value into an object of the specified target type.
/// </summary>
/// <param name="value">The value to be deserialized.</param>
/// <param name="targetType">The type of the object to deserialize the value into.</param>
/// <param name="jsonSerializerOptions">The <see cref="JsonSerializerOptions"/> to use for deserialization.</param>
/// <param name="deserializedValue">The deserialized object if the method succeeds; otherwise, null.</param>
/// <returns>true if the value is successfully deserialized; otherwise, false.</returns>
[RequiresUnreferencedCode("Uses reflection to deserialize given value if no source generated metadata provided via JSOs, making it incompatible with AOT scenarios.")]
[RequiresDynamicCode("Uses reflection to deserialize given value if no source generated metadata provided via JSOs, making it incompatible with AOT scenarios.")]
private static bool TryToDeserializeValue(object value, Type targetType, JsonSerializerOptions? jsonSerializerOptions, out object? deserializedValue)
{
try
{
deserializedValue = value switch
{
JsonDocument document => document.Deserialize(targetType, jsonSerializerOptions),
JsonNode node => node.Deserialize(targetType, jsonSerializerOptions),
JsonElement element => element.Deserialize(targetType, jsonSerializerOptions),
// The JSON can be represented by other data types from various libraries. For example, JObject, JToken, and JValue from the Newtonsoft.Json library.
// Since we don't take dependencies on these libraries and don't have access to the types here,
// the only way to deserialize those types is to convert them to a string first by calling the 'ToString' method.
// Attempting to use the 'JsonSerializer.Serialize' method, instead of calling the 'ToString' directly on those types, can lead to unpredictable outcomes.
// For instance, the JObject for { "id": 28 } JSON is serialized into the string "{ "Id": [] }", and the deserialization fails with the
// following exception - "The JSON value could not be converted to System.Int32. Path: $.Id | LineNumber: 0 | BytePositionInLine: 7."
_ => JsonSerializer.Deserialize(value.ToString()!, targetType, jsonSerializerOptions)
};
return true;
}
catch (NotSupportedException)
{
// There is no compatible JsonConverter for targetType or its serializable members.
}
catch (JsonException)
{
// The JSON is invalid.
}
deserializedValue = null;
return false;
}
/// <summary>
/// Gets a delegate for handling the result value of a method, converting it into the <see cref="Task{FunctionResult}"/> to return from the invocation.
/// </summary>
private static (Type ReturnType, Func<Kernel, KernelFunction, object?, ValueTask<FunctionResult>> Marshaler) GetReturnValueMarshalerDelegate(MethodInfo method)
{
// Handle each known return type for the method
Type returnType = method.ReturnType;
// No return value, either synchronous (void) or asynchronous (Task / ValueTask).
if (returnType == typeof(void))
{
return (typeof(void), (static (_, function, _) =>
new ValueTask<FunctionResult>(new FunctionResult(function))));
}
if (returnType == typeof(Task))
{
return (typeof(void), async static (_, function, result) =>
{
await ((Task)ThrowIfNullResult(result)).ConfigureAwait(false);
return new FunctionResult(function);
}
);
}
if (returnType == typeof(ValueTask))
{
return (typeof(void), async static (_, function, result) =>
{
await ((ValueTask)ThrowIfNullResult(result)).ConfigureAwait(false);
return new FunctionResult(function);
}
);
}
// string (which is special as no marshaling is required), either synchronous (string) or asynchronous (Task<string> / ValueTask<string>)
if (returnType == typeof(string))
{
return (typeof(string), static (kernel, function, result) =>
{
var resultString = (string?)result;
return new ValueTask<FunctionResult>(new FunctionResult(function, resultString, kernel.Culture));
}
);
}
if (returnType == typeof(Task<string>))
{
return (typeof(string), async static (kernel, function, result) =>
{
var resultString = await ((Task<string>)ThrowIfNullResult(result)).ConfigureAwait(false);
return new FunctionResult(function, resultString, kernel.Culture);
}
);
}
if (returnType == typeof(ValueTask<string>))
{
return (typeof(string), async static (kernel, function, result) =>
{
var resultString = await ((ValueTask<string>)ThrowIfNullResult(result)).ConfigureAwait(false);
return new FunctionResult(function, resultString, kernel.Culture);
}
);
}
if (returnType == typeof(FunctionResult))
{
return (typeof(object), static (_, function, result) =>
{
var functionResult = (FunctionResult?)result;
return new ValueTask<FunctionResult>(functionResult ?? new FunctionResult(function));
}
);
}
if (returnType == typeof(Task<FunctionResult>))
{
return (typeof(object), async static (_, _, result) =>
{
var functionResult = await ((Task<FunctionResult>)ThrowIfNullResult(result)).ConfigureAwait(false);
return functionResult;
}
);
}
if (returnType == typeof(ValueTask<FunctionResult>))
{
return (typeof(object), async static (_, _, result) =>
{
var functionResult = await ((ValueTask<FunctionResult>)ThrowIfNullResult(result)).ConfigureAwait(false);
return functionResult;
}
);
}
// Asynchronous return types
if (returnType.IsGenericType)
{
// Task<T>
#if NET6_0_OR_GREATER
if (returnType.GetGenericTypeDefinition() == typeof(Task<>) &&
((PropertyInfo)returnType.GetMemberWithSameMetadataDefinitionAs(s_taskGetResultPropertyInfo)) is PropertyInfo taskPropertyInfo &&
taskPropertyInfo.GetGetMethod() is MethodInfo taskResultGetter)
#else
if (returnType.GetGenericTypeDefinition() == typeof(Task<>) &&
returnType.GetProperty("Result", BindingFlags.Public | BindingFlags.Instance)?.GetGetMethod() is MethodInfo taskResultGetter)
#endif
{
return (taskResultGetter.ReturnType, async (kernel, function, result) =>
{
await ((Task)ThrowIfNullResult(result)).ConfigureAwait(false);
var taskResult = Invoke(taskResultGetter, result, null);
return new FunctionResult(function, taskResult, kernel.Culture);
}
);
}
// ValueTask<T>
#if NET6_0_OR_GREATER
if (returnType.GetGenericTypeDefinition() == typeof(ValueTask<>) &&
returnType.GetMemberWithSameMetadataDefinitionAs(s_valueTaskGetAsTaskMethodInfo) is MethodInfo valueTaskAsTask &&
valueTaskAsTask.ReturnType.GetMemberWithSameMetadataDefinitionAs(s_taskGetResultPropertyInfo) is PropertyInfo valueTaskPropertyInfo &&
valueTaskPropertyInfo.GetGetMethod() is MethodInfo asTaskResultGetter)
#else
if (returnType.GetGenericTypeDefinition() == typeof(ValueTask<>) &&
returnType.GetMethod("AsTask", BindingFlags.Public | BindingFlags.Instance) is MethodInfo valueTaskAsTask &&
valueTaskAsTask.ReturnType.GetProperty("Result", BindingFlags.Public | BindingFlags.Instance)?.GetGetMethod() is MethodInfo asTaskResultGetter)
#endif
{
return (asTaskResultGetter.ReturnType, async (kernel, function, result) =>
{
Task task = (Task)Invoke(valueTaskAsTask, ThrowIfNullResult(result), null)!;
await task.ConfigureAwait(false);
var taskResult = Invoke(asTaskResultGetter, task, null);
return new FunctionResult(function, taskResult, kernel.Culture);
}
);
}
// IAsyncEnumerable<T>
if (returnType.GetGenericTypeDefinition() == typeof(IAsyncEnumerable<>))
{
#if NET6_0_OR_GREATER
//typeof(IAsyncEnumerable<>).GetMethod("GetAsyncEnumerator")!;
MethodInfo? getAsyncEnumeratorMethod = returnType.GetMemberWithSameMetadataDefinitionAs(s_asyncEnumerableGetAsyncEnumeratorMethodInfo) as MethodInfo;
#else
Type elementType = returnType.GetGenericArguments()[0];
MethodInfo? getAsyncEnumeratorMethod = typeof(IAsyncEnumerable<>)
.MakeGenericType(elementType)
.GetMethod("GetAsyncEnumerator");
#endif
if (getAsyncEnumeratorMethod is not null)
{
return (returnType, (kernel, function, result) =>
{
var asyncEnumerator = Invoke(getAsyncEnumeratorMethod, result, s_cancellationTokenNoneArray);