Skip to content

Commit

Permalink
Removing Json conversion from AIFunction adapter and moving to the co…
Browse files Browse the repository at this point in the history
…re kernelmethod impl.
  • Loading branch information
RogerBarreto committed Nov 21, 2024
1 parent 8cd1aef commit 9eef868
Showing 1 changed file with 1 addition and 60 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -567,68 +567,9 @@ public KernelAIFunction(KernelFunction kernelFunction, Kernel? kernel)

// Create the KernelArguments from the supplied arguments.
KernelArguments args = [];

var parsers = new Dictionary<Type, Func<string, object>>(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) }
};

foreach (var argument in arguments)
{
if (argument.Value is null)
{
args[argument.Key] = null;
continue;
}

if (argument.Value is not JsonElement or JsonDocument or JsonNode)
{
args[argument.Key] = argument.Value;
continue;
}

// Resolve the contract used to marshal the value from JSON -- can throw if not supported or not found.
var parameter = this._kernelFunction.Metadata.Parameters.FirstOrDefault(p => p.Name == argument.Key);
if (parameter?.ParameterType is null)
{
args[argument.Key] = argument.Value;
continue;
}

Type parameterType = parameter.ParameterType;
JsonTypeInfo typeInfo = (this._kernelFunction.JsonSerializerOptions ?? JsonSerializerOptions.Default).GetTypeInfo(parameterType);

object? argumentValue = null;
if (argument.Value is JsonElement element && element.ValueKind == JsonValueKind.String)
{
if (parsers.TryGetValue(parameterType, out var parser))
{
args[argument.Key] = parser(element.GetString()!);
continue;
}
}

argumentValue = argument.Value switch
{
null => null, // Return as-is if null -- if the parameter is a struct this will be handled by MethodInfo.Invoke
JsonElement jsonElement => JsonSerializer.Deserialize(jsonElement, typeInfo),
JsonDocument doc => JsonSerializer.Deserialize(doc, typeInfo),
JsonNode node => JsonSerializer.Deserialize(node, typeInfo),
_ => argument.Value
};

args[argument.Key] = argumentValue;
args[argument.Key] = argument.Value;
}

// Invoke the KernelFunction.
Expand Down

0 comments on commit 9eef868

Please sign in to comment.