{
  "id": "dIL4vZA7RjcU07qx",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "name": "AI Symptom Checker & Doctor Suggestion",
  "tags": [],
  "nodes": [
    {
      "id": "73fc058d-d6ff-477d-826a-c1e050312f13",
      "name": "Medical AI Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOllama",
      "position": [
        240,
        1480
      ],
      "parameters": {
        "model": "=llama3.2-16000:latest",
        "options": {}
      },
      "credentials": {
        "ollamaApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "388c6212-65d0-47a4-a28a-f7bf9dd5c789",
      "name": "Symptom Input Webhook",
      "type": "n8n-nodes-base.webhook",
      "position": [
        -80,
        1260
      ],
      "parameters": {
        "path": "2837e22a-d927-40c4-bc43-7c2ec38cfdcf",
        "options": {},
        "httpMethod": "POST",
        "responseMode": "responseNode"
      },
      "typeVersion": 1
    },
    {
      "id": "d0f553ed-cb9f-458e-b4be-9facd5a9ce8a",
      "name": "AI Symptom Analysis",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        140,
        1260
      ],
      "parameters": {
        "text": "={{ $json.body.symptoms }}",
        "options": {
          "systemMessage": "You are a medical AI assistant that analyzes symptoms and provides preliminary assessments. IMPORTANT: Always emphasize that this is not a substitute for professional medical advice.\n\nAnalyze the symptoms and provide a JSON response with:\n{\n  \"urgency_level\": \"low/medium/high/emergency\",\n  \"possible_conditions\": [\"condition1\", \"condition2\", \"condition3\"],\n  \"specialist_needed\": \"General Practitioner/Cardiologist/Dermatologist/Neurologist/Orthopedist/Gastroenterologist/Pulmonologist/Emergency\",\n  \"severity_assessment\": \"brief description\",\n  \"recommended_actions\": [\"action1\", \"action2\"],\n  \"red_flags\": [\"warning sign if any\"]\n}\n\nSymptoms to analyze: {{ $json.body.symptoms }}\n\nPatient details:\n- Age: {{ $json.body.age || 'Not provided' }}\n- Gender: {{ $json.body.gender || 'Not provided' }}\n- Duration: {{ $json.body.duration || 'Not provided' }}\n- Additional info: {{ $json.body.additional_info || 'None' }}"
        },
        "promptType": "define"
      },
      "typeVersion": 2
    },
    {
      "id": "ce5d7cce-602e-4ca1-a565-15256a13fc6a",
      "name": "Parse Medical Analysis",
      "type": "n8n-nodes-base.code",
      "position": [
        520,
        1260
      ],
      "parameters": {
        "jsCode": "// Parse the AI response and extract medical assessment\nconst aiResponse = items[0].json.output;\nconst originalData = $node[\"Symptom Input Webhook\"].json.body;\n\ntry {\n  // Try to parse JSON response from AI\n  let analysis;\n  if (aiResponse.includes('{')) {\n    const jsonStart = aiResponse.indexOf('{');\n    const jsonEnd = aiResponse.lastIndexOf('}') + 1;\n    const jsonStr = aiResponse.substring(jsonStart, jsonEnd);\n    analysis = JSON.parse(jsonStr);\n  } else {\n    // Fallback if AI doesn't return proper JSON\n    analysis = {\n      urgency_level: \"medium\",\n      possible_conditions: [\"General symptoms requiring medical evaluation\"],\n      specialist_needed: \"General Practitioner\",\n      severity_assessment: aiResponse,\n      recommended_actions: [\"Consult with a healthcare provider\"],\n      red_flags: []\n    };\n  }\n\n  return [{\n    json: {\n      ...originalData,\n      analysis: analysis,\n      timestamp: new Date().toISOString()\n    }\n  }];\n} catch (error) {\n  // Error handling - return basic assessment\n  return [{\n    json: {\n      ...originalData,\n      analysis: {\n        urgency_level: \"medium\",\n        possible_conditions: [\"Symptoms require medical evaluation\"],\n        specialist_needed: \"General Practitioner\",\n        severity_assessment: \"Unable to analyze symptoms properly. Please consult a healthcare provider.\",\n        recommended_actions: [\"Schedule appointment with doctor\", \"Monitor symptoms\"],\n        red_flags: [\"Seek immediate care if symptoms worsen\"]\n      },\n      timestamp: new Date().toISOString()\n    }\n  }];\n}"
      },
      "typeVersion": 2
    },
    {
      "id": "15555bde-19dc-4278-b32b-e7601807cc6c",
      "name": "Check Emergency",
      "type": "n8n-nodes-base.if",
      "position": [
        740,
        1260
      ],
      "parameters": {
        "conditions": {
          "string": [
            {
              "value1": "={{ $json.analysis.urgency_level }}",
              "value2": "emergency"
            }
          ]
        }
      },
      "typeVersion": 1
    },
    {
      "id": "87c59d4b-098d-4884-80d8-297a4bd99e9e",
      "name": "Find Doctors",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        960,
        1360
      ],
      "parameters": {
        "url": "https://api.betterdoctor.com/2016-03-01/doctors",
        "options": {},
        "queryParametersUi": {
          "parameter": [
            {
              "name": "specialty_uid",
              "value": "={{ $json.analysis.specialist_needed === 'Cardiologist' ? 'cardiologist' : $json.analysis.specialist_needed === 'Dermatologist' ? 'dermatologist' : $json.analysis.specialist_needed === 'Neurologist' ? 'neurologist' : $json.analysis.specialist_needed === 'Orthopedist' ? 'orthopedic-surgeon' : $json.analysis.specialist_needed === 'Gastroenterologist' ? 'gastroenterologist' : $json.analysis.specialist_needed === 'Pulmonologist' ? 'pulmonologist' : 'family-practitioner' }}"
            },
            {
              "name": "location",
              "value": "={{ $json.location || 'New York, NY' }}"
            },
            {
              "name": "limit",
              "value": "5"
            },
            {
              "name": "user_key",
              "value": "YOUR_BETTERDOCTOR_API_KEY"
            }
          ]
        }
      },
      "typeVersion": 1
    },
    {
      "id": "a30ea8a7-1943-4549-9da1-a0d2372979db",
      "name": "Create Emergency Response",
      "type": "n8n-nodes-base.code",
      "position": [
        1180,
        1160
      ],
      "parameters": {
        "jsCode": "// Create emergency response\nconst patientData = items[0].json;\nconst symptoms = patientData.symptoms;\nconst analysis = patientData.analysis;\n\nconst emergencyMessage = `\ud83d\udea8 *URGENT MEDICAL ATTENTION NEEDED* \ud83d\udea8\\n\\n` +\n  `\u26a0\ufe0f Based on your symptoms, you may need immediate medical care.\\n\\n` +\n  `\ud83d\udccb *Your Symptoms:*\\n${symptoms}\\n\\n` +\n  `\ud83c\udfe5 *PLEASE DO ONE OF THE FOLLOWING IMMEDIATELY:*\\n` +\n  `\u2022 Call emergency services (911/108)\\n` +\n  `\u2022 Go to nearest emergency room\\n` +\n  `\u2022 Contact your doctor immediately\\n\\n` +\n  `\u26a0\ufe0f *This is an automated assessment. Trust your instincts - if you feel something is seriously wrong, seek immediate medical attention.*\\n\\n` +\n  `\ud83d\udcf1 Emergency Contact: 911 (US) | 108 (India)`;\n\nreturn [{\n  json: {\n    phone_number: patientData.phone,\n    email: patientData.email,\n    message: emergencyMessage,\n    type: 'emergency',\n    patient_data: patientData\n  }\n}];"
      },
      "typeVersion": 2
    },
    {
      "id": "1dbb9438-396b-4fc5-9a4a-7d493db64c47",
      "name": "Format Medical Response",
      "type": "n8n-nodes-base.code",
      "position": [
        1180,
        1360
      ],
      "parameters": {
        "jsCode": "// Format doctor recommendations and medical advice\nconst patientData = $node[\"Parse Medical Analysis\"].json;\nconst doctorsData = items[0].json;\nconst analysis = patientData.analysis;\n\n// Format doctors list\nlet doctorsList = '';\nif (doctorsData.data && doctorsData.data.length > 0) {\n  doctorsList = doctorsData.data.slice(0, 3).map((doctor, index) => {\n    const name = `${doctor.profile.first_name} ${doctor.profile.last_name}`;\n    const specialty = doctor.specialties[0]?.name || 'General Practice';\n    const phone = doctor.practices[0]?.phones[0]?.number || 'Not available';\n    const address = doctor.practices[0]?.visit_address ? \n      `${doctor.practices[0].visit_address.street}, ${doctor.practices[0].visit_address.city}` : \n      'Address not available';\n    \n    return `${index + 1}. *Dr. ${name}*\\n` +\n           `   \ud83c\udfe5 ${specialty}\\n` +\n           `   \ud83d\udcde ${phone}\\n` +\n           `   \ud83d\udccd ${address}\\n`;\n  }).join('\\n');\n} else {\n  doctorsList = 'No doctors found in your area. Please search online or contact your local healthcare directory.';\n}\n\n// Create comprehensive medical response\nconst urgencyEmoji = {\n  'low': '\ud83d\udfe2',\n  'medium': '\ud83d\udfe1', \n  'high': '\ud83d\udfe0',\n  'emergency': '\ud83d\udd34'\n};\n\nconst message = `\ud83c\udfe5 *Medical Assessment Results*\\n\\n` +\n  `\ud83d\udccb *Your Symptoms:*\\n${patientData.symptoms}\\n\\n` +\n  `${urgencyEmoji[analysis.urgency_level]} *Urgency Level:* ${analysis.urgency_level.toUpperCase()}\\n\\n` +\n  `\ud83d\udd0d *Possible Conditions:*\\n${analysis.possible_conditions.map(condition => `\u2022 ${condition}`).join('\\n')}\\n\\n` +\n  `\ud83d\udc68\u200d\u2695\ufe0f *Recommended Specialist:* ${analysis.specialist_needed}\\n\\n` +\n  `\ud83d\udca1 *Assessment:*\\n${analysis.severity_assessment}\\n\\n` +\n  `\u2705 *Recommended Actions:*\\n${analysis.recommended_actions.map(action => `\u2022 ${action}`).join('\\n')}\\n\\n`;\n\nlet fullMessage = message;\n\nif (analysis.red_flags && analysis.red_flags.length > 0) {\n  fullMessage += `\u26a0\ufe0f *Warning Signs:*\\n${analysis.red_flags.map(flag => `\u2022 ${flag}`).join('\\n')}\\n\\n`;\n}\n\nfullMessage += `\ud83d\udc69\u200d\u2695\ufe0f *Recommended Doctors Near You:*\\n${doctorsList}\\n\\n` +\n  `\u26a0\ufe0f *Important Disclaimer:*\\n` +\n  `This is an AI-generated assessment and should NOT replace professional medical advice. ` +\n  `Always consult with qualified healthcare providers for proper diagnosis and treatment.\\n\\n` +\n  `\ud83c\udd98 *If you experience severe symptoms or feel this is an emergency, ` +\n  `call emergency services immediately.*`;\n\nreturn [{\n  json: {\n    phone_number: patientData.phone,\n    email: patientData.email,\n    message: fullMessage,\n    type: 'medical_advice',\n    patient_data: patientData,\n    doctors: doctorsData.data || []\n  }\n}];"
      },
      "typeVersion": 2
    },
    {
      "id": "e88d7db7-1932-49dd-8899-b655fa35309a",
      "name": "Check WhatsApp Available",
      "type": "n8n-nodes-base.if",
      "position": [
        1400,
        1260
      ],
      "parameters": {
        "conditions": {
          "string": [
            {
              "value1": "={{ $json.phone_number }}",
              "operation": "isNotEmpty"
            }
          ]
        }
      },
      "typeVersion": 1
    },
    {
      "id": "a96b2f32-8df3-4788-85d5-ced36ff2a9d0",
      "name": "Prepare WhatsApp Message",
      "type": "n8n-nodes-base.code",
      "position": [
        1620,
        1160
      ],
      "parameters": {
        "jsCode": "// Prepare WhatsApp message payload\nconst data = items[0].json;\n\nreturn [{\n  json: {\n    messaging_product: \"whatsapp\",\n    to: data.phone_number,\n    type: \"text\",\n    text: {\n      body: data.message\n    }\n  }\n}];"
      },
      "typeVersion": 2
    },
    {
      "id": "d9824a6d-3782-4653-b492-088b4fb2689a",
      "name": "Send WhatsApp Response",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        1840,
        1160
      ],
      "parameters": {
        "url": "https://graph.facebook.com/v17.0/YOUR_PHONE_NUMBER_ID/messages",
        "options": {}
      },
      "typeVersion": 1
    },
    {
      "id": "df7d3ba7-fd59-4c61-849d-f6b378f091d1",
      "name": "Send Email Response",
      "type": "n8n-nodes-base.emailSend",
      "position": [
        1840,
        1360
      ],
      "parameters": {
        "html": "={{ $json.message.replace(/\\n/g, '<br>').replace(/\\*/g, '') }}",
        "options": {
          "allowUnauthorizedCerts": true
        },
        "subject": "\ud83c\udfe5 Your Medical Assessment & Doctor Recommendations",
        "toEmail": "={{ $json.email }}",
        "fromEmail": "user@example.com"
      },
      "credentials": {
        "smtp": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "38d61048-6dce-417e-ac59-8343bfea7851",
      "name": "Success Response",
      "type": "n8n-nodes-base.respondToWebhook",
      "position": [
        2060,
        1260
      ],
      "parameters": {
        "options": {},
        "respondWith": "json",
        "responseBody": "={{ { \"status\": \"success\", \"message\": \"Medical assessment sent successfully\", \"urgency_level\": $json.patient_data ? $json.patient_data.analysis.urgency_level : 'unknown', \"timestamp\": new Date().toISOString() } }}"
      },
      "typeVersion": 1
    },
    {
      "id": "e8bf4043-7a7a-45bb-93e0-f821f5f1febe",
      "name": "Medical Bot Overview",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -40,
        700
      ],
      "parameters": {
        "color": 5,
        "width": 600,
        "height": 400,
        "content": "## \ud83c\udfe5 AI Symptom Checker & Doctor Suggestion\n\n**Complete Medical Assistant Workflow:**\n\n\ud83d\udd0d **Symptom Analysis** - AI analyzes symptoms with urgency assessment\n\ud83d\udc68\u200d\u2695\ufe0f **Doctor Matching** - Finds relevant specialists in user's area\n\ud83d\udcf1 **Multi-Channel Delivery** - Sends via WhatsApp + Email\n\ud83d\udea8 **Emergency Detection** - Identifies urgent cases automatically\n\ud83d\udcca **Data Logging** - Tracks consultations for analytics\n\n\u2705 HIPAA-compliant data handling\n\u2705 Professional medical disclaimers\n\u2705 Emergency response protocols"
      },
      "typeVersion": 1
    },
    {
      "id": "13fa264a-485b-4fa1-8458-2d8f1b74c1a5",
      "name": "Setup Guide",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        720,
        260
      ],
      "parameters": {
        "color": 7,
        "width": 680,
        "height": 560,
        "content": "## \ud83d\udee0\ufe0f Setup Requirements:\n\n**APIs & Services:**\n1. **BetterDoctor API** - Doctor directory (free tier)\n2. **WhatsApp Business API** - Meta Developer account\n3. **SMTP Email** - For email notifications\n4. **Ollama** - Local AI model\n\n**Input Format (Webhook):**\n```json\n{\n  \"symptoms\": \"headache, fever, nausea\",\n  \"age\": 30,\n  \"gender\": \"male\",\n  \"duration\": \"2 days\",\n  \"phone\": \"+1234567890\",\n  \"email\": \"user@email.com\",\n  \"location\": \"New York, NY\"\n}\n```\n\n**Test URL:**\nPOST https://your-n8n-instance.com/webhook/symptom-checker-webhook"
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "27ec8d81-3686-4bf6-b767-b808b5328bf6",
  "connections": {
    "Find Doctors": {
      "main": [
        [
          {
            "node": "Format Medical Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Emergency": {
      "main": [
        [
          {
            "node": "Create Emergency Response",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Find Doctors",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Medical AI Model": {
      "ai_languageModel": [
        [
          {
            "node": "AI Symptom Analysis",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "AI Symptom Analysis": {
      "main": [
        [
          {
            "node": "Parse Medical Analysis",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send Email Response": {
      "main": [
        [
          {
            "node": "Success Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Symptom Input Webhook": {
      "main": [
        [
          {
            "node": "AI Symptom Analysis",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse Medical Analysis": {
      "main": [
        [
          {
            "node": "Check Emergency",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send WhatsApp Response": {
      "main": [
        [
          {
            "node": "Success Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format Medical Response": {
      "main": [
        [
          {
            "node": "Check WhatsApp Available",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check WhatsApp Available": {
      "main": [
        [
          {
            "node": "Prepare WhatsApp Message",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Send Email Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare WhatsApp Message": {
      "main": [
        [
          {
            "node": "Send WhatsApp Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Emergency Response": {
      "main": [
        [
          {
            "node": "Check WhatsApp Available",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}