| | | 1 | | // Copyright (c) NexusLabs. All rights reserved. |
| | | 2 | | // Licensed under the MIT License. |
| | | 3 | | |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Collections.Immutable; |
| | | 6 | | using System.Linq; |
| | | 7 | | using System.Text; |
| | | 8 | | |
| | | 9 | | namespace NexusLabs.Needlr.AgentFramework.Generators; |
| | | 10 | | |
| | | 11 | | internal static class AIFunctionProviderCodeGenerator |
| | | 12 | | { |
| | | 13 | | public static string GenerateAIFunctionProviderSource( |
| | | 14 | | List<AgentFunctionTypeInfo> types, |
| | | 15 | | string safeAssemblyName) |
| | | 16 | | { |
| | 138 | 17 | | var sb = new StringBuilder(); |
| | 138 | 18 | | sb.AppendLine("// <auto-generated/>"); |
| | 138 | 19 | | sb.AppendLine("#nullable enable"); |
| | 138 | 20 | | sb.AppendLine(); |
| | 138 | 21 | | sb.AppendLine("using global::Microsoft.Extensions.DependencyInjection;"); |
| | 138 | 22 | | sb.AppendLine(); |
| | 138 | 23 | | sb.AppendLine($"namespace {safeAssemblyName}.Generated;"); |
| | 138 | 24 | | sb.AppendLine(); |
| | 138 | 25 | | sb.AppendLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"NexusLabs.Needlr.AgentFramework.Generat |
| | 138 | 26 | | sb.AppendLine("internal sealed class GeneratedAIFunctionProvider : global::NexusLabs.Needlr.AgentFramework.IAIFu |
| | 138 | 27 | | sb.AppendLine("{"); |
| | 138 | 28 | | sb.AppendLine(" public bool TryGetFunctions("); |
| | 138 | 29 | | sb.AppendLine(" global::System.Type functionType,"); |
| | 138 | 30 | | sb.AppendLine(" global::System.IServiceProvider serviceProvider,"); |
| | 138 | 31 | | sb.AppendLine(" [global::System.Diagnostics.CodeAnalysis.NotNullWhen(true)]"); |
| | 138 | 32 | | sb.AppendLine(" out global::System.Collections.Generic.IReadOnlyList<global::Microsoft.Extensions.AI.AIFu |
| | 138 | 33 | | sb.AppendLine(" {"); |
| | | 34 | | |
| | 138 | 35 | | if (types.Count == 0) |
| | | 36 | | { |
| | 81 | 37 | | sb.AppendLine(" functions = null;"); |
| | 81 | 38 | | sb.AppendLine(" return false;"); |
| | | 39 | | } |
| | | 40 | | else |
| | | 41 | | { |
| | 57 | 42 | | var first = true; |
| | 228 | 43 | | foreach (var type in types) |
| | | 44 | | { |
| | 57 | 45 | | var keyword = first ? "if" : "else if"; |
| | 57 | 46 | | first = false; |
| | 57 | 47 | | sb.AppendLine($" {keyword} (functionType == typeof({type.TypeName}))"); |
| | 57 | 48 | | sb.AppendLine(" {"); |
| | 57 | 49 | | if (!type.IsStatic) |
| | 55 | 50 | | sb.AppendLine($" var typed = serviceProvider.GetRequiredService<{type.TypeName}>();"); |
| | 57 | 51 | | sb.AppendLine(" functions = new global::System.Collections.Generic.List<global::Microsoft.Ext |
| | 57 | 52 | | sb.AppendLine(" {"); |
| | 228 | 53 | | foreach (var m in type.Methods) |
| | | 54 | | { |
| | 57 | 55 | | var nestedName = $"{AgentDiscoveryHelper.GetShortName(type.TypeName)}_{m.MethodName}"; |
| | 57 | 56 | | if (type.IsStatic) |
| | 2 | 57 | | sb.AppendLine($" new {nestedName}(),"); |
| | | 58 | | else |
| | 55 | 59 | | sb.AppendLine($" new {nestedName}(typed),"); |
| | | 60 | | } |
| | 57 | 61 | | sb.AppendLine(" }.AsReadOnly();"); |
| | 57 | 62 | | sb.AppendLine(" return true;"); |
| | 57 | 63 | | sb.AppendLine(" }"); |
| | | 64 | | } |
| | 57 | 65 | | sb.AppendLine(" functions = null;"); |
| | 57 | 66 | | sb.AppendLine(" return false;"); |
| | | 67 | | } |
| | | 68 | | |
| | 138 | 69 | | sb.AppendLine(" }"); |
| | 138 | 70 | | sb.AppendLine(); |
| | | 71 | | |
| | 390 | 72 | | foreach (var type in types) |
| | | 73 | | { |
| | 57 | 74 | | var shortTypeName = AgentDiscoveryHelper.GetShortName(type.TypeName); |
| | 228 | 75 | | foreach (var m in type.Methods) |
| | | 76 | | { |
| | 57 | 77 | | var nestedName = $"{shortTypeName}_{m.MethodName}"; |
| | 57 | 78 | | AppendAIFunctionNestedClass(sb, type, m, nestedName); |
| | | 79 | | } |
| | | 80 | | } |
| | | 81 | | |
| | 138 | 82 | | sb.AppendLine("}"); |
| | 138 | 83 | | return sb.ToString(); |
| | | 84 | | } |
| | | 85 | | |
| | | 86 | | private static void AppendAIFunctionNestedClass( |
| | | 87 | | StringBuilder sb, |
| | | 88 | | AgentFunctionTypeInfo type, |
| | | 89 | | AgentFunctionMethodInfo method, |
| | | 90 | | string nestedClassName) |
| | | 91 | | { |
| | 57 | 92 | | sb.AppendLine($" private sealed class {nestedClassName} : global::Microsoft.Extensions.AI.AIFunction"); |
| | 57 | 93 | | sb.AppendLine(" {"); |
| | | 94 | | |
| | 57 | 95 | | if (!type.IsStatic) |
| | 55 | 96 | | sb.AppendLine($" private readonly {type.TypeName} _instance;"); |
| | | 97 | | |
| | 57 | 98 | | var schemaJson = BuildJsonSchema(method.Parameters); |
| | 57 | 99 | | sb.AppendLine(" private static readonly global::System.Text.Json.JsonElement _schema ="); |
| | 57 | 100 | | sb.AppendLine($" global::System.Text.Json.JsonDocument.Parse(\"\"\"{schemaJson}\"\"\").RootElement.Cl |
| | | 101 | | |
| | 57 | 102 | | if (!string.IsNullOrEmpty(method.ReturnJsonSchemaType)) |
| | | 103 | | { |
| | 53 | 104 | | var returnSchemaJson = !string.IsNullOrEmpty(method.ReturnObjectSchemaJson) |
| | 53 | 105 | | ? method.ReturnObjectSchemaJson |
| | 53 | 106 | | : $"{{\"type\":\"{method.ReturnJsonSchemaType}\"}}"; |
| | 53 | 107 | | sb.AppendLine(" private static readonly global::System.Text.Json.JsonElement _returnSchema ="); |
| | 53 | 108 | | sb.AppendLine($" global::System.Text.Json.JsonDocument.Parse(\"\"\"{returnSchemaJson}\"\"\").Root |
| | | 109 | | } |
| | | 110 | | |
| | 57 | 111 | | sb.AppendLine(); |
| | | 112 | | |
| | 57 | 113 | | if (!type.IsStatic) |
| | 55 | 114 | | sb.AppendLine($" public {nestedClassName}({type.TypeName} instance) {{ _instance = instance; }}"); |
| | | 115 | | else |
| | 2 | 116 | | sb.AppendLine($" public {nestedClassName}() {{ }}"); |
| | | 117 | | |
| | 57 | 118 | | sb.AppendLine(); |
| | | 119 | | |
| | 57 | 120 | | var escapedName = method.MethodName.Replace("\"", "\\\""); |
| | 57 | 121 | | var escapedDesc = method.Description.Replace("\\", "\\\\").Replace("\"", "\\\""); |
| | 57 | 122 | | sb.AppendLine($" public override string Name => \"{escapedName}\";"); |
| | 57 | 123 | | sb.AppendLine($" public override string Description => \"{escapedDesc}\";"); |
| | 57 | 124 | | sb.AppendLine(" public override global::System.Text.Json.JsonElement JsonSchema => _schema;"); |
| | | 125 | | |
| | 57 | 126 | | if (!string.IsNullOrEmpty(method.ReturnJsonSchemaType)) |
| | | 127 | | { |
| | 53 | 128 | | sb.AppendLine(" public override global::System.Text.Json.JsonElement? ReturnJsonSchema => _returnSche |
| | | 129 | | } |
| | | 130 | | |
| | 57 | 131 | | sb.AppendLine(); |
| | | 132 | | |
| | 57 | 133 | | if (method.IsAsync) |
| | 3 | 134 | | sb.AppendLine(" protected override async global::System.Threading.Tasks.ValueTask<object?> InvokeCore |
| | | 135 | | else |
| | 54 | 136 | | sb.AppendLine(" protected override global::System.Threading.Tasks.ValueTask<object?> InvokeCoreAsync( |
| | | 137 | | |
| | 57 | 138 | | sb.AppendLine(" global::Microsoft.Extensions.AI.AIFunctionArguments arguments,"); |
| | 57 | 139 | | sb.AppendLine(" global::System.Threading.CancellationToken ct)"); |
| | 57 | 140 | | sb.AppendLine(" {"); |
| | | 141 | | |
| | 224 | 142 | | foreach (var param in method.Parameters) |
| | | 143 | | { |
| | 55 | 144 | | if (param.IsCancellationToken) |
| | | 145 | | continue; |
| | 54 | 146 | | AppendParameterExtraction(sb, type, method, param); |
| | | 147 | | } |
| | | 148 | | |
| | 112 | 149 | | var paramList = string.Join(", ", method.Parameters.Select(p => p.IsCancellationToken ? "ct" : p.Name)); |
| | 57 | 150 | | var instanceExpr = type.IsStatic ? type.TypeName : "_instance"; |
| | | 151 | | |
| | 57 | 152 | | if (method.IsAsync) |
| | | 153 | | { |
| | 3 | 154 | | if (method.IsVoidLike) |
| | | 155 | | { |
| | 1 | 156 | | sb.AppendLine($" await {instanceExpr}.{method.MethodName}({paramList}).ConfigureAwait(false); |
| | 1 | 157 | | sb.AppendLine(" return null;"); |
| | | 158 | | } |
| | | 159 | | else |
| | | 160 | | { |
| | 2 | 161 | | sb.AppendLine($" var result = await {instanceExpr}.{method.MethodName}({paramList}).Configure |
| | 2 | 162 | | sb.AppendLine(" return result;"); |
| | | 163 | | } |
| | | 164 | | } |
| | | 165 | | else |
| | | 166 | | { |
| | 54 | 167 | | if (method.IsVoidLike) |
| | | 168 | | { |
| | 3 | 169 | | sb.AppendLine($" {instanceExpr}.{method.MethodName}({paramList});"); |
| | 3 | 170 | | sb.AppendLine(" return global::System.Threading.Tasks.ValueTask.FromResult<object?>(null);"); |
| | | 171 | | } |
| | | 172 | | else |
| | | 173 | | { |
| | 51 | 174 | | sb.AppendLine($" var result = {instanceExpr}.{method.MethodName}({paramList});"); |
| | 51 | 175 | | sb.AppendLine(" return global::System.Threading.Tasks.ValueTask.FromResult<object?>(result);" |
| | | 176 | | } |
| | | 177 | | } |
| | | 178 | | |
| | 57 | 179 | | sb.AppendLine(" }"); |
| | 57 | 180 | | sb.AppendLine(" }"); |
| | 57 | 181 | | sb.AppendLine(); |
| | 57 | 182 | | } |
| | | 183 | | |
| | | 184 | | private static string BuildJsonSchema(ImmutableArray<AgentFunctionParameterInfo> parameters) |
| | | 185 | | { |
| | 112 | 186 | | var nonCtParams = parameters.Where(p => !p.IsCancellationToken).ToList(); |
| | 57 | 187 | | if (nonCtParams.Count == 0) |
| | 6 | 188 | | return "{\"type\":\"object\",\"properties\":{}}"; |
| | | 189 | | |
| | 51 | 190 | | var props = new StringBuilder(); |
| | 51 | 191 | | var required = new List<string>(); |
| | | 192 | | |
| | 51 | 193 | | props.Append("{"); |
| | 51 | 194 | | var firstProp = true; |
| | 210 | 195 | | foreach (var param in nonCtParams) |
| | | 196 | | { |
| | 57 | 197 | | if (!firstProp) props.Append(","); |
| | 54 | 198 | | firstProp = false; |
| | 54 | 199 | | var escapedParamName = param.Name.Replace("\"", "\\\""); |
| | 54 | 200 | | props.Append($"\"{escapedParamName}\":"); |
| | 54 | 201 | | props.Append(BuildJsonSchemaTypeEntry(param)); |
| | 54 | 202 | | if (param.IsRequired) |
| | 36 | 203 | | required.Add(param.Name); |
| | | 204 | | } |
| | 51 | 205 | | props.Append("}"); |
| | | 206 | | |
| | 51 | 207 | | var sb = new StringBuilder(); |
| | 51 | 208 | | sb.Append("{\"type\":\"object\",\"properties\":"); |
| | 51 | 209 | | sb.Append(props); |
| | 51 | 210 | | if (required.Count > 0) |
| | | 211 | | { |
| | 34 | 212 | | sb.Append(",\"required\":["); |
| | 70 | 213 | | sb.Append(string.Join(",", required.Select(r => "\"" + r.Replace("\"", "\\\"") + "\""))); |
| | 34 | 214 | | sb.Append("]"); |
| | | 215 | | } |
| | 51 | 216 | | sb.Append("}"); |
| | 51 | 217 | | return sb.ToString(); |
| | | 218 | | } |
| | | 219 | | |
| | | 220 | | private static string BuildJsonSchemaTypeEntry(AgentFunctionParameterInfo param) |
| | | 221 | | { |
| | 54 | 222 | | if (string.IsNullOrEmpty(param.JsonSchemaType)) |
| | 0 | 223 | | return "{}"; |
| | | 224 | | |
| | 54 | 225 | | if (param.JsonSchemaType == "array") |
| | | 226 | | { |
| | 8 | 227 | | var desc = string.IsNullOrEmpty(param.Description) |
| | 8 | 228 | | ? "" |
| | 8 | 229 | | : $",\"description\":\"{param.Description!.Replace("\\", "\\\\").Replace("\"", "\\\"")}\""; |
| | | 230 | | |
| | 8 | 231 | | if (param.ItemJsonSchemaType == "object" && !string.IsNullOrEmpty(param.ItemObjectSchemaJson)) |
| | | 232 | | { |
| | | 233 | | // Complex object array items — emit the full object schema |
| | 5 | 234 | | return $"{{\"type\":\"array\",\"items\":{param.ItemObjectSchemaJson}{desc}}}"; |
| | | 235 | | } |
| | | 236 | | |
| | 3 | 237 | | if (!string.IsNullOrEmpty(param.ItemJsonSchemaType)) |
| | 3 | 238 | | return $"{{\"type\":\"array\",\"items\":{{\"type\":\"{param.ItemJsonSchemaType}\"}}{desc}}}"; |
| | | 239 | | |
| | 0 | 240 | | return $"{{\"type\":\"array\"{desc}}}"; |
| | | 241 | | } |
| | | 242 | | |
| | 46 | 243 | | if (param.JsonSchemaType == "object") |
| | | 244 | | { |
| | | 245 | | // Direct complex object parameter (not in an array). Use the pre-built object |
| | | 246 | | // schema (with properties + required fields) when discovery generated one; |
| | | 247 | | // otherwise fall back to the bare {"type":"object"} shape — usually the case |
| | | 248 | | // for empty DTOs or types with no public properties. |
| | 4 | 249 | | var desc = string.IsNullOrEmpty(param.Description) |
| | 4 | 250 | | ? "" |
| | 4 | 251 | | : $",\"description\":\"{param.Description!.Replace("\\", "\\\\").Replace("\"", "\\\"")}\""; |
| | 4 | 252 | | if (!string.IsNullOrEmpty(param.ObjectSchemaJson)) |
| | | 253 | | { |
| | | 254 | | // ObjectSchemaJson already starts with {"type":"object","properties":{…},"required":[…]}. |
| | | 255 | | // Splice the description in before the closing brace. |
| | 4 | 256 | | var inner = param.ObjectSchemaJson!.Substring(0, param.ObjectSchemaJson.Length - 1); |
| | 4 | 257 | | return string.IsNullOrEmpty(desc) |
| | 4 | 258 | | ? param.ObjectSchemaJson! |
| | 4 | 259 | | : $"{inner}{desc}}}"; |
| | | 260 | | } |
| | 0 | 261 | | return $"{{\"type\":\"object\"{desc}}}"; |
| | | 262 | | } |
| | | 263 | | |
| | 42 | 264 | | var format = string.IsNullOrEmpty(param.JsonSchemaFormat) |
| | 42 | 265 | | ? "" |
| | 42 | 266 | | : $",\"format\":\"{param.JsonSchemaFormat}\""; |
| | | 267 | | |
| | 42 | 268 | | if (!string.IsNullOrEmpty(param.Description)) |
| | | 269 | | { |
| | 1 | 270 | | var escapedDesc = param.Description!.Replace("\\", "\\\\").Replace("\"", "\\\""); |
| | 1 | 271 | | return $"{{\"type\":\"{param.JsonSchemaType}\"{format},\"description\":\"{escapedDesc}\"}}"; |
| | | 272 | | } |
| | | 273 | | |
| | 41 | 274 | | return $"{{\"type\":\"{param.JsonSchemaType}\"{format}}}"; |
| | | 275 | | } |
| | | 276 | | |
| | | 277 | | private const string ExtractorFqn = "global::NexusLabs.Needlr.AgentFramework.AgentFrameworkArgumentExtractor"; |
| | | 278 | | |
| | | 279 | | private static void AppendParameterExtraction( |
| | | 280 | | StringBuilder sb, |
| | | 281 | | AgentFunctionTypeInfo type, |
| | | 282 | | AgentFunctionMethodInfo method, |
| | | 283 | | AgentFunctionParameterInfo param) |
| | | 284 | | { |
| | 54 | 285 | | var rawVar = $"_raw_{param.Name}"; |
| | 54 | 286 | | var jVar = $"_j_{param.Name}"; |
| | 54 | 287 | | sb.AppendLine($" arguments.TryGetValue(\"{param.Name}\", out var {rawVar});"); |
| | | 288 | | |
| | 54 | 289 | | switch (param.JsonSchemaType) |
| | | 290 | | { |
| | | 291 | | case "string": |
| | 20 | 292 | | if (param.IsEnum) |
| | 2 | 293 | | AppendEnumExtraction(sb, type, method, param, rawVar); |
| | | 294 | | else |
| | 18 | 295 | | AppendPrimitiveExtraction(sb, type, method, param, rawVar, GetStringFamilyHelper(param)); |
| | 18 | 296 | | break; |
| | | 297 | | case "boolean": |
| | 5 | 298 | | AppendPrimitiveExtraction(sb, type, method, param, rawVar, "GetBooleanArgument"); |
| | 5 | 299 | | break; |
| | | 300 | | case "integer": |
| | 11 | 301 | | AppendPrimitiveExtraction(sb, type, method, param, rawVar, GetIntegerHelperForType(param.TypeFullName)); |
| | 11 | 302 | | break; |
| | | 303 | | case "number": |
| | 6 | 304 | | AppendPrimitiveExtraction(sb, type, method, param, rawVar, GetNumberHelperForType(param.TypeFullName)); |
| | 6 | 305 | | break; |
| | | 306 | | case "array": |
| | | 307 | | { |
| | 8 | 308 | | var elementType = GetArrayElementType(param.TypeFullName); |
| | 8 | 309 | | sb.AppendLine($" {param.TypeFullName} {param.Name};"); |
| | 8 | 310 | | sb.AppendLine($" if ({rawVar} is global::System.Text.Json.JsonElement {jVar} && {jVar}.ValueK |
| | 8 | 311 | | sb.AppendLine(" {"); |
| | 8 | 312 | | sb.AppendLine($" var _list_{param.Name} = new global::System.Collections.Generic.List<{el |
| | 8 | 313 | | sb.AppendLine($" foreach (var _elem in {jVar}.EnumerateArray())"); |
| | 8 | 314 | | sb.AppendLine(" {"); |
| | | 315 | | |
| | 8 | 316 | | if (param.ItemJsonSchemaType == "object" && param.ItemObjectProperties is { Count: > 0 }) |
| | | 317 | | { |
| | 5 | 318 | | sb.AppendLine($" var _obj = new {elementType}();"); |
| | 5 | 319 | | AppendObjectPropertyAssignments( |
| | 5 | 320 | | sb, |
| | 5 | 321 | | targetVar: "_obj", |
| | 5 | 322 | | sourceJsonElementVar: "_elem", |
| | 5 | 323 | | properties: param.ItemObjectProperties, |
| | 5 | 324 | | indent: " "); |
| | 5 | 325 | | sb.AppendLine($" _list_{param.Name}.Add(_obj);"); |
| | | 326 | | } |
| | 3 | 327 | | else if (param.ItemJsonSchemaType == "string") |
| | 2 | 328 | | sb.AppendLine($" _list_{param.Name}.Add({ExtractorFqn}.GetStringArgument(_elem)); |
| | 1 | 329 | | else if (param.ItemJsonSchemaType == "integer") |
| | 1 | 330 | | sb.AppendLine($" _list_{param.Name}.Add({ExtractorFqn}.GetInt32Argument(_elem));" |
| | 0 | 331 | | else if (param.ItemJsonSchemaType == "number") |
| | 0 | 332 | | sb.AppendLine($" _list_{param.Name}.Add({ExtractorFqn}.GetDoubleArgument(_elem)); |
| | 0 | 333 | | else if (param.ItemJsonSchemaType == "boolean") |
| | 0 | 334 | | sb.AppendLine($" _list_{param.Name}.Add({ExtractorFqn}.GetBooleanArgument(_elem)) |
| | | 335 | | else |
| | 0 | 336 | | sb.AppendLine($" _list_{param.Name}.Add(default!);"); |
| | | 337 | | |
| | 8 | 338 | | sb.AppendLine(" }"); |
| | 8 | 339 | | sb.AppendLine($" {param.Name} = _list_{param.Name}.ToArray();"); |
| | 8 | 340 | | sb.AppendLine(" }"); |
| | 8 | 341 | | sb.AppendLine($" else {{ {param.Name} = {rawVar} as {param.TypeFullName} ?? global::System.Ar |
| | 8 | 342 | | break; |
| | | 343 | | } |
| | | 344 | | case "object": |
| | | 345 | | { |
| | 4 | 346 | | if (param.ObjectProperties is { Count: > 0 }) |
| | | 347 | | { |
| | 4 | 348 | | var cVar = $"_c_{param.Name}"; |
| | 4 | 349 | | var jObjVar = $"_j_{param.Name}"; |
| | 4 | 350 | | var nullSuppress = param.IsNullable ? "" : "!"; |
| | 4 | 351 | | sb.AppendLine($" {param.TypeFullName} {param.Name};"); |
| | 4 | 352 | | sb.AppendLine($" if ({rawVar} is global::System.Text.Json.JsonElement {jObjVar} && {jObjV |
| | 4 | 353 | | sb.AppendLine(" {"); |
| | 4 | 354 | | sb.AppendLine($" {param.Name} = new {param.TypeFullName}();"); |
| | 4 | 355 | | AppendObjectPropertyAssignments( |
| | 4 | 356 | | sb, |
| | 4 | 357 | | targetVar: param.Name, |
| | 4 | 358 | | sourceJsonElementVar: jObjVar, |
| | 4 | 359 | | properties: param.ObjectProperties, |
| | 4 | 360 | | indent: " "); |
| | 4 | 361 | | sb.AppendLine(" }"); |
| | 4 | 362 | | sb.AppendLine($" else if ({rawVar} is {param.TypeFullName} {cVar})"); |
| | 4 | 363 | | sb.AppendLine(" {"); |
| | 4 | 364 | | sb.AppendLine($" {param.Name} = {cVar};"); |
| | 4 | 365 | | sb.AppendLine(" }"); |
| | 4 | 366 | | sb.AppendLine(" else"); |
| | 4 | 367 | | sb.AppendLine(" {"); |
| | 4 | 368 | | sb.AppendLine($" {param.Name} = default({param.TypeFullName}){nullSuppress};"); |
| | 4 | 369 | | sb.AppendLine(" }"); |
| | | 370 | | } |
| | | 371 | | else |
| | | 372 | | { |
| | 0 | 373 | | var cVar = $"_c_{param.Name}"; |
| | 0 | 374 | | var nullSuppress = param.IsNullable ? "" : "!"; |
| | 0 | 375 | | sb.AppendLine($" var {param.Name} = {rawVar} is {param.TypeFullName} {cVar} ? {cVar} : de |
| | | 376 | | } |
| | 0 | 377 | | break; |
| | | 378 | | } |
| | | 379 | | default: |
| | | 380 | | { |
| | 0 | 381 | | var cVar = $"_c_{param.Name}"; |
| | 0 | 382 | | var nullSuppress = param.IsNullable ? "" : "!"; |
| | 0 | 383 | | sb.AppendLine($" var {param.Name} = {rawVar} is {param.TypeFullName} {cVar} ? {cVar} : defaul |
| | | 384 | | break; |
| | | 385 | | } |
| | | 386 | | } |
| | 0 | 387 | | } |
| | | 388 | | |
| | | 389 | | /// <summary> |
| | | 390 | | /// Emits a kind-tolerant extraction call for a primitive parameter, gated by |
| | | 391 | | /// <c>AgentFrameworkArgumentExtractor.IsArgumentSupplied</c>: |
| | | 392 | | /// <list type="bullet"> |
| | | 393 | | /// <item><description>Required (not nullable, no default): emit a fail-fast guard that |
| | | 394 | | /// throws <see cref="System.ArgumentException"/> citing the tool/method/argument name.</description></item> |
| | | 395 | | /// <item><description>Has default: fall back to the captured C# default literal when the |
| | | 396 | | /// argument is missing, <c>JsonValueKind.Null</c>, or <c>JsonValueKind.Undefined</c>. The |
| | | 397 | | /// default literal wins over <c>null</c> even when the parameter is nullable |
| | | 398 | | /// (<c>string? p = "x"</c> falls back to <c>"x"</c>, not <c>null</c>).</description></item> |
| | | 399 | | /// <item><description>Nullable with no default: fall back to <see langword="null"/>.</description></item> |
| | | 400 | | /// </list> |
| | | 401 | | /// </summary> |
| | | 402 | | private static void AppendPrimitiveExtraction( |
| | | 403 | | StringBuilder sb, |
| | | 404 | | AgentFunctionTypeInfo type, |
| | | 405 | | AgentFunctionMethodInfo method, |
| | | 406 | | AgentFunctionParameterInfo param, |
| | | 407 | | string rawVar, |
| | | 408 | | string extractorMethod) |
| | | 409 | | { |
| | 40 | 410 | | var varType = GetVariableTypeForParam(param); |
| | 40 | 411 | | var extractorCall = $"{ExtractorFqn}.{extractorMethod}({rawVar})"; |
| | | 412 | | |
| | 40 | 413 | | if (param.IsRequired) |
| | | 414 | | { |
| | 23 | 415 | | var toolMethodName = $"{AgentDiscoveryHelper.GetShortName(type.TypeName)}.{method.MethodName}"; |
| | 23 | 416 | | sb.AppendLine($" if (!{ExtractorFqn}.IsArgumentSupplied({rawVar}))"); |
| | 23 | 417 | | sb.AppendLine(" {"); |
| | 23 | 418 | | sb.AppendLine(" throw new global::System.ArgumentException("); |
| | 23 | 419 | | sb.AppendLine($" \"Required argument '{param.Name}' was not supplied to AIFunction '{tool |
| | 23 | 420 | | sb.AppendLine(" nameof(arguments));"); |
| | 23 | 421 | | sb.AppendLine(" }"); |
| | 23 | 422 | | sb.AppendLine($" {varType} {param.Name} = {extractorCall};"); |
| | 23 | 423 | | return; |
| | | 424 | | } |
| | | 425 | | |
| | 17 | 426 | | var fallback = param.HasDefault ? param.DefaultLiteral! : "null"; |
| | 17 | 427 | | sb.AppendLine($" {varType} {param.Name};"); |
| | 17 | 428 | | sb.AppendLine($" if (!{ExtractorFqn}.IsArgumentSupplied({rawVar}))"); |
| | 17 | 429 | | sb.AppendLine($" {param.Name} = {fallback};"); |
| | 17 | 430 | | sb.AppendLine(" else"); |
| | 17 | 431 | | sb.AppendLine($" {param.Name} = {extractorCall};"); |
| | 17 | 432 | | } |
| | | 433 | | |
| | | 434 | | /// <summary> |
| | | 435 | | /// Resolves the C# variable-declaration type for a parameter. For nullable reference |
| | | 436 | | /// types (where <see cref="AgentFunctionParameterInfo.TypeFullName"/> does not already |
| | | 437 | | /// carry a trailing <c>?</c> from Roslyn's nullable-value-type shorthand), appends |
| | | 438 | | /// <c>?</c> so the declaration accepts a <see langword="null"/> assignment without |
| | | 439 | | /// warnings under <c>#nullable enable</c>. For nullable value types, the type name |
| | | 440 | | /// already ends with <c>?</c> (e.g., <c>global::System.Int32?</c>) and is returned |
| | | 441 | | /// unchanged to avoid the invalid <c>int??</c> shape. |
| | | 442 | | /// </summary> |
| | | 443 | | private static string GetVariableTypeForParam(AgentFunctionParameterInfo param) |
| | | 444 | | { |
| | 42 | 445 | | if (param.IsNullable && !param.TypeFullName.EndsWith("?")) |
| | 2 | 446 | | return param.TypeFullName + "?"; |
| | 40 | 447 | | return param.TypeFullName; |
| | | 448 | | } |
| | | 449 | | |
| | | 450 | | /// <summary> |
| | | 451 | | /// Emits enum-aware extraction. The JSON schema treats enums as <c>"string"</c> (LLMs |
| | | 452 | | /// emit enum values as strings), but the variable type is the enum itself — so the raw |
| | | 453 | | /// pipeline of <c>GetStringArgument</c> won't compile against an enum target. This |
| | | 454 | | /// emission gates with <c>AgentFrameworkArgumentExtractor.IsArgumentSupplied</c>, then |
| | | 455 | | /// routes the supplied string through <c>Enum.Parse<T>(s, ignoreCase: true)</c>. |
| | | 456 | | /// Default-value semantics mirror <see cref="AppendPrimitiveExtraction"/>: required → |
| | | 457 | | /// fail-fast guard; defaulted → emit the captured enum-member literal; nullable, no |
| | | 458 | | /// default → fall back to <see langword="null"/>. |
| | | 459 | | /// </summary> |
| | | 460 | | private static void AppendEnumExtraction( |
| | | 461 | | StringBuilder sb, |
| | | 462 | | AgentFunctionTypeInfo type, |
| | | 463 | | AgentFunctionMethodInfo method, |
| | | 464 | | AgentFunctionParameterInfo param, |
| | | 465 | | string rawVar) |
| | | 466 | | { |
| | 2 | 467 | | var varType = GetVariableTypeForParam(param); |
| | 2 | 468 | | var enumType = param.TypeFullName.TrimEnd('?'); |
| | 2 | 469 | | var stringExtract = $"{ExtractorFqn}.GetStringArgument({rawVar})"; |
| | 2 | 470 | | var enumParse = $"global::System.Enum.Parse<{enumType}>({stringExtract}, ignoreCase: true)"; |
| | | 471 | | |
| | 2 | 472 | | if (param.IsRequired) |
| | | 473 | | { |
| | 1 | 474 | | var toolMethodName = $"{AgentDiscoveryHelper.GetShortName(type.TypeName)}.{method.MethodName}"; |
| | 1 | 475 | | sb.AppendLine($" if (!{ExtractorFqn}.IsArgumentSupplied({rawVar}))"); |
| | 1 | 476 | | sb.AppendLine(" {"); |
| | 1 | 477 | | sb.AppendLine(" throw new global::System.ArgumentException("); |
| | 1 | 478 | | sb.AppendLine($" \"Required argument '{param.Name}' was not supplied to AIFunction '{tool |
| | 1 | 479 | | sb.AppendLine(" nameof(arguments));"); |
| | 1 | 480 | | sb.AppendLine(" }"); |
| | 1 | 481 | | sb.AppendLine($" {varType} {param.Name} = {enumParse};"); |
| | 1 | 482 | | return; |
| | | 483 | | } |
| | | 484 | | |
| | 1 | 485 | | var fallback = param.HasDefault ? param.DefaultLiteral! : "null"; |
| | 1 | 486 | | sb.AppendLine($" {varType} {param.Name};"); |
| | 1 | 487 | | sb.AppendLine($" if (!{ExtractorFqn}.IsArgumentSupplied({rawVar}))"); |
| | 1 | 488 | | sb.AppendLine($" {param.Name} = {fallback};"); |
| | 1 | 489 | | sb.AppendLine(" else"); |
| | 1 | 490 | | sb.AppendLine($" {param.Name} = {enumParse};"); |
| | 1 | 491 | | } |
| | | 492 | | |
| | | 493 | | /// <summary> |
| | | 494 | | /// Resolves the right helper for a "string" schema type, using the |
| | | 495 | | /// <see cref="AgentFunctionParameterInfo.JsonSchemaFormat"/> hint and the C# type to |
| | | 496 | | /// route <see cref="System.Guid"/>/<see cref="System.DateTime"/>/<see cref="System.DateTimeOffset"/>/ |
| | | 497 | | /// <see cref="System.TimeSpan"/> through their typed extractors instead of |
| | | 498 | | /// <c>GetStringArgument</c> (which would fail to compile against a non-string parameter type). |
| | | 499 | | /// JSON Schema collapses <see cref="System.DateTime"/> and <see cref="System.DateTimeOffset"/> |
| | | 500 | | /// under the same <c>"date-time"</c> format; the C# type disambiguates. |
| | | 501 | | /// </summary> |
| | 18 | 502 | | private static string GetStringFamilyHelper(AgentFunctionParameterInfo param) => param.JsonSchemaFormat switch |
| | 18 | 503 | | { |
| | 2 | 504 | | "uuid" => "GetGuidArgument", |
| | 2 | 505 | | "duration" => "GetTimeSpanArgument", |
| | 4 | 506 | | "date-time" => param.TypeFullName.Contains("DateTimeOffset") ? "GetDateTimeOffsetArgument" : "GetDateTimeArgumen |
| | 10 | 507 | | _ => "GetStringArgument", |
| | 18 | 508 | | }; |
| | | 509 | | |
| | | 510 | | /// <summary> |
| | | 511 | | /// Resolves the right helper for a "string"-schema object property. Same disambiguation |
| | | 512 | | /// as <see cref="GetStringFamilyHelper(AgentFunctionParameterInfo)"/> but uses |
| | | 513 | | /// <see cref="ObjectPropertyInfo.CSharpTypeFullName"/> for the DateTime/DateTimeOffset split. |
| | | 514 | | /// </summary> |
| | 16 | 515 | | private static string GetStringFamilyHelperForProperty(ObjectPropertyInfo prop) => prop.SchemaFormat switch |
| | 16 | 516 | | { |
| | 2 | 517 | | "uuid" => "GetGuidArgument", |
| | 1 | 518 | | "duration" => "GetTimeSpanArgument", |
| | 2 | 519 | | "date-time" => prop.CSharpTypeFullName.Contains("DateTimeOffset") ? "GetDateTimeOffsetArgument" : "GetDateTimeAr |
| | 11 | 520 | | _ => "GetStringArgument", |
| | 16 | 521 | | }; |
| | | 522 | | |
| | | 523 | | private static string GetIntegerHelperForType(string typeFullName) |
| | | 524 | | { |
| | 16 | 525 | | if (typeFullName.Contains("System.Int64")) return "GetInt64Argument"; |
| | 14 | 526 | | if (typeFullName.Contains("System.Int16")) return "GetInt16Argument"; |
| | 14 | 527 | | if (typeFullName.Contains("System.SByte")) return "GetSByteArgument"; |
| | 14 | 528 | | if (typeFullName.Contains("System.Byte")) return "GetByteArgument"; |
| | 14 | 529 | | if (typeFullName.Contains("System.UInt64")) return "GetUInt64Argument"; |
| | 14 | 530 | | if (typeFullName.Contains("System.UInt32")) return "GetUInt32Argument"; |
| | 14 | 531 | | if (typeFullName.Contains("System.UInt16")) return "GetUInt16Argument"; |
| | 14 | 532 | | return "GetInt32Argument"; |
| | | 533 | | } |
| | | 534 | | |
| | | 535 | | private static string GetNumberHelperForType(string typeFullName) |
| | | 536 | | { |
| | 9 | 537 | | if (typeFullName.Contains("System.Single")) return "GetSingleArgument"; |
| | 7 | 538 | | if (typeFullName.Contains("System.Decimal")) return "GetDecimalArgument"; |
| | 3 | 539 | | return "GetDoubleArgument"; |
| | | 540 | | } |
| | | 541 | | |
| | | 542 | | /// <summary> |
| | | 543 | | /// Emits per-property assignment statements for a complex object — used by both the |
| | | 544 | | /// array-of-objects branch (one assignment block per array element) and the top-level |
| | | 545 | | /// DTO branch (one assignment block for the parameter itself). Mirrors the schema-side |
| | | 546 | | /// machinery in <c>BuildObjectSchemaJson</c> but on the C# code-emit side. |
| | | 547 | | /// <para> |
| | | 548 | | /// Each property assignment is gated on both <c>TryGetProperty</c> (key present) and an |
| | | 549 | | /// inline <c>JsonValueKind.Null</c>/<c>JsonValueKind.Undefined</c> check (value supplied). |
| | | 550 | | /// When the value is missing or null, the property is left at whatever the parent |
| | | 551 | | /// <c>new T()</c> established — which respects any C# init-default declared on the |
| | | 552 | | /// property (e.g., <c>public string Foo { get; init; } = "default";</c>) without the |
| | | 553 | | /// generator needing to re-emit the literal. This avoids invoking the strict extractors |
| | | 554 | | /// (which throw on null) and makes <c>{"foo": null}</c> payloads symmetric with omitted |
| | | 555 | | /// keys. |
| | | 556 | | /// </para> |
| | | 557 | | /// </summary> |
| | | 558 | | private static void AppendObjectPropertyAssignments( |
| | | 559 | | StringBuilder sb, |
| | | 560 | | string targetVar, |
| | | 561 | | string sourceJsonElementVar, |
| | | 562 | | IReadOnlyList<ObjectPropertyInfo> properties, |
| | | 563 | | string indent) |
| | | 564 | | { |
| | 62 | 565 | | foreach (var prop in properties) |
| | | 566 | | { |
| | 22 | 567 | | sb.AppendLine($"{indent}if ({sourceJsonElementVar}.TryGetProperty(\"{prop.JsonName}\", out var _p_{prop.Json |
| | 22 | 568 | | sb.AppendLine($"{indent} _p_{prop.JsonName}.ValueKind != global::System.Text.Json.JsonValueKind.Null &&") |
| | 22 | 569 | | sb.AppendLine($"{indent} _p_{prop.JsonName}.ValueKind != global::System.Text.Json.JsonValueKind.Undefined |
| | 22 | 570 | | switch (prop.SchemaType) |
| | | 571 | | { |
| | | 572 | | case "string": |
| | 16 | 573 | | sb.AppendLine($"{indent} {targetVar}.{prop.CSharpName} = {ExtractorFqn}.{GetStringFamilyHelperFor |
| | 16 | 574 | | break; |
| | | 575 | | case "integer": |
| | 4 | 576 | | sb.AppendLine($"{indent} {targetVar}.{prop.CSharpName} = {ExtractorFqn}.{GetIntegerHelperForType( |
| | 4 | 577 | | break; |
| | | 578 | | case "number": |
| | 1 | 579 | | sb.AppendLine($"{indent} {targetVar}.{prop.CSharpName} = {ExtractorFqn}.{GetNumberHelperForType(p |
| | 1 | 580 | | break; |
| | | 581 | | case "boolean": |
| | 1 | 582 | | sb.AppendLine($"{indent} {targetVar}.{prop.CSharpName} = {ExtractorFqn}.GetBooleanArgument(_p_{pr |
| | 1 | 583 | | break; |
| | | 584 | | default: |
| | 0 | 585 | | sb.AppendLine($"{indent} {targetVar}.{prop.CSharpName} = {ExtractorFqn}.GetStringArgument(_p_{pro |
| | | 586 | | break; |
| | | 587 | | } |
| | | 588 | | } |
| | 9 | 589 | | } |
| | | 590 | | |
| | | 591 | | /// <summary> |
| | | 592 | | /// Extracts the element type from an array type's fully-qualified name. |
| | | 593 | | /// E.g., <c>"global::MyNamespace.FeedbackEntry[]"</c> → <c>"global::MyNamespace.FeedbackEntry"</c>. |
| | | 594 | | /// </summary> |
| | | 595 | | private static string GetArrayElementType(string arrayTypeFullName) |
| | | 596 | | { |
| | | 597 | | // Handle T[] syntax |
| | 8 | 598 | | if (arrayTypeFullName.EndsWith("[]")) |
| | 8 | 599 | | return arrayTypeFullName.Substring(0, arrayTypeFullName.Length - 2); |
| | | 600 | | |
| | | 601 | | // Fallback: return as-is (shouldn't happen for valid array types) |
| | 0 | 602 | | return arrayTypeFullName; |
| | | 603 | | } |
| | | 604 | | } |