/** * A conservative invoice triage example. A clear result still needs the * application's business checks; this function never authorizes payment. * @param {unknown} response */ function routeInvoice(response) { /** @param {unknown} value @returns {value is Record} */ function isRecord(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); } if (!isRecord(response) || !isRecord(response.data) || !isRecord(response.fields)) { throw new Error('Expected an extraction response with data and fields'); } const required = ['/invoice_number', '/total', '/currency']; const pointers = new Set([...required, ...Object.keys(response.fields)]); const reasons = []; for (const pointer of pointers) { const field = response.fields[pointer]; if (!isRecord(field)) { reasons.push({ pointer, reason: 'metadata_absent' }); continue; } if (field.state !== 'present') { // This example reviews null and missing optional fields too. reasons.push({ pointer, reason: 'not_present' }); continue; } if (field.conflict === true) reasons.push({ pointer, reason: 'conflict' }); if ( typeof field.confidence !== 'number' || !Number.isFinite(field.confidence) || field.confidence < 0 || field.confidence > 1 ) { reasons.push({ pointer, reason: 'score_absent_or_invalid' }); } if (field.grounding !== 'verified' || !isRecord(field.anchor)) { reasons.push({ pointer, reason: 'source_review' }); } } const data = response.data; if ( typeof data.invoice_number !== 'string' || data.invoice_number.length === 0 || typeof data.total !== 'number' || !Number.isFinite(data.total) || (data.currency !== 'USD' && data.currency !== 'EUR') ) { reasons.push({ pointer: '', reason: 'data_contract' }); } return { route: reasons.length ? 'exception_review' : 'business_checks', reasons, // Preserve source references for the reviewer; do not put them in logs. extraction: response, }; } return $input.all().map((item, index) => ({ json: routeInvoice(item.json), pairedItem: { item: index } }));