Loading...
const res = await llm.generate({ prompt: 'Return the user as JSON.' });
const user = JSON.parse(res.text);const res = await llm.generate({
prompt: 'Extract the user from the text.',
responseFormat: { type: 'json_schema', schema: userJsonSchema },
});
const user = validateUser(JSON.parse(res.text));A schema-constrained response plus validation in code catches missing fields before the data is used.
JSON.parse.JSON mode only aims for valid JSON. Structured output also constrains the response to a given schema, so required fields and types match.
Yes. Output can still be truncated, refused or wrong in meaning, so validate it before use.
The model formats it like a chat answer. Use the API's structured output, or strip the fence before parsing.