forked from dotnet/extensions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAIFunctionFactory.cs
536 lines (472 loc) · 27.5 KB
/
AIFunctionFactory.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization.Metadata;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Shared.Collections;
using Microsoft.Shared.Diagnostics;
#pragma warning disable CA1031 // Do not catch general exception types
#pragma warning disable S3011 // Reflection should not be used to increase accessibility of classes, methods, or fields
namespace Microsoft.Extensions.AI;
/// <summary>Provides factory methods for creating commonly used implementations of <see cref="AIFunction"/>.</summary>
public static partial class AIFunctionFactory
{
/// <summary>Holds the default options instance used when creating function.</summary>
private static readonly AIFunctionFactoryOptions _defaultOptions = new();
/// <summary>Creates an <see cref="AIFunction"/> instance for a method, specified via a delegate.</summary>
/// <param name="method">The method to be represented via the created <see cref="AIFunction"/>.</param>
/// <param name="options">Metadata to use to override defaults inferred from <paramref name="method"/>.</param>
/// <returns>The created <see cref="AIFunction"/> for invoking <paramref name="method"/>.</returns>
/// <remarks>
/// <para>
/// Return values are serialized to <see cref="JsonElement"/> using <paramref name="options"/>'s
/// <see cref="AIFunctionFactoryOptions.SerializerOptions"/>. Arguments that are not already of the expected type are
/// marshaled to the expected type via JSON and using <paramref name="options"/>'s
/// <see cref="AIFunctionFactoryOptions.SerializerOptions"/>. If the argument is a <see cref="JsonElement"/>,
/// <see cref="JsonDocument"/>, or <see cref="JsonNode"/>, it is deserialized directly. If the argument is anything else unknown,
/// it is round-tripped through JSON, serializing the object as JSON and then deserializing it to the expected type.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="method"/> is <see langword="null"/>.</exception>
public static AIFunction Create(Delegate method, AIFunctionFactoryOptions? options)
{
_ = Throw.IfNull(method);
return ReflectionAIFunction.Build(method.Method, method.Target, options ?? _defaultOptions);
}
/// <summary>Creates an <see cref="AIFunction"/> instance for a method, specified via a delegate.</summary>
/// <param name="method">The method to be represented via the created <see cref="AIFunction"/>.</param>
/// <param name="name">The name to use for the <see cref="AIFunction"/>.</param>
/// <param name="description">The description to use for the <see cref="AIFunction"/>.</param>
/// <param name="serializerOptions">The <see cref="JsonSerializerOptions"/> used to marshal function parameters and any return value.</param>
/// <returns>The created <see cref="AIFunction"/> for invoking <paramref name="method"/>.</returns>
/// <remarks>
/// <para>
/// Return values are serialized to <see cref="JsonElement"/> using <paramref name="serializerOptions"/>.
/// Arguments that are not already of the expected type are marshaled to the expected type via JSON and using
/// <paramref name="serializerOptions"/>. If the argument is a <see cref="JsonElement"/>, <see cref="JsonDocument"/>,
/// or <see cref="JsonNode"/>, it is deserialized directly. If the argument is anything else unknown, it is
/// round-tripped through JSON, serializing the object as JSON and then deserializing it to the expected type.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="method"/> is <see langword="null"/>.</exception>
public static AIFunction Create(Delegate method, string? name = null, string? description = null, JsonSerializerOptions? serializerOptions = null)
{
_ = Throw.IfNull(method);
AIFunctionFactoryOptions createOptions = serializerOptions is null && name is null && description is null
? _defaultOptions
: new()
{
Name = name,
Description = description,
SerializerOptions = serializerOptions,
};
return ReflectionAIFunction.Build(method.Method, method.Target, createOptions);
}
/// <summary>
/// Creates an <see cref="AIFunction"/> 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="AIFunction"/>.</param>
/// <param name="target">
/// The target object for the <paramref name="method"/> if it represents an instance method.
/// This should be <see langword="null"/> if and only if <paramref name="method"/> is a static method.
/// </param>
/// <param name="options">Metadata to use to override defaults inferred from <paramref name="method"/>.</param>
/// <returns>The created <see cref="AIFunction"/> for invoking <paramref name="method"/>.</returns>
/// <remarks>
/// <para>
/// Return values are serialized to <see cref="JsonElement"/> using <paramref name="options"/>'s
/// <see cref="AIFunctionFactoryOptions.SerializerOptions"/>. Arguments that are not already of the expected type are
/// marshaled to the expected type via JSON and using <paramref name="options"/>'s
/// <see cref="AIFunctionFactoryOptions.SerializerOptions"/>. If the argument is a <see cref="JsonElement"/>,
/// <see cref="JsonDocument"/>, or <see cref="JsonNode"/>, it is deserialized directly. If the argument is anything else unknown,
/// it is round-tripped through JSON, serializing the object as JSON and then deserializing it to the expected type.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="method"/> is <see langword="null"/>.</exception>
public static AIFunction Create(MethodInfo method, object? target, AIFunctionFactoryOptions? options)
{
_ = Throw.IfNull(method);
return ReflectionAIFunction.Build(method, target, options ?? _defaultOptions);
}
/// <summary>
/// Creates an <see cref="AIFunction"/> 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="AIFunction"/>.</param>
/// <param name="target">
/// The target object for the <paramref name="method"/> if it represents an instance method.
/// This should be <see langword="null"/> if and only if <paramref name="method"/> is a static method.
/// </param>
/// <param name="name">The name to use for the <see cref="AIFunction"/>.</param>
/// <param name="description">The description to use for the <see cref="AIFunction"/>.</param>
/// <param name="serializerOptions">The <see cref="JsonSerializerOptions"/> used to marshal function parameters and return value.</param>
/// <returns>The created <see cref="AIFunction"/> for invoking <paramref name="method"/>.</returns>
/// <remarks>
/// <para>
/// Return values are serialized to <see cref="JsonElement"/> using <paramref name="serializerOptions"/>.
/// Arguments that are not already of the expected type are marshaled to the expected type via JSON and using
/// <paramref name="serializerOptions"/>. If the argument is a <see cref="JsonElement"/>, <see cref="JsonDocument"/>,
/// or <see cref="JsonNode"/>, it is deserialized directly. If the argument is anything else unknown, it is
/// round-tripped through JSON, serializing the object as JSON and then deserializing it to the expected type.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="method"/> is <see langword="null"/>.</exception>
public static AIFunction Create(MethodInfo method, object? target, string? name = null, string? description = null, JsonSerializerOptions? serializerOptions = null)
{
_ = Throw.IfNull(method);
AIFunctionFactoryOptions createOptions = serializerOptions is null && name is null && description is null
? _defaultOptions
: new()
{
Name = name,
Description = description,
SerializerOptions = serializerOptions,
};
return ReflectionAIFunction.Build(method, target, createOptions);
}
private sealed class ReflectionAIFunction : AIFunction
{
public static ReflectionAIFunction Build(MethodInfo method, object? target, AIFunctionFactoryOptions options)
{
_ = Throw.IfNull(method);
if (method.ContainsGenericParameters)
{
Throw.ArgumentException(nameof(method), "Open generic methods are not supported");
}
if (!method.IsStatic && target is null)
{
Throw.ArgumentNullException(nameof(target), "Target must not be null for an instance method.");
}
ReflectionAIFunctionDescriptor functionDescriptor = ReflectionAIFunctionDescriptor.GetOrCreate(method, options);
if (target is null && options.AdditionalProperties is null)
{
// We can use a cached value for static methods not specifying additional properties.
return functionDescriptor.CachedDefaultInstance ??= new(functionDescriptor, target, options);
}
return new(functionDescriptor, target, options);
}
private ReflectionAIFunction(ReflectionAIFunctionDescriptor functionDescriptor, object? target, AIFunctionFactoryOptions options)
{
FunctionDescriptor = functionDescriptor;
Target = target;
AdditionalProperties = options.AdditionalProperties ?? EmptyReadOnlyDictionary<string, object?>.Instance;
}
public ReflectionAIFunctionDescriptor FunctionDescriptor { get; }
public object? Target { get; }
public override IReadOnlyDictionary<string, object?> AdditionalProperties { get; }
public override string Name => FunctionDescriptor.Name;
public override string Description => FunctionDescriptor.Description;
public override MethodInfo UnderlyingMethod => FunctionDescriptor.Method;
public override JsonElement JsonSchema => FunctionDescriptor.JsonSchema;
public override JsonSerializerOptions JsonSerializerOptions => FunctionDescriptor.JsonSerializerOptions;
protected override Task<object?> InvokeCoreAsync(
IEnumerable<KeyValuePair<string, object?>>? arguments,
IServiceProvider? services,
CancellationToken cancellationToken)
{
var paramMarshallers = FunctionDescriptor.ParameterMarshallers;
object?[] args = paramMarshallers.Length != 0 ? new object?[paramMarshallers.Length] : [];
IReadOnlyDictionary<string, object?> argDict =
arguments is null ? EmptyReadOnlyDictionary<string, object?>.Instance :
arguments as IReadOnlyDictionary<string, object?> ?? // if arguments is an AIFunctionArguments, which is an IROD, use it as-is
arguments.
#if NET8_0_OR_GREATER
ToDictionary();
#else
ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
#endif
for (int i = 0; i < args.Length; i++)
{
args[i] = paramMarshallers[i](argDict, services, cancellationToken);
}
return FunctionDescriptor.ReturnParameterMarshaller(ReflectionInvoke(FunctionDescriptor.Method, Target, args), cancellationToken);
}
}
/// <summary>
/// A descriptor for a .NET method-backed AIFunction that precomputes its marshalling delegates and JSON schema.
/// </summary>
private sealed class ReflectionAIFunctionDescriptor
{
private const int InnerCacheSoftLimit = 512;
private static readonly ConditionalWeakTable<JsonSerializerOptions, ConcurrentDictionary<DescriptorKey, ReflectionAIFunctionDescriptor>> _descriptorCache = new();
/// <summary>A boxed <see cref="CancellationToken.None"/>.</summary>
private static readonly object? _boxedDefaultCancellationToken = default(CancellationToken);
/// <summary>
/// Gets or creates a descriptors using the specified method and options.
/// </summary>
public static ReflectionAIFunctionDescriptor GetOrCreate(MethodInfo method, AIFunctionFactoryOptions options)
{
JsonSerializerOptions serializerOptions = options.SerializerOptions ?? AIJsonUtilities.DefaultOptions;
AIJsonSchemaCreateOptions schemaOptions = options.JsonSchemaCreateOptions ?? AIJsonSchemaCreateOptions.Default;
serializerOptions.MakeReadOnly();
ConcurrentDictionary<DescriptorKey, ReflectionAIFunctionDescriptor> innerCache = _descriptorCache.GetOrCreateValue(serializerOptions);
DescriptorKey key = new(method, options.Name, options.Description, schemaOptions);
if (innerCache.TryGetValue(key, out ReflectionAIFunctionDescriptor? descriptor))
{
return descriptor;
}
descriptor = new(key, serializerOptions);
return innerCache.Count < InnerCacheSoftLimit
? innerCache.GetOrAdd(key, descriptor)
: descriptor;
}
private ReflectionAIFunctionDescriptor(DescriptorKey key, JsonSerializerOptions serializerOptions)
{
AIJsonSchemaCreateOptions schemaOptions = new()
{
// This needs to be kept in sync with the shape of AIJsonSchemaCreateOptions.
TransformSchemaNode = key.SchemaOptions.TransformSchemaNode,
IncludeParameter = parameterInfo =>
{
// Explicitly exclude IServiceProvider. It'll be satisifed via AIFunctionArguments.
if (parameterInfo.ParameterType == typeof(IServiceProvider))
{
return false;
}
// For all other parameters, delegate to whatever behavior is specified in the options.
// If none is specified, include the parameter.
return key.SchemaOptions.IncludeParameter?.Invoke(parameterInfo) ?? true;
},
IncludeTypeInEnumSchemas = key.SchemaOptions.IncludeTypeInEnumSchemas,
DisallowAdditionalProperties = key.SchemaOptions.DisallowAdditionalProperties,
IncludeSchemaKeyword = key.SchemaOptions.IncludeSchemaKeyword,
RequireAllProperties = key.SchemaOptions.RequireAllProperties,
};
// Get marshaling delegates for parameters.
ParameterInfo[] parameters = key.Method.GetParameters();
ParameterMarshallers = new Func<IReadOnlyDictionary<string, object?>, IServiceProvider?, CancellationToken, object?>[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
ParameterMarshallers[i] = GetParameterMarshaller(serializerOptions, parameters[i]);
}
// Get a marshaling delegate for the return value.
ReturnParameterMarshaller = GetReturnParameterMarshaller(key.Method, serializerOptions);
Method = key.Method;
Name = key.Name ?? GetFunctionName(key.Method);
Description = key.Description ?? key.Method.GetCustomAttribute<DescriptionAttribute>(inherit: true)?.Description ?? string.Empty;
JsonSerializerOptions = serializerOptions;
JsonSchema = AIJsonUtilities.CreateFunctionJsonSchema(
key.Method,
Name,
Description,
serializerOptions,
schemaOptions);
}
public string Name { get; }
public string Description { get; }
public MethodInfo Method { get; }
public JsonSerializerOptions JsonSerializerOptions { get; }
public JsonElement JsonSchema { get; }
public Func<IReadOnlyDictionary<string, object?>, IServiceProvider?, CancellationToken, object?>[] ParameterMarshallers { get; }
public Func<object?, CancellationToken, Task<object?>> ReturnParameterMarshaller { get; }
public ReflectionAIFunction? CachedDefaultInstance { get; set; }
private static string GetFunctionName(MethodInfo method)
{
// Get the function name to use.
string name = SanitizeMemberName(method.Name);
const string AsyncSuffix = "Async";
if (IsAsyncMethod(method) &&
name.EndsWith(AsyncSuffix, StringComparison.Ordinal) &&
name.Length > AsyncSuffix.Length)
{
name = name.Substring(0, name.Length - AsyncSuffix.Length);
}
return name;
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>
private static Func<IReadOnlyDictionary<string, object?>, IServiceProvider?, CancellationToken, object?> GetParameterMarshaller(
JsonSerializerOptions serializerOptions,
ParameterInfo parameter)
{
if (string.IsNullOrWhiteSpace(parameter.Name))
{
Throw.ArgumentException(nameof(parameter), "Parameter is missing a name.");
}
// Resolve the contract used to marshal the value from JSON -- can throw if not supported or not found.
Type parameterType = parameter.ParameterType;
JsonTypeInfo typeInfo = serializerOptions.GetTypeInfo(parameterType);
// For CancellationToken parameters, we always bind to the token passed directly to InvokeAsync.
if (parameterType == typeof(CancellationToken))
{
return static (_, _, cancellationToken) =>
cancellationToken == default ? _boxedDefaultCancellationToken : // optimize common case of a default CT to avoid boxing
cancellationToken;
}
// For IServiceProvider parameters, we always bind to the services passed directly to InvokeAsync.
if (parameterType == typeof(IServiceProvider))
{
return (arguments, services, _) =>
{
if (services is not null)
{
return services;
}
if (!parameter.HasDefaultValue)
{
Throw.ArgumentException(nameof(arguments), $"An {nameof(IServiceProvider)} was not provided for the {parameter.Name} parameter.");
}
// The IServiceProvider parameter was optional. Return the default value.
return null;
};
}
// For all other parameters, create a marshaller that tries to extract the value from the arguments dictionary.
return (arguments, _, _) =>
{
// If the parameter has an argument specified in the dictionary, return that argument.
if (arguments.TryGetValue(parameter.Name, out object? value))
{
return value switch
{
null => null, // Return as-is if null -- if the parameter is a struct this will be handled by MethodInfo.Invoke
_ when parameterType.IsInstanceOfType(value) => value, // Do nothing if value is assignable to parameter type
JsonElement element => JsonSerializer.Deserialize(element, typeInfo),
JsonDocument doc => JsonSerializer.Deserialize(doc, typeInfo),
JsonNode node => JsonSerializer.Deserialize(node, typeInfo),
_ => MarshallViaJsonRoundtrip(value),
};
object? MarshallViaJsonRoundtrip(object value)
{
try
{
string json = JsonSerializer.Serialize(value, serializerOptions.GetTypeInfo(value.GetType()));
return JsonSerializer.Deserialize(json, typeInfo);
}
catch
{
// Eat any exceptions and fall back to the original value to force a cast exception later on.
return value;
}
}
}
// If the parameter is required and there's no argument specified for it, throw.
if (!parameter.HasDefaultValue)
{
Throw.ArgumentException(nameof(arguments), $"Missing required parameter '{parameter.Name}' for method '{parameter.Member.Name}'.");
}
// Otherwise, use the optional parameter's default value.
return parameter.DefaultValue;
};
}
/// <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 Func<object?, CancellationToken, Task<object?>> GetReturnParameterMarshaller(MethodInfo method, JsonSerializerOptions serializerOptions)
{
Type returnType = method.ReturnType;
JsonTypeInfo returnTypeInfo;
// Void
if (returnType == typeof(void))
{
return static (_, _) => Task.FromResult<object?>(null);
}
// Task
if (returnType == typeof(Task))
{
return async static (result, _) =>
{
await ((Task)ThrowIfNullResult(result)).ConfigureAwait(false);
return null;
};
}
// ValueTask
if (returnType == typeof(ValueTask))
{
return async static (result, _) =>
{
await ((ValueTask)ThrowIfNullResult(result)).ConfigureAwait(false);
return null;
};
}
if (returnType.IsGenericType)
{
// Task<T>
if (returnType.GetGenericTypeDefinition() == typeof(Task<>))
{
MethodInfo taskResultGetter = GetMethodFromGenericMethodDefinition(returnType, _taskGetResult);
returnTypeInfo = serializerOptions.GetTypeInfo(taskResultGetter.ReturnType);
return async (taskObj, cancellationToken) =>
{
await ((Task)ThrowIfNullResult(taskObj)).ConfigureAwait(false);
object? result = ReflectionInvoke(taskResultGetter, taskObj, null);
return await SerializeResultAsync(result, returnTypeInfo, cancellationToken).ConfigureAwait(false);
};
}
// ValueTask<T>
if (returnType.GetGenericTypeDefinition() == typeof(ValueTask<>))
{
MethodInfo valueTaskAsTask = GetMethodFromGenericMethodDefinition(returnType, _valueTaskAsTask);
MethodInfo asTaskResultGetter = GetMethodFromGenericMethodDefinition(valueTaskAsTask.ReturnType, _taskGetResult);
returnTypeInfo = serializerOptions.GetTypeInfo(asTaskResultGetter.ReturnType);
return async (taskObj, cancellationToken) =>
{
var task = (Task)ReflectionInvoke(valueTaskAsTask, ThrowIfNullResult(taskObj), null)!;
await task.ConfigureAwait(false);
object? result = ReflectionInvoke(asTaskResultGetter, task, null);
return await SerializeResultAsync(result, returnTypeInfo, cancellationToken).ConfigureAwait(false);
};
}
}
// For everything else, just serialize the result as-is.
returnTypeInfo = serializerOptions.GetTypeInfo(returnType);
return (result, cancellationToken) => SerializeResultAsync(result, returnTypeInfo, cancellationToken);
static async Task<object?> SerializeResultAsync(object? result, JsonTypeInfo returnTypeInfo, CancellationToken cancellationToken)
{
if (returnTypeInfo.Kind is JsonTypeInfoKind.None)
{
// Special-case trivial contracts to avoid the more expensive general-purpose serialization path.
return JsonSerializer.SerializeToElement(result, returnTypeInfo);
}
// Serialize asynchronously to support potential IAsyncEnumerable responses.
using PooledMemoryStream stream = new();
await JsonSerializer.SerializeAsync(stream, result, returnTypeInfo, cancellationToken).ConfigureAwait(false);
Utf8JsonReader reader = new(stream.GetBuffer());
return JsonElement.ParseValue(ref reader);
}
// Throws an exception if a result is found to be null unexpectedly
static object ThrowIfNullResult(object? result) => result ?? throw new InvalidOperationException("Function returned null unexpectedly.");
}
private static readonly MethodInfo _taskGetResult = typeof(Task<>).GetProperty(nameof(Task<int>.Result), BindingFlags.Instance | BindingFlags.Public)!.GetMethod!;
private static readonly MethodInfo _valueTaskAsTask = typeof(ValueTask<>).GetMethod(nameof(ValueTask<int>.AsTask), BindingFlags.Instance | BindingFlags.Public)!;
private static MethodInfo GetMethodFromGenericMethodDefinition(Type specializedType, MethodInfo genericMethodDefinition)
{
Debug.Assert(specializedType.IsGenericType && specializedType.GetGenericTypeDefinition() == genericMethodDefinition.DeclaringType, "generic member definition doesn't match type.");
#if NET
return (MethodInfo)specializedType.GetMemberWithSameMetadataDefinitionAs(genericMethodDefinition);
#else
const BindingFlags All = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;
return specializedType.GetMethods(All).First(m => m.MetadataToken == genericMethodDefinition.MetadataToken);
#endif
}
private record struct DescriptorKey(MethodInfo Method, string? Name, string? Description, AIJsonSchemaCreateOptions SchemaOptions);
}
}