| | | 1 | | using System.Globalization; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | |
| | | 4 | | namespace NexusLabs.Needlr.AgentFramework; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Kind-tolerant argument extractors for source-generated <c>[AgentFunction]</c> wrappers. |
| | | 8 | | /// </summary> |
| | | 9 | | /// <remarks> |
| | | 10 | | /// <para> |
| | | 11 | | /// <c>Microsoft.Extensions.AI.AIFunctionArguments</c> delivers tool argument values as |
| | | 12 | | /// <see langword="object"/> — but the underlying <c>IChatClient</c> determines the |
| | | 13 | | /// runtime shape: |
| | | 14 | | /// </para> |
| | | 15 | | /// <list type="bullet"> |
| | | 16 | | /// <item> |
| | | 17 | | /// <description> |
| | | 18 | | /// GitHub Copilot's <c>IChatClient</c> stringifies values: arrays/objects arrive as |
| | | 19 | | /// <see cref="JsonElement"/> with <see cref="JsonValueKind.String"/>. |
| | | 20 | | /// </description> |
| | | 21 | | /// </item> |
| | | 22 | | /// <item> |
| | | 23 | | /// <description> |
| | | 24 | | /// <c>AzureOpenAIClient.AsIChatClient()</c> (and most others) parse the model's tool-call |
| | | 25 | | /// JSON literally: arrays arrive as <see cref="JsonValueKind.Array"/>, objects as |
| | | 26 | | /// <see cref="JsonValueKind.Object"/>, numbers as <see cref="JsonValueKind.Number"/>, etc. |
| | | 27 | | /// </description> |
| | | 28 | | /// </item> |
| | | 29 | | /// </list> |
| | | 30 | | /// <para> |
| | | 31 | | /// Calling <c>JsonElement.GetString()</c> / <c>GetInt32()</c> / <c>GetBoolean()</c> |
| | | 32 | | /// directly throws <see cref="InvalidOperationException"/> when <see cref="JsonValueKind"/> |
| | | 33 | | /// doesn't match. These extractors translate per-kind so the source generator can emit a |
| | | 34 | | /// single uniform call regardless of the chat client's delivery shape. |
| | | 35 | | /// </para> |
| | | 36 | | /// <para> |
| | | 37 | | /// <strong>Extractors assume the value is present and non-null.</strong> Every extractor |
| | | 38 | | /// throws on <see langword="null"/> raws, on <see cref="JsonValueKind.Null"/>, and on |
| | | 39 | | /// <see cref="JsonValueKind.Undefined"/>. The generator is responsible for missing-key / |
| | | 40 | | /// null / undefined handling — typically by gating each extraction call with |
| | | 41 | | /// <see cref="IsArgumentSupplied(object?)"/> and short-circuiting to a declared default |
| | | 42 | | /// value or to <see langword="null"/> for nullable parameter types. This keeps the |
| | | 43 | | /// presence/optionality concern at the generator layer where the C# parameter metadata |
| | | 44 | | /// (<c>HasExplicitDefaultValue</c>, <c>NullableAnnotation</c>) lives, and keeps the |
| | | 45 | | /// extractors focused on kind-tolerant decoding of <em>present</em> values. |
| | | 46 | | /// </para> |
| | | 47 | | /// <para> |
| | | 48 | | /// <strong>Strict semantics for typed primitives.</strong> Booleans receiving numeric kinds |
| | | 49 | | /// throw rather than coerce <c>0</c>/<c>1</c> — the model is violating its own schema; the |
| | | 50 | | /// helper does not paper over it. Numeric extractors prefer the precision-preserving |
| | | 51 | | /// <c>TryGet*</c> overload (<c>TryGetDecimal</c> for decimal, <c>TryGetDouble</c> for double) |
| | | 52 | | /// and fall back to invariant-culture parsing on <see cref="JsonValueKind.String"/>. |
| | | 53 | | /// </para> |
| | | 54 | | /// <para> |
| | | 55 | | /// <strong>Supported parameter types.</strong> <see cref="string"/>, <see cref="bool"/>, the |
| | | 56 | | /// 8 integer types (<see cref="byte"/>/<see cref="sbyte"/>/<see cref="short"/>/<see cref="ushort"/>/ |
| | | 57 | | /// <see cref="int"/>/<see cref="uint"/>/<see cref="long"/>/<see cref="ulong"/>), |
| | | 58 | | /// <see cref="float"/>/<see cref="double"/>/<see cref="decimal"/>, <see cref="Guid"/>, |
| | | 59 | | /// <see cref="DateTime"/>, <see cref="DateTimeOffset"/>, and <see cref="TimeSpan"/>. JSON has |
| | | 60 | | /// no native kind for the temporal/GUID types — the model emits a string and the extractor |
| | | 61 | | /// parses it (ISO 8601 for date-time / duration, GUID literal for <see cref="Guid"/>). |
| | | 62 | | /// </para> |
| | | 63 | | /// </remarks> |
| | | 64 | | public static class AgentFrameworkArgumentExtractor |
| | | 65 | | { |
| | | 66 | | /// <summary> |
| | | 67 | | /// Returns <see langword="true"/> when <paramref name="raw"/> represents a value the |
| | | 68 | | /// extractor methods are willing to decode. Returns <see langword="false"/> for |
| | | 69 | | /// <see langword="null"/> raws, <see cref="JsonValueKind.Null"/>, and |
| | | 70 | | /// <see cref="JsonValueKind.Undefined"/> — these mean the chat client did not supply the |
| | | 71 | | /// argument and the generator-emitted wrapper should fall back to the parameter's |
| | | 72 | | /// declared default value (or <see langword="null"/> for nullable parameters), or throw |
| | | 73 | | /// <see cref="ArgumentException"/> for required parameters. |
| | | 74 | | /// </summary> |
| | | 75 | | /// <param name="raw">The raw argument value as delivered by <c>AIFunctionArguments</c>.</param> |
| | | 76 | | /// <returns> |
| | | 77 | | /// <see langword="false"/> when the argument is missing/null/undefined; <see langword="true"/> |
| | | 78 | | /// otherwise (including for typed values, JSON strings, numbers, booleans, arrays, and objects). |
| | | 79 | | /// </returns> |
| | | 80 | | /// <remarks> |
| | | 81 | | /// This is the documented gate for the extractor methods on this class. Source-generated |
| | | 82 | | /// agent-function wrappers call this once per parameter site to decide whether to invoke the |
| | | 83 | | /// kind-tolerant extractor or to short-circuit to a fallback. The check is intentionally |
| | | 84 | | /// inexpensive — a single null check plus, for <see cref="JsonElement"/>, two |
| | | 85 | | /// <see cref="JsonValueKind"/> comparisons. |
| | | 86 | | /// </remarks> |
| | | 87 | | public static bool IsArgumentSupplied(object? raw) |
| | | 88 | | { |
| | 57 | 89 | | if (raw is null) |
| | | 90 | | { |
| | 17 | 91 | | return false; |
| | | 92 | | } |
| | | 93 | | |
| | 40 | 94 | | if (raw is JsonElement je && |
| | 40 | 95 | | (je.ValueKind == JsonValueKind.Null || je.ValueKind == JsonValueKind.Undefined)) |
| | | 96 | | { |
| | 8 | 97 | | return false; |
| | | 98 | | } |
| | | 99 | | |
| | 32 | 100 | | return true; |
| | | 101 | | } |
| | | 102 | | |
| | | 103 | | /// <summary> |
| | | 104 | | /// Extracts a <see cref="string"/> argument from a raw <see cref="object"/> delivered |
| | | 105 | | /// by <c>AIFunctionArguments</c>. |
| | | 106 | | /// </summary> |
| | | 107 | | /// <param name="raw">The raw argument value.</param> |
| | | 108 | | /// <returns> |
| | | 109 | | /// <see cref="JsonElement"/> with <see cref="JsonValueKind.String"/> → |
| | | 110 | | /// <see cref="JsonElement.GetString"/> (or empty string if the JSON string is null);<br/> |
| | | 111 | | /// <see cref="JsonValueKind.Array"/>, <see cref="JsonValueKind.Object"/>, |
| | | 112 | | /// <see cref="JsonValueKind.Number"/>, <see cref="JsonValueKind.True"/>, |
| | | 113 | | /// <see cref="JsonValueKind.False"/> → <see cref="JsonElement.GetRawText"/>;<br/> |
| | | 114 | | /// already-typed <see cref="string"/> → as-is;<br/> |
| | | 115 | | /// any other object → <see cref="object.ToString"/> (or empty string). |
| | | 116 | | /// </returns> |
| | | 117 | | /// <exception cref="InvalidOperationException"> |
| | | 118 | | /// Thrown when <paramref name="raw"/> is <see langword="null"/>, <see cref="JsonValueKind.Null"/>, |
| | | 119 | | /// or <see cref="JsonValueKind.Undefined"/>. Callers must gate with |
| | | 120 | | /// <see cref="IsArgumentSupplied(object?)"/> first. |
| | | 121 | | /// </exception> |
| | | 122 | | public static string GetStringArgument(object? raw) |
| | | 123 | | { |
| | 28 | 124 | | if (raw is null) |
| | | 125 | | { |
| | 1 | 126 | | throw new InvalidOperationException( |
| | 1 | 127 | | "Cannot extract string argument from null."); |
| | | 128 | | } |
| | | 129 | | |
| | 27 | 130 | | if (raw is JsonElement je) |
| | | 131 | | { |
| | 24 | 132 | | return je.ValueKind switch |
| | 24 | 133 | | { |
| | 12 | 134 | | JsonValueKind.String => je.GetString() ?? string.Empty, |
| | 24 | 135 | | JsonValueKind.Null or JsonValueKind.Undefined => |
| | 2 | 136 | | throw new InvalidOperationException( |
| | 2 | 137 | | $"Cannot extract string argument: unexpected JsonValueKind {je.ValueKind}."), |
| | 10 | 138 | | _ => je.GetRawText(), |
| | 24 | 139 | | }; |
| | | 140 | | } |
| | | 141 | | |
| | 3 | 142 | | if (raw is string s) |
| | | 143 | | { |
| | 2 | 144 | | return s; |
| | | 145 | | } |
| | | 146 | | |
| | 1 | 147 | | return raw.ToString() ?? string.Empty; |
| | | 148 | | } |
| | | 149 | | |
| | | 150 | | /// <summary> |
| | | 151 | | /// Extracts a <see cref="bool"/> argument with strict kind semantics. |
| | | 152 | | /// </summary> |
| | | 153 | | /// <param name="raw">The raw argument value.</param> |
| | | 154 | | /// <returns> |
| | | 155 | | /// <see cref="JsonValueKind.True"/>/<see cref="JsonValueKind.False"/> → |
| | | 156 | | /// <see cref="JsonElement.GetBoolean"/>;<br/> |
| | | 157 | | /// <see cref="JsonValueKind.String"/> → <see cref="bool.TryParse(string?, out bool)"/>;<br/> |
| | | 158 | | /// already-typed <see cref="bool"/> → as-is. |
| | | 159 | | /// </returns> |
| | | 160 | | /// <exception cref="InvalidOperationException"> |
| | | 161 | | /// Thrown for <see cref="JsonValueKind.Number"/>, <see cref="JsonValueKind.Array"/>, |
| | | 162 | | /// <see cref="JsonValueKind.Object"/>, <see cref="JsonValueKind.Null"/>, |
| | | 163 | | /// <see cref="JsonValueKind.Undefined"/>, or unparseable strings such as <c>"1"</c> or |
| | | 164 | | /// <c>"yes"</c>. This is intentional — silently coercing <c>0</c>/<c>1</c> or |
| | | 165 | | /// <c>"yes"</c>/<c>"no"</c> would mask schema violations from the model. |
| | | 166 | | /// </exception> |
| | | 167 | | public static bool GetBooleanArgument(object? raw) |
| | | 168 | | { |
| | 17 | 169 | | if (raw is bool b) |
| | | 170 | | { |
| | 2 | 171 | | return b; |
| | | 172 | | } |
| | | 173 | | |
| | 15 | 174 | | if (raw is JsonElement je) |
| | | 175 | | { |
| | 14 | 176 | | switch (je.ValueKind) |
| | | 177 | | { |
| | | 178 | | case JsonValueKind.True: |
| | | 179 | | case JsonValueKind.False: |
| | 4 | 180 | | return je.GetBoolean(); |
| | | 181 | | case JsonValueKind.String: |
| | 6 | 182 | | var s = je.GetString(); |
| | 6 | 183 | | if (bool.TryParse(s, out var parsed)) |
| | | 184 | | { |
| | 4 | 185 | | return parsed; |
| | | 186 | | } |
| | 2 | 187 | | throw new InvalidOperationException( |
| | 2 | 188 | | $"Cannot extract bool argument: JSON String '{s}' is not 'true' or 'false'."); |
| | | 189 | | default: |
| | 4 | 190 | | throw new InvalidOperationException( |
| | 4 | 191 | | $"Cannot extract bool argument: unexpected JsonValueKind {je.ValueKind}."); |
| | | 192 | | } |
| | | 193 | | } |
| | | 194 | | |
| | 1 | 195 | | throw new InvalidOperationException( |
| | 1 | 196 | | $"Cannot extract bool argument from {raw?.GetType().FullName ?? "null"}."); |
| | | 197 | | } |
| | | 198 | | |
| | | 199 | | /// <summary>Extracts an <see cref="int"/> argument.</summary> |
| | | 200 | | /// <param name="raw">The raw argument value.</param> |
| | | 201 | | public static int GetInt32Argument(object? raw) |
| | 17 | 202 | | => ExtractInteger<int>( |
| | 17 | 203 | | raw, |
| | 10 | 204 | | tryNumber: (JsonElement je, out int v) => je.TryGetInt32(out v), |
| | 21 | 205 | | tryParseInvariant: s => int.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var v) ? v : |
| | | 206 | | |
| | | 207 | | /// <summary>Extracts a <see cref="long"/> argument.</summary> |
| | | 208 | | /// <param name="raw">The raw argument value.</param> |
| | | 209 | | public static long GetInt64Argument(object? raw) |
| | 1 | 210 | | => ExtractInteger<long>( |
| | 1 | 211 | | raw, |
| | 1 | 212 | | tryNumber: (JsonElement je, out long v) => je.TryGetInt64(out v), |
| | 1 | 213 | | tryParseInvariant: s => long.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var v) ? v |
| | | 214 | | |
| | | 215 | | /// <summary>Extracts a <see cref="short"/> argument.</summary> |
| | | 216 | | /// <param name="raw">The raw argument value.</param> |
| | | 217 | | public static short GetInt16Argument(object? raw) |
| | 1 | 218 | | => ExtractInteger<short>( |
| | 1 | 219 | | raw, |
| | 1 | 220 | | tryNumber: (JsonElement je, out short v) => je.TryGetInt16(out v), |
| | 1 | 221 | | tryParseInvariant: s => short.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var v) ? v |
| | | 222 | | |
| | | 223 | | /// <summary>Extracts an <see cref="sbyte"/> argument.</summary> |
| | | 224 | | /// <param name="raw">The raw argument value.</param> |
| | | 225 | | public static sbyte GetSByteArgument(object? raw) |
| | 0 | 226 | | => ExtractInteger<sbyte>( |
| | 0 | 227 | | raw, |
| | 0 | 228 | | tryNumber: (JsonElement je, out sbyte v) => je.TryGetSByte(out v), |
| | 0 | 229 | | tryParseInvariant: s => sbyte.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var v) ? v |
| | | 230 | | |
| | | 231 | | /// <summary>Extracts a <see cref="byte"/> argument.</summary> |
| | | 232 | | /// <param name="raw">The raw argument value.</param> |
| | | 233 | | public static byte GetByteArgument(object? raw) |
| | 1 | 234 | | => ExtractInteger<byte>( |
| | 1 | 235 | | raw, |
| | 1 | 236 | | tryNumber: (JsonElement je, out byte v) => je.TryGetByte(out v), |
| | 1 | 237 | | tryParseInvariant: s => byte.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var v) ? v |
| | | 238 | | |
| | | 239 | | /// <summary>Extracts a <see cref="ushort"/> argument.</summary> |
| | | 240 | | /// <param name="raw">The raw argument value.</param> |
| | | 241 | | public static ushort GetUInt16Argument(object? raw) |
| | 0 | 242 | | => ExtractInteger<ushort>( |
| | 0 | 243 | | raw, |
| | 0 | 244 | | tryNumber: (JsonElement je, out ushort v) => je.TryGetUInt16(out v), |
| | 0 | 245 | | tryParseInvariant: s => ushort.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var v) ? |
| | | 246 | | |
| | | 247 | | /// <summary>Extracts a <see cref="uint"/> argument.</summary> |
| | | 248 | | /// <param name="raw">The raw argument value.</param> |
| | | 249 | | public static uint GetUInt32Argument(object? raw) |
| | 1 | 250 | | => ExtractInteger<uint>( |
| | 1 | 251 | | raw, |
| | 1 | 252 | | tryNumber: (JsonElement je, out uint v) => je.TryGetUInt32(out v), |
| | 1 | 253 | | tryParseInvariant: s => uint.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var v) ? v |
| | | 254 | | |
| | | 255 | | /// <summary>Extracts a <see cref="ulong"/> argument.</summary> |
| | | 256 | | /// <param name="raw">The raw argument value.</param> |
| | | 257 | | public static ulong GetUInt64Argument(object? raw) |
| | 0 | 258 | | => ExtractInteger<ulong>( |
| | 0 | 259 | | raw, |
| | 0 | 260 | | tryNumber: (JsonElement je, out ulong v) => je.TryGetUInt64(out v), |
| | 0 | 261 | | tryParseInvariant: s => ulong.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out var v) ? v |
| | | 262 | | |
| | | 263 | | /// <summary>Extracts a <see cref="float"/> argument.</summary> |
| | | 264 | | /// <param name="raw">The raw argument value.</param> |
| | | 265 | | /// <remarks> |
| | | 266 | | /// Rejects non-finite values (<see cref="float.NaN"/>, <see cref="float.PositiveInfinity"/>, |
| | | 267 | | /// <see cref="float.NegativeInfinity"/>) — JSON itself does not represent them, so receiving |
| | | 268 | | /// one indicates schema violation. |
| | | 269 | | /// </remarks> |
| | | 270 | | public static float GetSingleArgument(object? raw) |
| | 4 | 271 | | => ExtractFloat<float>( |
| | 4 | 272 | | raw, |
| | 1 | 273 | | tryNumber: (JsonElement je, out float v) => je.TryGetSingle(out v), |
| | 1 | 274 | | tryParseInvariant: s => float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var v) ? v : |
| | 4 | 275 | | isFinite: float.IsFinite); |
| | | 276 | | |
| | | 277 | | /// <summary>Extracts a <see cref="double"/> argument with precision-first decoding.</summary> |
| | | 278 | | /// <param name="raw">The raw argument value.</param> |
| | | 279 | | /// <remarks> |
| | | 280 | | /// Uses <see cref="JsonElement.TryGetDouble"/> on <see cref="JsonValueKind.Number"/> for |
| | | 281 | | /// IEEE-754 fidelity. Rejects non-finite values per JSON spec. |
| | | 282 | | /// </remarks> |
| | | 283 | | public static double GetDoubleArgument(object? raw) |
| | 2 | 284 | | => ExtractFloat<double>( |
| | 2 | 285 | | raw, |
| | 1 | 286 | | tryNumber: (JsonElement je, out double v) => je.TryGetDouble(out v), |
| | 0 | 287 | | tryParseInvariant: s => double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out var v) ? v |
| | 2 | 288 | | isFinite: double.IsFinite); |
| | | 289 | | |
| | | 290 | | /// <summary>Extracts a <see cref="decimal"/> argument with precision-preserving decoding.</summary> |
| | | 291 | | /// <param name="raw">The raw argument value.</param> |
| | | 292 | | /// <remarks> |
| | | 293 | | /// Uses <see cref="JsonElement.TryGetDecimal"/> on <see cref="JsonValueKind.Number"/> first |
| | | 294 | | /// to preserve precision that would be lost via a <see cref="double"/> round-trip. Falls |
| | | 295 | | /// back to invariant-culture parsing for <see cref="JsonValueKind.String"/>. |
| | | 296 | | /// </remarks> |
| | | 297 | | public static decimal GetDecimalArgument(object? raw) |
| | | 298 | | { |
| | 5 | 299 | | if (raw is decimal d) |
| | | 300 | | { |
| | 1 | 301 | | return d; |
| | | 302 | | } |
| | | 303 | | |
| | 4 | 304 | | if (raw is JsonElement je) |
| | | 305 | | { |
| | 4 | 306 | | switch (je.ValueKind) |
| | | 307 | | { |
| | | 308 | | case JsonValueKind.Number: |
| | 2 | 309 | | if (je.TryGetDecimal(out var v)) |
| | | 310 | | { |
| | 2 | 311 | | return v; |
| | | 312 | | } |
| | 0 | 313 | | throw new InvalidOperationException( |
| | 0 | 314 | | $"Cannot extract decimal argument: JSON Number '{je.GetRawText()}' is not representable as decim |
| | | 315 | | case JsonValueKind.String: |
| | 2 | 316 | | var s = je.GetString(); |
| | 2 | 317 | | if (decimal.TryParse(s, NumberStyles.Number, CultureInfo.InvariantCulture, out var parsed)) |
| | | 318 | | { |
| | 1 | 319 | | return parsed; |
| | | 320 | | } |
| | 1 | 321 | | throw new InvalidOperationException( |
| | 1 | 322 | | $"Cannot extract decimal argument: JSON String '{s}' is not a numeric literal."); |
| | | 323 | | default: |
| | 0 | 324 | | throw new InvalidOperationException( |
| | 0 | 325 | | $"Cannot extract decimal argument: unexpected JsonValueKind {je.ValueKind}."); |
| | | 326 | | } |
| | | 327 | | } |
| | | 328 | | |
| | 0 | 329 | | throw new InvalidOperationException( |
| | 0 | 330 | | $"Cannot extract decimal argument from {raw?.GetType().FullName ?? "null"}."); |
| | | 331 | | } |
| | | 332 | | |
| | | 333 | | /// <summary>Extracts a <see cref="Guid"/> argument.</summary> |
| | | 334 | | /// <param name="raw">The raw argument value.</param> |
| | | 335 | | /// <remarks> |
| | | 336 | | /// JSON has no native GUID kind — the model emits a string. Uses |
| | | 337 | | /// <see cref="JsonElement.TryGetGuid"/> on <see cref="JsonValueKind.String"/>; throws on |
| | | 338 | | /// any other kind to surface schema violations rather than silently substituting |
| | | 339 | | /// <see cref="Guid.Empty"/>. |
| | | 340 | | /// </remarks> |
| | | 341 | | public static Guid GetGuidArgument(object? raw) |
| | | 342 | | { |
| | 11 | 343 | | if (raw is Guid g) |
| | | 344 | | { |
| | 1 | 345 | | return g; |
| | | 346 | | } |
| | | 347 | | |
| | 10 | 348 | | if (raw is JsonElement je) |
| | | 349 | | { |
| | 9 | 350 | | switch (je.ValueKind) |
| | | 351 | | { |
| | | 352 | | case JsonValueKind.String: |
| | 7 | 353 | | if (je.TryGetGuid(out var v)) |
| | | 354 | | { |
| | 5 | 355 | | return v; |
| | | 356 | | } |
| | 2 | 357 | | throw new InvalidOperationException( |
| | 2 | 358 | | $"Cannot extract Guid argument: JSON String '{je.GetString()}' is not a valid GUID."); |
| | | 359 | | default: |
| | 2 | 360 | | throw new InvalidOperationException( |
| | 2 | 361 | | $"Cannot extract Guid argument: unexpected JsonValueKind {je.ValueKind}."); |
| | | 362 | | } |
| | | 363 | | } |
| | | 364 | | |
| | 1 | 365 | | throw new InvalidOperationException( |
| | 1 | 366 | | $"Cannot extract Guid argument from {raw?.GetType().FullName ?? "null"}."); |
| | | 367 | | } |
| | | 368 | | |
| | | 369 | | /// <summary>Extracts a <see cref="DateTime"/> argument from an ISO 8601 string.</summary> |
| | | 370 | | /// <param name="raw">The raw argument value.</param> |
| | | 371 | | /// <remarks> |
| | | 372 | | /// JSON has no native date-time kind — the model emits a string. Uses |
| | | 373 | | /// <see cref="JsonElement.TryGetDateTime"/> which accepts the JSON-Schema-spec |
| | | 374 | | /// <c>"date-time"</c> format (ISO 8601 with optional offset). |
| | | 375 | | /// </remarks> |
| | | 376 | | public static DateTime GetDateTimeArgument(object? raw) |
| | | 377 | | { |
| | 7 | 378 | | if (raw is DateTime dt) |
| | | 379 | | { |
| | 1 | 380 | | return dt; |
| | | 381 | | } |
| | | 382 | | |
| | 6 | 383 | | if (raw is JsonElement je) |
| | | 384 | | { |
| | 6 | 385 | | switch (je.ValueKind) |
| | | 386 | | { |
| | | 387 | | case JsonValueKind.String: |
| | 5 | 388 | | if (je.TryGetDateTime(out var v)) |
| | | 389 | | { |
| | 4 | 390 | | return v; |
| | | 391 | | } |
| | 1 | 392 | | throw new InvalidOperationException( |
| | 1 | 393 | | $"Cannot extract DateTime argument: JSON String '{je.GetString()}' is not a valid ISO 8601 date- |
| | | 394 | | default: |
| | 1 | 395 | | throw new InvalidOperationException( |
| | 1 | 396 | | $"Cannot extract DateTime argument: unexpected JsonValueKind {je.ValueKind}."); |
| | | 397 | | } |
| | | 398 | | } |
| | | 399 | | |
| | 0 | 400 | | throw new InvalidOperationException( |
| | 0 | 401 | | $"Cannot extract DateTime argument from {raw?.GetType().FullName ?? "null"}."); |
| | | 402 | | } |
| | | 403 | | |
| | | 404 | | /// <summary>Extracts a <see cref="DateTimeOffset"/> argument from an ISO 8601 string.</summary> |
| | | 405 | | /// <param name="raw">The raw argument value.</param> |
| | | 406 | | /// <remarks> |
| | | 407 | | /// JSON has no native date-time kind — the model emits a string with optional offset. |
| | | 408 | | /// Uses <see cref="JsonElement.TryGetDateTimeOffset"/>. |
| | | 409 | | /// </remarks> |
| | | 410 | | public static DateTimeOffset GetDateTimeOffsetArgument(object? raw) |
| | | 411 | | { |
| | 4 | 412 | | if (raw is DateTimeOffset dto) |
| | | 413 | | { |
| | 1 | 414 | | return dto; |
| | | 415 | | } |
| | | 416 | | |
| | 3 | 417 | | if (raw is JsonElement je) |
| | | 418 | | { |
| | 3 | 419 | | switch (je.ValueKind) |
| | | 420 | | { |
| | | 421 | | case JsonValueKind.String: |
| | 3 | 422 | | if (je.TryGetDateTimeOffset(out var v)) |
| | | 423 | | { |
| | 2 | 424 | | return v; |
| | | 425 | | } |
| | 1 | 426 | | throw new InvalidOperationException( |
| | 1 | 427 | | $"Cannot extract DateTimeOffset argument: JSON String '{je.GetString()}' is not a valid ISO 8601 |
| | | 428 | | default: |
| | 0 | 429 | | throw new InvalidOperationException( |
| | 0 | 430 | | $"Cannot extract DateTimeOffset argument: unexpected JsonValueKind {je.ValueKind}."); |
| | | 431 | | } |
| | | 432 | | } |
| | | 433 | | |
| | 0 | 434 | | throw new InvalidOperationException( |
| | 0 | 435 | | $"Cannot extract DateTimeOffset argument from {raw?.GetType().FullName ?? "null"}."); |
| | | 436 | | } |
| | | 437 | | |
| | | 438 | | /// <summary>Extracts a <see cref="TimeSpan"/> argument from a string.</summary> |
| | | 439 | | /// <param name="raw">The raw argument value.</param> |
| | | 440 | | /// <remarks> |
| | | 441 | | /// <para> |
| | | 442 | | /// JSON has no native duration kind. This helper accepts both common LLM outputs: |
| | | 443 | | /// </para> |
| | | 444 | | /// <list type="bullet"> |
| | | 445 | | /// <item> |
| | | 446 | | /// <description> |
| | | 447 | | /// .NET round-trip format like <c>"01:30:00"</c> or <c>"1.02:03:04"</c> via |
| | | 448 | | /// <see cref="TimeSpan.TryParse(string?, IFormatProvider?, out TimeSpan)"/> with invariant culture. |
| | | 449 | | /// </description> |
| | | 450 | | /// </item> |
| | | 451 | | /// <item> |
| | | 452 | | /// <description> |
| | | 453 | | /// JSON-Schema-spec ISO 8601 duration like <c>"PT1H30M"</c> via |
| | | 454 | | /// <see cref="System.Xml.XmlConvert.ToTimeSpan"/>. |
| | | 455 | | /// </description> |
| | | 456 | | /// </item> |
| | | 457 | | /// </list> |
| | | 458 | | /// </remarks> |
| | | 459 | | public static TimeSpan GetTimeSpanArgument(object? raw) |
| | | 460 | | { |
| | 11 | 461 | | if (raw is TimeSpan ts) |
| | | 462 | | { |
| | 1 | 463 | | return ts; |
| | | 464 | | } |
| | | 465 | | |
| | 10 | 466 | | if (raw is JsonElement je) |
| | | 467 | | { |
| | 10 | 468 | | switch (je.ValueKind) |
| | | 469 | | { |
| | | 470 | | case JsonValueKind.String: |
| | 8 | 471 | | var s = je.GetString(); |
| | 8 | 472 | | if (TryParseTimeSpan(s, out var v)) |
| | | 473 | | { |
| | 6 | 474 | | return v; |
| | | 475 | | } |
| | 2 | 476 | | throw new InvalidOperationException( |
| | 2 | 477 | | $"Cannot extract TimeSpan argument: JSON String '{s}' is neither a .NET duration ('hh:mm:ss') no |
| | | 478 | | default: |
| | 2 | 479 | | throw new InvalidOperationException( |
| | 2 | 480 | | $"Cannot extract TimeSpan argument: unexpected JsonValueKind {je.ValueKind}."); |
| | | 481 | | } |
| | | 482 | | } |
| | | 483 | | |
| | 0 | 484 | | throw new InvalidOperationException( |
| | 0 | 485 | | $"Cannot extract TimeSpan argument from {raw?.GetType().FullName ?? "null"}."); |
| | | 486 | | } |
| | | 487 | | |
| | | 488 | | private static bool TryParseTimeSpan(string? s, out TimeSpan result) |
| | | 489 | | { |
| | 8 | 490 | | if (string.IsNullOrWhiteSpace(s)) |
| | | 491 | | { |
| | 0 | 492 | | result = default; |
| | 0 | 493 | | return false; |
| | | 494 | | } |
| | | 495 | | |
| | 8 | 496 | | if (TimeSpan.TryParse(s, CultureInfo.InvariantCulture, out result)) |
| | | 497 | | { |
| | 2 | 498 | | return true; |
| | | 499 | | } |
| | | 500 | | |
| | | 501 | | try |
| | | 502 | | { |
| | 6 | 503 | | result = System.Xml.XmlConvert.ToTimeSpan(s!); |
| | 4 | 504 | | return true; |
| | | 505 | | } |
| | 2 | 506 | | catch (FormatException) |
| | | 507 | | { |
| | 2 | 508 | | result = default; |
| | 2 | 509 | | return false; |
| | | 510 | | } |
| | 6 | 511 | | } |
| | | 512 | | |
| | | 513 | | private delegate bool TryNumber<T>(JsonElement je, out T value); |
| | | 514 | | |
| | | 515 | | private static T ExtractInteger<T>( |
| | | 516 | | object? raw, |
| | | 517 | | TryNumber<T> tryNumber, |
| | | 518 | | Func<string?, T?> tryParseInvariant) |
| | | 519 | | where T : struct |
| | | 520 | | { |
| | 21 | 521 | | if (raw is T typed) |
| | | 522 | | { |
| | 1 | 523 | | return typed; |
| | | 524 | | } |
| | | 525 | | |
| | 20 | 526 | | if (raw is JsonElement je) |
| | | 527 | | { |
| | 19 | 528 | | switch (je.ValueKind) |
| | | 529 | | { |
| | | 530 | | case JsonValueKind.Number: |
| | 14 | 531 | | if (tryNumber(je, out var n)) |
| | | 532 | | { |
| | 12 | 533 | | return n; |
| | | 534 | | } |
| | 2 | 535 | | throw new InvalidOperationException( |
| | 2 | 536 | | $"Cannot extract {typeof(T).Name} argument: JSON Number '{je.GetRawText()}' " + |
| | 2 | 537 | | $"is out of range or has a fractional component."); |
| | | 538 | | case JsonValueKind.String: |
| | 4 | 539 | | var s = je.GetString(); |
| | 4 | 540 | | var parsed = tryParseInvariant(s); |
| | 4 | 541 | | if (parsed.HasValue) |
| | | 542 | | { |
| | 3 | 543 | | return parsed.Value; |
| | | 544 | | } |
| | 1 | 545 | | throw new InvalidOperationException( |
| | 1 | 546 | | $"Cannot extract {typeof(T).Name} argument: JSON String '{s}' is not a numeric literal."); |
| | | 547 | | default: |
| | 1 | 548 | | throw new InvalidOperationException( |
| | 1 | 549 | | $"Cannot extract {typeof(T).Name} argument: unexpected JsonValueKind {je.ValueKind}."); |
| | | 550 | | } |
| | | 551 | | } |
| | | 552 | | |
| | 1 | 553 | | throw new InvalidOperationException( |
| | 1 | 554 | | $"Cannot extract {typeof(T).Name} argument from {raw?.GetType().FullName ?? "null"}."); |
| | | 555 | | } |
| | | 556 | | |
| | | 557 | | private static T ExtractFloat<T>( |
| | | 558 | | object? raw, |
| | | 559 | | TryNumber<T> tryNumber, |
| | | 560 | | Func<string?, T?> tryParseInvariant, |
| | | 561 | | Func<T, bool> isFinite) |
| | | 562 | | where T : struct |
| | | 563 | | { |
| | 6 | 564 | | if (raw is T typed) |
| | | 565 | | { |
| | 3 | 566 | | if (!isFinite(typed)) |
| | | 567 | | { |
| | 3 | 568 | | throw new InvalidOperationException( |
| | 3 | 569 | | $"Cannot extract {typeof(T).Name} argument: value is not finite (NaN/Infinity)."); |
| | | 570 | | } |
| | 0 | 571 | | return typed; |
| | | 572 | | } |
| | | 573 | | |
| | 3 | 574 | | if (raw is JsonElement je) |
| | | 575 | | { |
| | 3 | 576 | | switch (je.ValueKind) |
| | | 577 | | { |
| | | 578 | | case JsonValueKind.Number: |
| | 2 | 579 | | if (tryNumber(je, out var n)) |
| | | 580 | | { |
| | 2 | 581 | | if (!isFinite(n)) |
| | | 582 | | { |
| | 0 | 583 | | throw new InvalidOperationException( |
| | 0 | 584 | | $"Cannot extract {typeof(T).Name} argument: " + |
| | 0 | 585 | | "JSON Number is not finite (NaN/Infinity)."); |
| | | 586 | | } |
| | 2 | 587 | | return n; |
| | | 588 | | } |
| | 0 | 589 | | throw new InvalidOperationException( |
| | 0 | 590 | | $"Cannot extract {typeof(T).Name} argument: JSON Number '{je.GetRawText()}' " + |
| | 0 | 591 | | $"is not representable as {typeof(T).Name}."); |
| | | 592 | | case JsonValueKind.String: |
| | 1 | 593 | | var s = je.GetString(); |
| | 1 | 594 | | var parsed = tryParseInvariant(s); |
| | 1 | 595 | | if (parsed.HasValue) |
| | | 596 | | { |
| | 1 | 597 | | if (!isFinite(parsed.Value)) |
| | | 598 | | { |
| | 0 | 599 | | throw new InvalidOperationException( |
| | 0 | 600 | | $"Cannot extract {typeof(T).Name} argument: " + |
| | 0 | 601 | | "parsed value is not finite (NaN/Infinity)."); |
| | | 602 | | } |
| | 1 | 603 | | return parsed.Value; |
| | | 604 | | } |
| | 0 | 605 | | throw new InvalidOperationException( |
| | 0 | 606 | | $"Cannot extract {typeof(T).Name} argument: JSON String '{s}' is not a numeric literal."); |
| | | 607 | | default: |
| | 0 | 608 | | throw new InvalidOperationException( |
| | 0 | 609 | | $"Cannot extract {typeof(T).Name} argument: unexpected JsonValueKind {je.ValueKind}."); |
| | | 610 | | } |
| | | 611 | | } |
| | | 612 | | |
| | 0 | 613 | | throw new InvalidOperationException( |
| | 0 | 614 | | $"Cannot extract {typeof(T).Name} argument from {raw?.GetType().FullName ?? "null"}."); |
| | | 615 | | } |
| | | 616 | | } |