WhatsApp AI Assistant
Module 20 · ai · intermediate
pick.js
// Use the AI reply when there is one; otherwise the rule-based reply. Runs for both branches of "Use AI?".
return $input.all().map((item, i) => {
const fromAi = !item.json.wa_id; // AI chain output only has { output } (or an error)
const st = fromAi ? $('Conversation State').itemMatching(i).json : item.json;
const ai = fromAi ? item.json.output : null;
if (st.action !== 'answer') return { json: { ...st, reply_source: st.reply ? 'rules' : 'none', lead_patch: {}, next_awaiting: st.convo.awaiting } };
if (ai?.reply) {
const patch = Object.fromEntries(Object.entries(ai.lead ?? {}).filter(([, v]) => v !== null && String(v).trim() !== ''));
return { json: { ...st, reply: String(ai.reply).slice(0, 4096), reply_source: 'ai', intent: ai.intent ?? 'other', lead_patch: patch, ai_handoff: ai.handoff === true, next_awaiting: null } };
}
return {
json: {
...st, reply: st.rules.reply, reply_source: 'rules', intent: st.rules.intent, lead_patch: st.rules.patch,
next_awaiting: st.rules.awaiting, ai_error: fromAi ? String(item.json.error?.message ?? item.json.error ?? 'no AI output') : undefined,
},
};
});