22 lines
991 B
JavaScript
22 lines
991 B
JavaScript
// Turns an API answer into a result object. Structured outputs guarantee the
|
|
// JSON is schema-valid when the turn ends normally, so the cases worth naming
|
|
// are the ones where it does not: a refusal, an answer cut off at max_tokens,
|
|
// or no text block at all (adaptive thinking puts a thinking block first).
|
|
export function readRecipeResponse(response) {
|
|
const { stop_reason: stopReason, content = [] } = response ?? {}
|
|
if (stopReason === 'refusal') {
|
|
return { ok: false, reason: 'the model declined to answer (stop_reason: refusal)' }
|
|
}
|
|
if (stopReason === 'max_tokens') {
|
|
return { ok: false, reason: 'answer cut off at max_tokens' }
|
|
}
|
|
const textBlock = content.find((block) => block.type === 'text')
|
|
if (!textBlock) {
|
|
return { ok: false, reason: 'no text block in the answer' }
|
|
}
|
|
try {
|
|
return { ok: true, recipe: JSON.parse(textBlock.text) }
|
|
} catch (error) {
|
|
return { ok: false, reason: `unreadable JSON in the answer: ${error.message}` }
|
|
}
|
|
}
|