Skip to content

parseJsonAnswer

function parseJsonAnswer(text): unknown;

Defined in: core/src/types.ts:254

Read the JSON out of a model’s answer. Models wrap it: a ```json fence, an unmarked fence, a sentence before it, notes after it. This takes the first fenced block marked json or not marked at all. Text after the language on the fence line is read as the start of the JSON first, and as a label on the block when that doesn’t parse. With no such block, it takes the text from the first { or [ to the bracket that closes it, and with no bracket either, the whole answer (a bare number, say). Then it parses that.

It returns unknown on purpose: parsed is not validated, and a model’s JSON has the schema’s shape only once the caller has checked it.

Parameter Type
text string

unknown

when that text is not JSON. The error carries the answer, so a log shows what the model actually said.