{
  "name": "BIA AI Phone Receptionist (Gulfsip 22204171 -> Ring Group 600)",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "bia-voice-receptionist",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "node-webhook-in",
      "name": "FreePBX Voice Turn Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        220,
        300
      ],
      "webhookId": "bia-voice-receptionist"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "gem-key",
              "name": "gemini_api_key",
              "value": "PASTE_YOUR_GEMINI_API_KEY_HERE",
              "type": "string"
            },
            {
              "id": "gem-model",
              "name": "gemini_model",
              "value": "gemini-2.5-flash",
              "type": "string"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      },
      "id": "node-config",
      "name": "Set Gemini API Key",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        450,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "const input = $input.first().json;\nconst body = input.body || input;\nconst did = String(body.did || '22204171');\nif (did.includes('02039210370')) {\n  throw new Error('Soho66 (02039210370) is excluded; this workflow is strictly for Gulfsip 22204171.');\n}\n\nconst lang = body.language === 'ar' ? 'ar' : 'en';\nconst afterHours = Boolean(body.after_hours);\nconst fromOverflow = Boolean(body.from_overflow);\nconst audioB64 = String(body.audio_b64 || '').trim();\nconst inst = body.institute || {};\nconst courses = Array.isArray(body.courses) ? body.courses : [];\nconst history = Array.isArray(body.history) ? body.history : [];\n\nconst courseLines = courses.map(c => `- [${c.code}] ${c.title} | ${c.category} | Fee:${c.fee} | Dur:${c.duration} | ${c.schedule}`).join('\\n');\nconst histLines = history.length ? history.map(h => `${String(h.role).toUpperCase()}: ${h.text}`).join('\\n') : '(Start of call)';\n\nconst langRule = lang === 'ar'\n  ? 'STRICT LANGUAGE LOCK: Caller selected ARABIC. Transcribe audio in Arabic (keeping English course names like IELTS, PMP, Cisco, OTHM, CompTIA, Power BI clear) and reply ONLY in natural, polite Kuwaiti/Gulf Arabic. NEVER reply in English sentences.'\n  : 'STRICT LANGUAGE LOCK: Caller selected ENGLISH. Transcribe audio in ENGLISH ONLY (NEVER output Arabic script) and reply ONLY in natural, warm British English. Domain terms: IELTS, LanguageCert, OTHM, NCC, Pearson BTEC, ACCA, CompTIA, Cisco CCNA, CEH, Cyber Security, PMP, Python, Power BI, Corporate Training, Salmiya, Kuwait.';\n\nconst hoursRule = afterHours\n  ? 'OFFICE STATUS: AFTER HOURS (Sat-Thu 9 AM-8 PM Kuwait Time, Friday closed). Keep transfer_to=\"\", set wants_callback=true, answer all questions fully, and record complete lead details for next-morning callback.'\n  : (fromOverflow\n    ? 'OFFICE STATUS: Human advisors in Ring Group 600/601 did not answer right now. Reassure the caller warmly that all advisors are currently busy, answer their questions fully, and capture their complete contact/course/corporate requirements (wants_callback=true). Only set transfer_to=\"600\" if they explicitly insist on trying reception again.'\n    : 'OFFICE STATUS: OPEN HOURS. If the caller explicitly asks to speak to a human/advisor/receptionist, set transfer_to=\"600\" and say a brief warm handoff.');\n\nconst systemPrompt = `You are Sarah, the fast, warm Digital Receptionist at ${inst.name || 'Britain International Academy'} (BIA), Salmiya, Kuwait (Line: 22204171).\nAddress: ${inst.address || 'Building 34, Block 10, Essa Al Qatami St, Salmiya, Kuwait'} | Hours: ${inst.working_hours || 'Sat-Thu 9 AM-8 PM, Fri Closed'}\nWhatsApp: ${inst.whatsapp || '+965 65701004'} | Email: ${inst.email || 'info@bia.edu.kw'} | Corporate Email: ${inst.corporate_email || 'corp-training@bia.edu.kw'}\nCorporate Terms: ${inst.corporate_terms || 'Tailored corporate training onsite, at BIA Salmiya, or online; 15-day lead time.'}\n\n${langRule}\n${hoursRule}\n\nLIVE COURSES (${courses.length} courses):\n${courseLines}\n\nRULES:\n1. Keep spoken reply crisp and natural (1-2 short sentences, NO markdown/bullets/asterisks).\n2. If audio is silent/static with no speech, set \"silent\":true, \"transcript\":\"\", \"reply\":\"\"!\n3. If caller only greets (\"Hello\"/\"\u0623\u0644\u0648\"), reply warmly in 1 sentence asking how you can help with courses or corporate training (end_call=false).\n4. INDIVIDUAL COURSES: Give exact live fee, duration, and schedule from the catalog; ask for their name and preferred timing.\n5. CORPORATE TRAINING (\u062a\u062f\u0631\u064a\u0628 \u0634\u0631\u0643\u0627\u062a / \u062a\u062f\u0631\u064a\u0628 \u0645\u0624\u0633\u0633\u064a / \u0645\u0648\u0638\u0641\u064a\u0646 / \u0639\u0631\u0636 \u0633\u0639\u0631 / \u0648\u0632\u0627\u0631\u0629 / \u062c\u0647\u0629): Set lead_type=\"Corporate\", department=\"Corporate Training\", wants_callback=true. Collect step by step (1-2 short questions per turn): company_name, caller_name, interested_course, trainees_count, preferred dates/location, email.\n6. Keep previously learned fields across turns. Return STRICT JSON ONLY:\n{\"silent\":false,\"transcript\":\"exact caller speech\",\"reply\":\"...\",\"reply_lang\":\"${lang}\",\"caller_name\":\"\",\"company_name\":\"\",\"email\":\"\",\"trainees_count\":\"\",\"lead_type\":\"Individual or Corporate\",\"department\":\"\",\"interested_course\":\"\",\"requirements\":\"\",\"wants_callback\":false,\"transfer_to\":\"\",\"end_call\":false,\"summary\":\"\"}`;\n\nconst userParts = [];\nif (audioB64) {\n  userParts.push({ inline_data: { mime_type: 'audio/wav', data: audioB64 } });\n  userParts.push({ text: `Caller: ${body.caller_number || 'Unknown'} | Selected Language: ${lang.toUpperCase()}\\nHistory:\\n${histLines}\\n\\nListen to the caller audio above, transcribe it accurately, and respond in ${lang === 'ar' ? 'ARABIC' : 'ENGLISH'} in strict JSON.` });\n} else {\n  userParts.push({ text: `Caller: ${body.caller_number || 'Unknown'} | Selected Language: ${lang.toUpperCase()}\\nHistory:\\n${histLines}\\n\\nCaller said: ${body.transcript || ''}\\n\\nRespond in ${lang === 'ar' ? 'ARABIC' : 'ENGLISH'} in strict JSON.` });\n}\n\nreturn [{\n  json: {\n    gemini_url: `https://generativelanguage.googleapis.com/v1beta/models/${input.gemini_model || 'gemini-2.5-flash'}:generateContent?key=${input.gemini_api_key}`,\n    caller_number: body.caller_number || '',\n    did,\n    language: lang,\n    after_hours: afterHours,\n    from_overflow: fromOverflow,\n    transcript: body.transcript || '',\n    gemini_body: {\n      system_instruction: { parts: [{ text: systemPrompt }] },\n      contents: [{ role: 'user', parts: userParts }],\n      generationConfig: { temperature: 0.25, maxOutputTokens: 450, responseMimeType: 'application/json', thinkingConfig: { thinkingBudget: 0 } }\n    }\n  }\n}];"
      },
      "id": "node-build-prompt",
      "name": "Build BIA Receptionist Prompt",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        680,
        300
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $json.gemini_url }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json.gemini_body) }}",
        "options": {
          "timeout": 20000
        }
      },
      "id": "node-gemini-call",
      "name": "Ask Gemini 2.5 Flash",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        920,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "const resp = $input.first().json;\nconst prev = $('Build BIA Receptionist Prompt').first().json;\nconst lang = prev.language === 'ar' ? 'ar' : 'en';\nconst rawText = resp?.candidates?.[0]?.content?.parts?.[0]?.text || '{}';\nlet parsed = {};\ntry {\n  parsed = JSON.parse(rawText);\n} catch (e) {\n  const m = rawText.match(/\\{[\\s\\S]*\\}/);\n  parsed = m ? JSON.parse(m[0]) : { reply: rawText };\n}\n\nconst transcript = String(parsed.transcript || prev.transcript || '').trim();\nconst isSilent = Boolean(parsed.silent) || (!transcript && !String(parsed.reply || '').trim());\n\nlet transferTo = String(parsed.transfer_to || '').trim();\nif (prev.after_hours) {\n  transferTo = '';\n} else {\n  if (transferTo === '602') transferTo = '600';\n  if (!transferTo && !prev.from_overflow && /\\b(human|person|agent|operator|receptionist|transfer me|speak to someone|talk to someone)\\b|\u0645\u0648\u0638\u0641|\u0628\u0634\u0631\u064a|\u0627\u0633\u062a\u0642\u0628\u0627\u0644|\u062a\u062d\u0648\u064a\u0644|\u0623\u0643\u0644\u0645 \u0623\u062d\u062f|\u0643\u0644\u0645 \u0627\u062d\u062f/iu.test(transcript)) {\n    transferTo = '600';\n  }\n}\n\nconst fallbackReply = lang === 'ar'\n  ? '\u0634\u0643\u0631\u0627\u064b \u0644\u062a\u0648\u0627\u0635\u0644\u0643 \u0645\u0639 \u0623\u0643\u0627\u062f\u064a\u0645\u064a\u0629 \u0628\u0631\u064a\u0637\u0627\u0646\u064a\u0627 \u0627\u0644\u062f\u0648\u0644\u064a\u0629. \u062a\u0645 \u062a\u0633\u062c\u064a\u0644 \u062a\u0641\u0627\u0635\u064a\u0644 \u0637\u0644\u0628\u0643 \u0648\u0633\u064a\u062a\u0648\u0627\u0635\u0644 \u0645\u0639\u0643 \u0641\u0631\u064a\u0642\u0646\u0627 \u0642\u0631\u064a\u0628\u0627\u064b.'\n  : 'Thank you for calling Britain International Academy. I have noted your inquiry and our team will follow up with you shortly.';\n\nreturn [{\n  json: {\n    silent: isSilent,\n    transcript,\n    reply: isSilent ? '' : (parsed.reply || fallbackReply),\n    reply_lang: lang,\n    caller_name: String(parsed.caller_name || '').trim(),\n    company_name: String(parsed.company_name || '').trim(),\n    email: String(parsed.email || '').trim(),\n    trainees_count: String(parsed.trainees_count || '').trim(),\n    lead_type: String(parsed.lead_type || '').trim() || 'Individual',\n    department: String(parsed.department || '').trim() || 'General Inquiries',\n    interested_course: String(parsed.interested_course || '').trim(),\n    requirements: String(parsed.requirements || '').trim(),\n    wants_callback: Boolean(parsed.wants_callback),\n    transfer_to: transferTo,\n    end_call: Boolean(parsed.end_call),\n    summary: String(parsed.summary || '').trim()\n  }\n}];"
      },
      "id": "node-parse-reply",
      "name": "Format Reply & Transfer Decision",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1160,
        300
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify($json) }}",
        "options": {}
      },
      "id": "node-respond",
      "name": "Respond to FreePBX",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        1400,
        300
      ]
    }
  ],
  "connections": {
    "FreePBX Voice Turn Webhook": {
      "main": [
        [
          {
            "node": "Set Gemini API Key",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set Gemini API Key": {
      "main": [
        [
          {
            "node": "Build BIA Receptionist Prompt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build BIA Receptionist Prompt": {
      "main": [
        [
          {
            "node": "Ask Gemini 2.5 Flash",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ask Gemini 2.5 Flash": {
      "main": [
        [
          {
            "node": "Format Reply & Transfer Decision",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format Reply & Transfer Decision": {
      "main": [
        [
          {
            "node": "Respond to FreePBX",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  }
}