JSON collection, decoding, and output Schema validation
The policy implementation follows.
ts
export function createJsonTransport<Output, const Id extends string = string>(definition: {
readonly id: Id;
readonly outputSchema: import('../../structs/common.js').SchemaAdapter<Output>;
readonly options?: Pick<ModelOptions, 'temperature' | 'json'>;
}): ModelTransportDefinition<Output> & { readonly id: Id } {
const { id, outputSchema, options } = definition;
if (typeof id !== 'string' || !id.trim()) throw new TypeError('JSON transport requires an ID');
const schema = snapshotSchemaAdapter(outputSchema);
const settings = Object.freeze({
...snapshotModelOptions({ temperature: options?.temperature, json: options?.json ?? true }),
});
const instruction =
'Return exactly one complete JSON value matching this JSON Schema: ' +
JSON.stringify(schema.jsonSchema) +
'\nReturn the value itself, without prose, fences, a schema document or a capability-selection envelope.';
return Object.freeze({
id,
prepare() {
return {
options: settings,
instruction,
schemaChars: instruction.length,
createResponse() {
let raw = '';
return {
get outputChars() {
return raw.length;
},
push(part: import('../../structs/model/messages.js').ModelPart) {
if (typeof part !== 'string')
modelProtocolError('JSON value transport does not accept native call events');
raw += part;
},
finish(): Output {
let value: unknown;
try {
value = JSON.parse(raw);
} catch {
modelProtocolError('JSON value transport requires complete JSON');
}
return schema.parse(value);
},
};
},
};
},
});
}