forked from zhongkaifu/TensorSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStructuredOutputs.cs
More file actions
1027 lines (884 loc) · 38.2 KB
/
Copy pathStructuredOutputs.cs
File metadata and controls
1027 lines (884 loc) · 38.2 KB
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) Zhongkai Fu. All rights reserved.
// https://github.com/zhongkaifu/TensorSharp
//
// This file is part of TensorSharp.
//
// TensorSharp is licensed under the BSD-3-Clause license found in the LICENSE file in the root directory of this source tree.
//
// TensorSharp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the BSD-3-Clause License for more details.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
namespace TensorSharp.Runtime
{
public enum StructuredOutputKind
{
JsonObject,
JsonSchema
}
public sealed class StructuredOutputFormat
{
private StructuredOutputFormat(StructuredOutputKind kind, string? name = null,
string? schemaJson = null, bool strict = false, string? description = null)
{
Kind = kind;
Name = name;
SchemaJson = schemaJson;
Strict = strict;
Description = description;
}
public StructuredOutputKind Kind { get; }
public string? Name { get; }
public string? SchemaJson { get; }
public bool Strict { get; }
public string? Description { get; }
public static StructuredOutputFormat JsonObject()
=> new(StructuredOutputKind.JsonObject);
public static StructuredOutputFormat JsonSchema(string name, string schemaJson,
bool strict = true, string? description = null)
=> new(StructuredOutputKind.JsonSchema, name, schemaJson, strict, description);
}
public static class StructuredOutputPrompt
{
public static List<ChatMessage> Apply(List<ChatMessage> messages, StructuredOutputFormat format)
{
if (format == null)
return messages;
var result = new List<ChatMessage>(messages?.Count + 1 ?? 1);
string instruction = BuildInstruction(format);
if (messages != null && messages.Count > 0 &&
(messages[0].Role == "system" || messages[0].Role == "developer"))
{
var first = CloneMessage(messages[0])!;
first.Content = string.IsNullOrWhiteSpace(first.Content)
? instruction
: first.Content!.TrimEnd() + "\n\n" + instruction;
result.Add(first);
for (int i = 1; i < messages.Count; i++)
result.Add(CloneMessage(messages[i])!);
return result;
}
result.Add(new ChatMessage { Role = "system", Content = instruction });
if (messages != null)
{
foreach (var msg in messages)
result.Add(CloneMessage(msg)!);
}
return result;
}
public static string BuildInstruction(StructuredOutputFormat format)
{
if (format == null)
return "";
if (format.Kind == StructuredOutputKind.JsonObject)
{
return "You must answer with valid JSON. Return exactly one JSON object and nothing else. " +
"Do not include Markdown code fences, explanations, or extra text before or after the JSON.";
}
var sb = new StringBuilder();
sb.Append("You must answer with valid JSON that matches the provided JSON Schema exactly. ");
sb.Append("Return exactly one JSON object and nothing else. ");
sb.Append("Do not include Markdown code fences, explanations, or extra text before or after the JSON.");
sb.Append("\n\nStructured output schema name: ");
sb.Append(format.Name);
if (!string.IsNullOrWhiteSpace(format.Description))
{
sb.Append("\nSchema description: ");
sb.Append(format.Description.Trim());
}
sb.Append("\nRules:");
sb.Append("\n- Include every required property.");
sb.Append("\n- Do not add properties that are not defined in the schema.");
sb.Append("\n- Use `null` only when the schema allows it.");
sb.Append("\n- Keep property order aligned with the schema.");
sb.Append("\n\nJSON Schema:");
sb.Append("\n");
sb.Append(format.SchemaJson);
return sb.ToString();
}
private static ChatMessage? CloneMessage(ChatMessage msg)
{
if (msg == null)
return null;
return new ChatMessage
{
Role = msg.Role,
Content = msg.Content,
ImagePaths = msg.ImagePaths != null ? new List<string>(msg.ImagePaths) : null,
AudioPaths = msg.AudioPaths != null ? new List<string>(msg.AudioPaths) : null,
IsVideo = msg.IsVideo,
ToolCalls = msg.ToolCalls != null ? new List<ToolCall>(msg.ToolCalls) : null,
Thinking = msg.Thinking
};
}
}
public sealed class StructuredOutputSchemaValidationResult
{
public bool IsValid { get; init; }
public List<string> Errors { get; init; } = new();
public string? ErrorMessage
=> Errors.Count == 0 ? null : string.Join("; ", Errors);
}
public sealed class StructuredOutputNormalizationResult
{
public bool IsValid { get; init; }
public string NormalizedContent { get; init; } = string.Empty;
public List<string> Errors { get; init; } = new();
public string? ErrorMessage
=> Errors.Count == 0 ? null : string.Join("; ", Errors);
}
public static class StructuredOutputValidator
{
private static readonly HashSet<string> SupportedPrimitiveTypes = new(StringComparer.Ordinal)
{
"string", "number", "integer", "boolean", "object", "array", "null"
};
private static readonly HashSet<string> UnsupportedKeywords = new(StringComparer.Ordinal)
{
"allOf", "not", "dependentRequired", "dependentSchemas", "if", "then", "else",
"minLength", "maxLength", "pattern", "format",
"minimum", "maximum", "multipleOf",
"patternProperties",
"minItems", "maxItems"
};
public static StructuredOutputSchemaValidationResult ValidateSchema(StructuredOutputFormat format)
{
var result = new StructuredOutputSchemaValidationResult();
if (format == null || format.Kind == StructuredOutputKind.JsonObject)
return new StructuredOutputSchemaValidationResult { IsValid = true };
bool missingCriticalField = false;
if (string.IsNullOrWhiteSpace(format.Name))
{
result.Errors.Add("response_format.json_schema.name is required.");
missingCriticalField = true;
}
if (string.IsNullOrWhiteSpace(format.SchemaJson))
{
result.Errors.Add("response_format.json_schema.schema is required.");
missingCriticalField = true;
}
if (!format.Strict)
result.Errors.Add("response_format.json_schema.strict must be true.");
if (missingCriticalField)
return result;
JsonDocument schemaDoc;
try
{
schemaDoc = JsonDocument.Parse(format.SchemaJson ?? "");
}
catch (Exception ex)
{
result.Errors.Add("response_format.json_schema.schema is not valid JSON: " + ex.Message);
return result;
}
using (schemaDoc)
{
var root = schemaDoc.RootElement;
if (root.ValueKind != JsonValueKind.Object)
{
result.Errors.Add("Structured outputs require the schema root to be a JSON object.");
return result;
}
if (root.TryGetProperty("anyOf", out _))
result.Errors.Add("Structured outputs do not allow `anyOf` at the root schema.");
if (!SchemaAllowsObject(root, root))
result.Errors.Add("Structured outputs require the schema root to describe a JSON object.");
var ctx = new SchemaValidationContext(root, result.Errors);
ValidateSchemaNode(root, "$", 1, true, ctx);
if (ctx.TotalPropertyCount > 5000)
result.Errors.Add("Structured outputs allow at most 5000 object properties across the schema.");
if (ctx.TotalEnumValues > 1000)
result.Errors.Add("Structured outputs allow at most 1000 enum values across the schema.");
if (ctx.TotalStringBytes > 120000)
result.Errors.Add("Structured outputs allow at most 120000 total characters across names, enum values, and const values.");
}
return new StructuredOutputSchemaValidationResult
{
IsValid = result.Errors.Count == 0,
Errors = result.Errors
};
}
public static StructuredOutputNormalizationResult NormalizeOutput(string rawOutput, StructuredOutputFormat format)
{
if (format == null)
{
return new StructuredOutputNormalizationResult
{
IsValid = true,
NormalizedContent = rawOutput ?? ""
};
}
if (string.IsNullOrWhiteSpace(rawOutput))
{
return new StructuredOutputNormalizationResult
{
Errors = new List<string> { "The model returned an empty response." }
};
}
if (format.Kind == StructuredOutputKind.JsonObject)
return NormalizeJsonObject(rawOutput);
var schemaValidation = ValidateSchema(format);
if (!schemaValidation.IsValid)
{
return new StructuredOutputNormalizationResult
{
Errors = new List<string>(schemaValidation.Errors)
};
}
if (!TryExtractJsonObject(rawOutput, out string? candidateJson, out string? extractError))
{
return new StructuredOutputNormalizationResult
{
Errors = new List<string> { extractError }
};
}
try
{
using var valueDoc = JsonDocument.Parse(candidateJson);
using var schemaDoc = JsonDocument.Parse(format.SchemaJson ?? "");
var errors = new List<string>();
if (!TryNormalizeValue(valueDoc.RootElement, schemaDoc.RootElement, schemaDoc.RootElement,
"$", 1, errors, out JsonNode? normalizedNode))
{
return new StructuredOutputNormalizationResult { Errors = errors };
}
if (normalizedNode is not JsonObject)
{
return new StructuredOutputNormalizationResult
{
Errors = new List<string> { "Structured outputs require a JSON object response." }
};
}
return new StructuredOutputNormalizationResult
{
IsValid = true,
NormalizedContent = normalizedNode.ToJsonString(new JsonSerializerOptions { WriteIndented = false })
};
}
catch (Exception ex)
{
return new StructuredOutputNormalizationResult
{
Errors = new List<string> { "The model response could not be parsed as JSON: " + ex.Message }
};
}
}
private static StructuredOutputNormalizationResult NormalizeJsonObject(string rawOutput)
{
if (!TryExtractJsonObject(rawOutput, out string? candidateJson, out string? extractError))
{
return new StructuredOutputNormalizationResult
{
Errors = new List<string> { extractError }
};
}
try
{
using var doc = JsonDocument.Parse(candidateJson);
if (doc.RootElement.ValueKind != JsonValueKind.Object)
{
return new StructuredOutputNormalizationResult
{
Errors = new List<string> { "response_format.type=json_object requires the model to return a JSON object." }
};
}
return new StructuredOutputNormalizationResult
{
IsValid = true,
NormalizedContent = JsonSerializer.Serialize(doc.RootElement)
};
}
catch (Exception ex)
{
return new StructuredOutputNormalizationResult
{
Errors = new List<string> { "The model response could not be parsed as JSON: " + ex.Message }
};
}
}
private static void ValidateSchemaNode(JsonElement schema, string path, int depth,
bool isRoot, SchemaValidationContext ctx)
{
if (ctx.Errors.Count >= 16)
return;
if (depth > 10)
{
ctx.Errors.Add($"Schema nesting exceeds the supported depth of 10 at {path}.");
return;
}
RegisterUnsupportedKeywords(schema, path, ctx);
RegisterEnumAndConstStats(schema, path, ctx);
if (schema.TryGetProperty("$ref", out var refEl))
{
string? refPath = refEl.GetString();
if (!TryResolveRef(ctx.RootSchema, refPath, out JsonElement target, out string? refError))
{
ctx.Errors.Add($"{path}: {refError}");
return;
}
if (ctx.ActiveRefs.Contains(refPath!))
return;
ctx.ActiveRefs.Add(refPath!);
ValidateSchemaNode(target, $"{path}->$ref({refPath})", depth + 1, false, ctx);
ctx.ActiveRefs.Remove(refPath!);
return;
}
if (schema.TryGetProperty("anyOf", out var anyOfEl))
{
if (isRoot)
ctx.Errors.Add("Structured outputs do not allow `anyOf` at the root schema.");
if (anyOfEl.ValueKind != JsonValueKind.Array || anyOfEl.GetArrayLength() == 0)
{
ctx.Errors.Add($"{path}: `anyOf` must be a non-empty array.");
return;
}
int idx = 0;
foreach (var variant in anyOfEl.EnumerateArray())
{
ValidateSchemaNode(variant, $"{path}.anyOf[{idx}]", depth + 1, false, ctx);
idx++;
}
}
var types = ReadTypeList(schema, path, ctx);
bool objectLike = SchemaIsObjectLike(schema, ctx.RootSchema);
bool arrayLike = schema.TryGetProperty("items", out _) || types.Contains("array");
if (objectLike)
{
if (!schema.TryGetProperty("additionalProperties", out var apEl) ||
apEl.ValueKind != JsonValueKind.False)
{
ctx.Errors.Add($"{path}: `additionalProperties: false` is required for every object schema.");
}
var propertyNames = new HashSet<string>(StringComparer.Ordinal);
if (schema.TryGetProperty("properties", out var propsEl))
{
if (propsEl.ValueKind != JsonValueKind.Object)
{
ctx.Errors.Add($"{path}: `properties` must be an object.");
}
else
{
foreach (var prop in propsEl.EnumerateObject())
{
propertyNames.Add(prop.Name);
ctx.TotalPropertyCount++;
ctx.TotalStringBytes += prop.Name.Length;
ValidateSchemaNode(prop.Value, $"{path}.properties.{prop.Name}", depth + 1, false, ctx);
}
}
}
if (!schema.TryGetProperty("required", out var requiredEl) || requiredEl.ValueKind != JsonValueKind.Array)
{
ctx.Errors.Add($"{path}: `required` must be an array listing every property.");
}
else
{
var requiredNames = new HashSet<string>(StringComparer.Ordinal);
foreach (var item in requiredEl.EnumerateArray())
{
if (item.ValueKind == JsonValueKind.String && item.GetString() is string reqName)
requiredNames.Add(reqName);
}
foreach (var propName in propertyNames)
{
if (!requiredNames.Contains(propName))
ctx.Errors.Add($"{path}: property `{propName}` must be listed in `required`.");
}
foreach (var reqName in requiredNames)
{
if (!propertyNames.Contains(reqName))
ctx.Errors.Add($"{path}: `required` contains unknown property `{reqName}`.");
}
}
}
if (arrayLike)
{
if (!schema.TryGetProperty("items", out var itemsEl))
ctx.Errors.Add($"{path}: array schemas must define `items`.");
else
ValidateSchemaNode(itemsEl, $"{path}.items", depth + 1, false, ctx);
}
if (schema.TryGetProperty("$defs", out var defsEl))
{
if (defsEl.ValueKind != JsonValueKind.Object)
{
ctx.Errors.Add($"{path}: `$defs` must be an object.");
}
else
{
foreach (var def in defsEl.EnumerateObject())
{
ctx.TotalStringBytes += def.Name.Length;
ValidateSchemaNode(def.Value, $"{path}.$defs.{def.Name}", depth + 1, false, ctx);
}
}
}
}
private static void RegisterUnsupportedKeywords(JsonElement schema, string path, SchemaValidationContext ctx)
{
foreach (var prop in schema.EnumerateObject())
{
if (UnsupportedKeywords.Contains(prop.Name))
ctx.Errors.Add($"{path}: `{prop.Name}` is not supported by structured outputs.");
}
}
private static void RegisterEnumAndConstStats(JsonElement schema, string path, SchemaValidationContext ctx)
{
if (schema.TryGetProperty("enum", out var enumEl))
{
if (enumEl.ValueKind != JsonValueKind.Array)
{
ctx.Errors.Add($"{path}: `enum` must be an array.");
return;
}
foreach (var item in enumEl.EnumerateArray())
{
ctx.TotalEnumValues++;
if (item.ValueKind == JsonValueKind.String)
ctx.TotalStringBytes += item.GetString()?.Length ?? 0;
}
}
if (schema.TryGetProperty("const", out var constEl) && constEl.ValueKind == JsonValueKind.String)
ctx.TotalStringBytes += constEl.GetString()?.Length ?? 0;
}
private static HashSet<string> ReadTypeList(JsonElement schema, string path, SchemaValidationContext ctx)
{
var types = new HashSet<string>(StringComparer.Ordinal);
if (!schema.TryGetProperty("type", out var typeEl))
return types;
if (typeEl.ValueKind == JsonValueKind.String)
{
string typeName = typeEl.GetString() ?? "";
if (SupportedPrimitiveTypes.Contains(typeName))
types.Add(typeName);
else
ctx.Errors.Add($"{path}: unsupported type `{typeName}`.");
return types;
}
if (typeEl.ValueKind == JsonValueKind.Array)
{
foreach (var item in typeEl.EnumerateArray())
{
if (item.ValueKind != JsonValueKind.String)
{
ctx.Errors.Add($"{path}: `type` arrays may only contain strings.");
continue;
}
string typeName = item.GetString() ?? "";
if (SupportedPrimitiveTypes.Contains(typeName))
types.Add(typeName);
else
ctx.Errors.Add($"{path}: unsupported type `{typeName}`.");
}
return types;
}
ctx.Errors.Add($"{path}: `type` must be a string or array of strings.");
return types;
}
private static bool TryNormalizeValue(JsonElement value, JsonElement schema, JsonElement rootSchema,
string path, int depth, List<string> errors, out JsonNode? normalized)
{
normalized = null;
if (depth > 128)
{
errors.Add($"{path}: response exceeded the supported normalization depth.");
return false;
}
if (schema.TryGetProperty("$ref", out var refEl))
{
string? refPath = refEl.GetString();
if (!TryResolveRef(rootSchema, refPath, out JsonElement target, out string? refError))
{
errors.Add($"{path}: {refError}");
return false;
}
return TryNormalizeValue(value, target, rootSchema, path, depth + 1, errors, out normalized);
}
if (schema.TryGetProperty("anyOf", out var anyOfEl))
{
foreach (var variant in anyOfEl.EnumerateArray())
{
var variantErrors = new List<string>();
if (TryNormalizeValue(value, variant, rootSchema, path, depth + 1, variantErrors, out normalized))
return true;
}
errors.Add($"{path}: value did not match any schema in `anyOf`.");
return false;
}
var typeCtx = new SchemaValidationContext(rootSchema, new List<string>());
var types = ReadTypeList(schema, path, typeCtx);
if (types.Contains("null") && value.ValueKind == JsonValueKind.Null)
{
normalized = null;
return true;
}
if (SchemaMatchesObject(value, schema, rootSchema, path, depth, errors, out normalized))
return CheckEnumAndConst(schema, normalized, errors, path, allowNullFallback: true);
if (SchemaMatchesArray(value, schema, rootSchema, path, depth, errors, out normalized))
return CheckEnumAndConst(schema, normalized, errors, path, allowNullFallback: true);
if (TryNormalizePrimitive(value, types, path, errors, out normalized))
return CheckEnumAndConst(schema, normalized, errors, path, allowNullFallback: true);
if (typeCtx.Errors.Count > 0)
errors.AddRange(typeCtx.Errors);
return false;
}
private static bool SchemaMatchesObject(JsonElement value, JsonElement schema, JsonElement rootSchema,
string path, int depth, List<string> errors, out JsonNode? normalized)
{
normalized = null;
bool objectLike = SchemaIsObjectLike(schema, rootSchema);
if (!objectLike)
return false;
if (value.ValueKind != JsonValueKind.Object)
{
errors.Add($"{path}: expected an object.");
return false;
}
var result = new JsonObject();
if (!schema.TryGetProperty("properties", out var propsEl) || propsEl.ValueKind != JsonValueKind.Object)
{
normalized = result;
return true;
}
foreach (var prop in propsEl.EnumerateObject())
{
if (value.TryGetProperty(prop.Name, out var childValue))
{
if (!TryNormalizeValue(childValue, prop.Value, rootSchema, $"{path}.{prop.Name}", depth + 1, errors, out JsonNode? childNode))
return false;
result[prop.Name] = childNode;
}
else if (AllowsNull(prop.Value, rootSchema))
{
result[prop.Name] = null;
}
else
{
errors.Add($"{path}: missing required property `{prop.Name}`.");
return false;
}
}
normalized = result;
return true;
}
private static bool SchemaMatchesArray(JsonElement value, JsonElement schema, JsonElement rootSchema,
string path, int depth, List<string> errors, out JsonNode? normalized)
{
normalized = null;
bool arrayLike = schema.TryGetProperty("items", out _)
|| (schema.TryGetProperty("type", out var typeEl) &&
((typeEl.ValueKind == JsonValueKind.String && typeEl.GetString() == "array") ||
(typeEl.ValueKind == JsonValueKind.Array && ArrayContainsType(typeEl, "array"))));
if (!arrayLike)
return false;
if (value.ValueKind != JsonValueKind.Array)
{
errors.Add($"{path}: expected an array.");
return false;
}
if (!schema.TryGetProperty("items", out var itemsEl))
{
normalized = JsonNode.Parse(value.GetRawText());
return true;
}
var result = new JsonArray();
int index = 0;
foreach (var item in value.EnumerateArray())
{
if (!TryNormalizeValue(item, itemsEl, rootSchema, $"{path}[{index}]", depth + 1, errors, out JsonNode? childNode))
return false;
result.Add(childNode);
index++;
}
normalized = result;
return true;
}
private static bool TryNormalizePrimitive(JsonElement value, HashSet<string> types,
string path, List<string> errors, out JsonNode? normalized)
{
normalized = null;
if (types.Count == 0)
{
if (value.ValueKind == JsonValueKind.Null)
return true;
normalized = JsonNode.Parse(value.GetRawText());
return normalized != null;
}
if (types.Contains("string") && value.ValueKind == JsonValueKind.String)
{
normalized = JsonValue.Create(value.GetString());
return true;
}
if (types.Contains("boolean") &&
(value.ValueKind == JsonValueKind.True || value.ValueKind == JsonValueKind.False))
{
normalized = JsonValue.Create(value.GetBoolean());
return true;
}
if (types.Contains("integer") && value.ValueKind == JsonValueKind.Number)
{
if (value.TryGetInt64(out long asInt))
{
normalized = JsonValue.Create(asInt);
return true;
}
if (value.TryGetDouble(out double asDouble) && Math.Abs(asDouble - Math.Round(asDouble)) < 1e-9)
{
normalized = JsonValue.Create((long)Math.Round(asDouble));
return true;
}
errors.Add($"{path}: expected an integer.");
return false;
}
if (types.Contains("number") && value.ValueKind == JsonValueKind.Number)
{
normalized = JsonNode.Parse(value.GetRawText());
return normalized != null;
}
if (types.Contains("null") && value.ValueKind == JsonValueKind.Null)
{
normalized = null;
return true;
}
errors.Add($"{path}: value does not match the schema type.");
return false;
}
private static bool CheckEnumAndConst(JsonElement schema, JsonNode? normalized,
List<string> errors, string path, bool allowNullFallback)
{
if (normalized == null && allowNullFallback)
return true;
if (schema.TryGetProperty("const", out var constEl))
{
JsonNode? constNode = JsonNode.Parse(constEl.GetRawText());
if (!JsonNode.DeepEquals(normalized, constNode))
{
errors.Add($"{path}: value does not match the schema const.");
return false;
}
}
if (schema.TryGetProperty("enum", out var enumEl))
{
bool matched = false;
foreach (var enumValue in enumEl.EnumerateArray())
{
JsonNode? enumNode = JsonNode.Parse(enumValue.GetRawText());
if (JsonNode.DeepEquals(normalized, enumNode))
{
matched = true;
break;
}
}
if (!matched)
{
errors.Add($"{path}: value is not in the schema enum.");
return false;
}
}
return true;
}
private static bool SchemaAllowsObject(JsonElement schema, JsonElement rootSchema)
{
if (schema.TryGetProperty("$ref", out var refEl))
{
return TryResolveRef(rootSchema, refEl.GetString(), out JsonElement target, out _)
&& SchemaAllowsObject(target, rootSchema);
}
if (schema.TryGetProperty("type", out var typeEl))
{
if (typeEl.ValueKind == JsonValueKind.String)
return string.Equals(typeEl.GetString(), "object", StringComparison.Ordinal);
if (typeEl.ValueKind == JsonValueKind.Array)
{
foreach (var item in typeEl.EnumerateArray())
{
if (item.ValueKind == JsonValueKind.String &&
string.Equals(item.GetString(), "object", StringComparison.Ordinal))
return true;
}
}
}
return schema.TryGetProperty("properties", out _)
|| schema.TryGetProperty("additionalProperties", out _);
}
private static bool SchemaIsObjectLike(JsonElement schema, JsonElement rootSchema)
{
if (schema.TryGetProperty("$ref", out var refEl) &&
TryResolveRef(rootSchema, refEl.GetString(), out JsonElement target, out _))
{
return SchemaIsObjectLike(target, rootSchema);
}
return schema.TryGetProperty("properties", out _)
|| schema.TryGetProperty("additionalProperties", out _)
|| (schema.TryGetProperty("type", out var typeEl) &&
((typeEl.ValueKind == JsonValueKind.String && typeEl.GetString() == "object") ||
(typeEl.ValueKind == JsonValueKind.Array && ArrayContainsType(typeEl, "object"))));
}
private static bool AllowsNull(JsonElement schema, JsonElement rootSchema)
{
if (schema.TryGetProperty("$ref", out var refEl))
{
return TryResolveRef(rootSchema, refEl.GetString(), out JsonElement target, out _)
&& AllowsNull(target, rootSchema);
}
if (schema.TryGetProperty("type", out var typeEl))
{
if (typeEl.ValueKind == JsonValueKind.String)
return typeEl.GetString() == "null";
if (typeEl.ValueKind == JsonValueKind.Array)
return ArrayContainsType(typeEl, "null");
}
if (schema.TryGetProperty("anyOf", out var anyOfEl))
{
foreach (var variant in anyOfEl.EnumerateArray())
{
if (AllowsNull(variant, rootSchema))
return true;
}
}
return false;
}
private static bool ArrayContainsType(JsonElement typeArray, string expected)
{
foreach (var item in typeArray.EnumerateArray())
{
if (item.ValueKind == JsonValueKind.String &&
string.Equals(item.GetString(), expected, StringComparison.Ordinal))
return true;
}
return false;
}
private static bool TryResolveRef(JsonElement rootSchema, string? refPath,
out JsonElement target, [NotNullWhen(false)] out string? error)
{
target = default;
error = null;
if (string.IsNullOrWhiteSpace(refPath))
{
error = "Encountered an empty `$ref`.";
return false;
}
if (refPath == "#")
{
target = rootSchema;
return true;
}
if (!refPath.StartsWith("#/", StringComparison.Ordinal))
{
error = $"Only local refs are supported, but received `{refPath}`.";
return false;
}
JsonElement current = rootSchema;
string[] segments = refPath.Substring(2).Split('/');
foreach (var rawSegment in segments)
{
string segment = rawSegment.Replace("~1", "/").Replace("~0", "~");
if (current.ValueKind != JsonValueKind.Object || !current.TryGetProperty(segment, out current))
{
error = $"Could not resolve `$ref` path `{refPath}`.";
return false;
}
}
target = current;
return true;
}
private static bool TryExtractJsonObject(string rawOutput, [NotNullWhen(true)] out string? json, [NotNullWhen(false)] out string? error)
{
error = null;
string trimmed = rawOutput.Trim();
if (TryParseCandidate(trimmed, out json))
return true;
var fenceMatches = Regex.Matches(trimmed, "```(?:json)?\\s*(.*?)\\s*```",
RegexOptions.IgnoreCase | RegexOptions.Singleline);
foreach (Match match in fenceMatches)
{
if (match.Groups.Count > 1 && TryParseCandidate(match.Groups[1].Value.Trim(), out json))
return true;
}
for (int i = 0; i < trimmed.Length; i++)
{
if (trimmed[i] != '{')
continue;
if (TryReadBalancedObject(trimmed, i, out string? candidate) && TryParseCandidate(candidate, out json))
return true;
}
error = "The model response did not contain a valid JSON object.";
return false;
}
private static bool TryParseCandidate(string candidate, [NotNullWhen(true)] out string? json)
{
json = null;
if (string.IsNullOrWhiteSpace(candidate))
return false;
try
{
using var doc = JsonDocument.Parse(candidate);
if (doc.RootElement.ValueKind != JsonValueKind.Object)
return false;
json = JsonSerializer.Serialize(doc.RootElement);
return true;
}
catch
{
return false;
}
}
private static bool TryReadBalancedObject(string text, int startIndex, [NotNullWhen(true)] out string? json)
{
json = null;
bool inString = false;
bool escaping = false;
int depth = 0;
for (int i = startIndex; i < text.Length; i++)
{
char ch = text[i];
if (escaping)
{
escaping = false;
continue;
}
if (ch == '\\' && inString)
{
escaping = true;
continue;
}
if (ch == '"')
{
inString = !inString;
continue;
}
if (inString)
continue;
if (ch == '{')
depth++;
else if (ch == '}')
depth--;
if (depth == 0)