|
| 1 | +function schema = jsonSchemaFromPrototype(prototype) |
| 2 | +% This function is undocumented and will change in a future release |
| 3 | + |
| 4 | +%jsonSchemaFromPrototype Create a JSON Schema matching given prototype |
| 5 | + |
| 6 | +% Copyright 2024 The MathWorks Inc. |
| 7 | + |
| 8 | +if ~isstruct(prototype) |
| 9 | + error("llms:incorrectResponseFormat", ... |
| 10 | + llms.utils.errorMessageCatalog.getMessage("llms:incorrectResponseFormat")); |
| 11 | +end |
| 12 | + |
| 13 | +% OpenAI requires top-level to be "type":"object" |
| 14 | +if ~isscalar(prototype) |
| 15 | + prototype = struct("result",{prototype}); |
| 16 | +end |
| 17 | + |
| 18 | +schema = recursiveSchemaFromPrototype(prototype); |
| 19 | +end |
| 20 | + |
| 21 | +function schema = recursiveSchemaFromPrototype(prototype) |
| 22 | + if ~isscalar(prototype) |
| 23 | + schema = struct("type","array","items",recursiveSchemaFromPrototype(prototype(1))); |
| 24 | + elseif isstruct(prototype) |
| 25 | + schema = schemaFromStruct(prototype); |
| 26 | + elseif isstring(prototype) || iscellstr(prototype) |
| 27 | + schema = struct("type","string"); |
| 28 | + elseif isinteger(prototype) |
| 29 | + schema = struct("type","integer"); |
| 30 | + elseif isnumeric(prototype) |
| 31 | + schema = struct("type","number"); |
| 32 | + elseif islogical(prototype) |
| 33 | + schema = struct("type","boolean"); |
| 34 | + elseif iscategorical(prototype) |
| 35 | + schema = struct("type","string", ... |
| 36 | + "enum",{categories(prototype)}); |
| 37 | + elseif ismissing(prototype) |
| 38 | + schema = struct("type","null"); |
| 39 | + else |
| 40 | + error("llms:unsupportedDatatypeInPrototype", ... |
| 41 | + llms.utils.errorMessageCatalog.getMessage("llms:unsupportedDatatypeInPrototype", class(prototype))); |
| 42 | + end |
| 43 | +end |
| 44 | + |
| 45 | +function schema = schemaFromStruct(prototype) |
| 46 | +fields = string(fieldnames(prototype)); |
| 47 | + |
| 48 | +properties = struct(); |
| 49 | +for fn=fields(:).' |
| 50 | + properties.(fn) = recursiveSchemaFromPrototype(prototype.(fn)); |
| 51 | +end |
| 52 | + |
| 53 | +% to make jsonencode encode an array |
| 54 | +if isscalar(fields) |
| 55 | + fields = {{fields}}; |
| 56 | +end |
| 57 | + |
| 58 | +schema = struct( ... |
| 59 | + "type","object", ... |
| 60 | + "properties",properties, ... |
| 61 | + "required",fields, ... |
| 62 | + "additionalProperties",false); |
| 63 | +end |
0 commit comments