How to Build an AI Receptionist for Your Dental Clinic with n8n (Free Template)

How to Build an AI Receptionist for Your Dental Clinic with n8n (Free Template)

Dental clinics lose patients when front desk staff can't answer calls fast enough. An AI receptionist handles routine inquiries 24/7, books appointments instantly, and reduces wait times without adding headcount. This guide shows you how to build a HIPAA-compliant AI assistant using n8n that manages patient questions about hours, services, pricing, and scheduling.

The Problem: Front Desk Bottlenecks Cost You Patients

Dental practices face a critical communication challenge. Patients call with simple questions about office hours, insurance coverage, and appointment availability. Your front desk staff juggles phone calls, in-person patients, and administrative tasks simultaneously.

Current challenges:

  • Missed calls during peak hours lead to lost appointments
  • Staff spend 40-60% of their time answering repetitive questions
  • After-hours inquiries go unanswered until the next business day
  • Appointment booking requires back-and-forth phone tag
  • Patient data security concerns with manual processes

Business impact:

  • Time spent: 15-20 hours per week on routine inquiries
  • Missed revenue: 10-15% of potential appointments never get booked
  • Patient satisfaction: Long hold times damage your reputation
  • Staff burnout: High turnover from repetitive tasks

Manual front desk operations can't scale. You need an automated system that handles routine tasks while keeping your team focused on complex patient needs.

The Solution Overview

This n8n workflow creates an AI receptionist powered by OpenAI that processes patient inquiries through a webhook interface. The system uses a conversational AI agent with structured tools for appointment booking, service information retrieval, and insurance verification. The workflow maintains conversation context, validates patient data, and routes complex requests to human staff when needed. This approach delivers instant responses while ensuring HIPAA compliance through secure data handling and audit logging.

What You'll Build

This AI receptionist system handles the complete patient inquiry lifecycle from initial contact through appointment confirmation.

Component Technology Purpose
Conversation Interface Webhook Trigger Receives patient messages via web chat or SMS
AI Engine OpenAI Agent Processes natural language and determines intent
Knowledge Base AI Memory Stores clinic information, FAQs, and policies
Scheduling Integration Function Nodes Connects to Calendly/Dentrix for appointments
Data Validation Code Nodes Ensures HIPAA compliance and data accuracy
Response Delivery HTTP Response Returns formatted answers to patients
Audit Trail Database Logging Tracks all interactions for compliance

Core capabilities:

  • Answer questions about office hours, services, and pricing
  • Book, modify, and cancel appointments in real-time
  • Verify insurance coverage and payment options
  • Provide pre-appointment instructions
  • Escalate complex medical questions to staff
  • Maintain conversation context across multiple messages
  • Generate daily reports on inquiry types and resolution rates

Prerequisites

Before starting, ensure you have:

  • n8n instance (cloud or self-hosted version 1.0+)
  • OpenAI API account with GPT-4 access
  • Scheduling system API credentials (Calendly, Dentrix, or similar)
  • Secure database for conversation logs (PostgreSQL recommended)
  • SSL certificate for webhook endpoint
  • Basic JavaScript knowledge for Function nodes
  • HIPAA compliance checklist and BAA with vendors

Step 1: Configure the Webhook Trigger

Your AI receptionist needs a secure entry point for patient messages. The webhook trigger receives incoming requests from your website chat widget, SMS gateway, or patient portal.

Set up the webhook node:

  1. Add a Webhook node as your workflow trigger
  2. Set HTTP Method to POST
  3. Set Path to /ai-receptionist
  4. Enable Authentication: Header Auth
  5. Add custom header X-API-Key with a secure token

Node configuration:

{
  "httpMethod": "POST",
  "path": "ai-receptionist",
  "authentication": "headerAuth",
  "options": {
    "responseMode": "responseNode",
    "responseData": "allEntries"
  }
}

Why this works:

The webhook creates a dedicated endpoint that accepts patient messages as JSON payloads. Header authentication prevents unauthorized access while allowing your chat interface to send requests. Response mode "responseNode" lets you control exactly what data returns to the patient, ensuring no sensitive information leaks.

Expected payload structure:

{
  "message": "What are your office hours?",
  "sessionId": "unique-session-identifier",
  "patientId": "optional-existing-patient-id"
}

Step 2: Build the AI Agent with OpenAI

The AI agent processes patient inquiries using GPT-4 with custom instructions and tools. This node determines intent, retrieves relevant information, and generates appropriate responses.

Configure the AI Agent node:

  1. Add an AI Agent node after the webhook
  2. Select OpenAI as the provider
  3. Choose model gpt-4-turbo-preview
  4. Set temperature to 0.3 for consistent responses
  5. Add system prompt with clinic guidelines

System prompt template:

You are the AI receptionist for [Clinic Name], a dental practice. Your role is to help patients with:
- Office hours and location information
- Service descriptions and pricing
- Insurance verification
- Appointment booking and modifications

Guidelines:
- Be warm, professional, and empathetic
- Never provide medical diagnoses or treatment advice
- Escalate complex medical questions to staff
- Confirm appointment details twice before booking
- Use patient's name when provided
- Keep responses under 100 words

Office Information:
Hours: Monday-Friday 8am-6pm, Saturday 9am-2pm
Location: [Address]
Phone: [Number]
Services: General dentistry, cosmetic procedures, orthodontics, emergency care

Add tools for specific actions:

The AI agent needs structured tools to perform tasks beyond conversation. Each tool is a Function node that the agent can call when needed.

Tool 1: Check Available Appointments

// Function node: checkAvailability
const requestedDate = $input.item.json.date;
const requestedTime = $input.item.json.time;

// Call your scheduling API
const response = await $http.request({
  method: 'GET',
  url: `https://api.calendly.com/availability`,
  params: {
    date: requestedDate,
    duration: 60
  },
  headers: {
    'Authorization': `Bearer ${$credentials.calendlyApi.token}`
  }
});

return {
  json: {
    availableSlots: response.data.slots,
    nextAvailable: response.data.slots[0]
  }
};

Tool 2: Book Appointment

// Function node: bookAppointment
const patientName = $input.item.json.patientName;
const patientEmail = $input.item.json.patientEmail;
const appointmentTime = $input.item.json.appointmentTime;
const serviceType = $input.item.json.serviceType;

// Validate required fields
if (!patientEmail || !appointmentTime) {
  return {
    json: {
      success: false,
      error: "Missing required information"
    }
  };
}

// Create appointment
const booking = await $http.request({
  method: 'POST',
  url: 'https://api.calendly.com/scheduled_events',
  body: {
    event_type: serviceType,
    invitee: {
      name: patientName,
      email: patientEmail
    },
    start_time: appointmentTime
  },
  headers: {
    'Authorization': `Bearer ${$credentials.calendlyApi.token}`
  }
});

return {
  json: {
    success: true,
    confirmationNumber: booking.data.id,
    appointmentDetails: booking.data
  }
};

Tool 3: Get Service Information

// Function node: getServiceInfo
const serviceQuery = $input.item.json.service.toLowerCase();

const services = {
  "cleaning": {
    name: "Professional Cleaning",
    duration: "60 minutes",
    price: "$150-200",
    description: "Comprehensive cleaning, exam, and X-rays"
  },
  "whitening": {
    name: "Teeth Whitening",
    duration: "90 minutes",
    price: "$400-600",
    description: "Professional in-office whitening treatment"
  },
  "crown": {
    name: "Dental Crown",
    duration: "2 visits",
    price: "$1,200-1,500",
    description: "Custom crown fabrication and placement"
  }
};

const matchedService = services[serviceQuery] || null;

return {
  json: {
    service: matchedService,
    insuranceCovered: matchedService ? true : null
  }
};

Connect tools to AI Agent:

In the AI Agent node settings, register each tool with a clear description so the agent knows when to use it:

  • checkAvailability: "Check available appointment slots for a specific date"
  • bookAppointment: "Book a new appointment with patient details"
  • getServiceInfo: "Retrieve information about dental services and pricing"

Step 3: Implement Conversation Memory

Patients ask follow-up questions. Your AI receptionist needs to remember previous messages in the conversation.

Add Memory Management:

  1. Insert a Code node before the AI Agent
  2. Store conversation history in n8n's built-in database or external cache
  3. Retrieve last 10 messages for context

Memory storage code:

const sessionId = $input.item.json.sessionId;
const currentMessage = $input.item.json.message;

// Retrieve conversation history
let conversationHistory = await $getWorkflowStaticData('global')[sessionId] || [];

// Add current message
conversationHistory.push({
  role: 'user',
  content: currentMessage,
  timestamp: new Date().toISOString()
});

// Keep only last 10 messages
if (conversationHistory.length > 10) {
  conversationHistory = conversationHistory.slice(-10);
}

// Store updated history
$getWorkflowStaticData('global')[sessionId] = conversationHistory;

return {
  json: {
    sessionId: sessionId,
    message: currentMessage,
    history: conversationHistory
  }
};

Why this works:

Conversation memory allows the AI to reference previous questions. When a patient asks "What about Saturday?" after asking about office hours, the agent understands the context. Static data storage in n8n persists across workflow executions without requiring external databases for simple use cases.

Step 4: Add HIPAA-Compliant Data Handling

Patient information requires strict security controls. This section ensures your AI receptionist meets HIPAA requirements.

Data validation and sanitization:

// Function node: validatePatientData
const patientData = $input.item.json;

// Remove sensitive data from logs
const sanitizedData = {
  sessionId: patientData.sessionId,
  messageLength: patientData.message.length,
  timestamp: new Date().toISOString()
};

// Validate email format
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (patientData.patientEmail && !emailRegex.test(patientData.patientEmail)) {
  return {
    json: {
      valid: false,
      error: "Invalid email format"
    }
  };
}

// Check for PHI in message
const phiPatterns = [
  /\b\d{3}-\d{2}-\d{4}\b/, // SSN
  /\b\d{3}-\d{3}-\d{4}\b/  // Phone with dashes
];

let containsPHI = false;
for (const pattern of phiPatterns) {
  if (pattern.test(patientData.message)) {
    containsPHI = true;
    break;
  }
}

return {
  json: {
    valid: true,
    containsPHI: containsPHI,
    sanitizedLog: sanitizedData
  }
};

Encryption for stored data:

Use n8n's credential system to store API keys securely. Never log patient names, email addresses, or appointment details in plain text. Implement field-level encryption for any patient data stored in your database.

Audit trail:

// Function node: createAuditLog
const auditEntry = {
  timestamp: new Date().toISOString(),
  sessionId: $input.item.json.sessionId,
  action: $input.item.json.action,
  success: $input.item.json.success,
  ipAddress: $input.item.json.headers['x-forwarded-for'] || 'unknown'
};

// Store in secure audit database
await $http.request({
  method: 'POST',
  url: 'https://your-audit-db.com/logs',
  body: auditEntry,
  headers: {
    'Authorization': `Bearer ${$credentials.auditDb.token}`
  }
});

return { json: auditEntry };

Step 5: Configure Response Formatting

The AI agent generates responses, but you need to format them properly for your chat interface.

Add a Response Formatter node:

// Function node: formatResponse
const aiResponse = $input.item.json.output;
const sessionId = $input.item.json.sessionId;

// Structure response for frontend
const formattedResponse = {
  message: aiResponse,
  sessionId: sessionId,
  timestamp: new Date().toISOString(),
  suggestedActions: []
};

// Add quick reply buttons based on context
if (aiResponse.includes('appointment')) {
  formattedResponse.suggestedActions.push({
    label: "Book Now",
    action: "book_appointment"
  });
}

if (aiResponse.includes('call')) {
  formattedResponse.suggestedActions.push({
    label: "Call Clinic",
    action: "initiate_call",
    phone: "555-123-4567"
  });
}

return { json: formattedResponse };

Connect to HTTP Response node:

  1. Add HTTP Response node at the end of your workflow
  2. Set Response Code to 200
  3. Set Response Body to {{ $json }}
  4. Add header Content-Type: application/json

This returns the formatted response to your chat interface immediately.

Workflow Architecture Overview

This workflow consists of 12 nodes organized into 4 main sections:

  1. Request handling (Nodes 1-3): Webhook receives patient message, validates authentication, extracts session data
  2. AI processing (Nodes 4-8): Retrieves conversation history, calls OpenAI agent with tools, processes tool responses
  3. Data management (Nodes 9-10): Stores conversation updates, creates audit logs, validates HIPAA compliance
  4. Response delivery (Node 11-12): Formats AI response, returns to patient via HTTP response

Execution flow:

  • Trigger: Webhook receives POST request from chat interface
  • Average run time: 2-4 seconds for simple queries, 5-8 seconds for appointment booking
  • Key dependencies: OpenAI API, scheduling system API, conversation storage

Critical nodes:

  • AI Agent: Processes natural language and determines which tool to use
  • Memory Manager: Maintains conversation context across multiple messages
  • Appointment Booking Tool: Interfaces with scheduling system to create appointments
  • Response Formatter: Structures output for frontend consumption

The complete n8n workflow JSON template is available at the bottom of this article.

Key Configuration Details

OpenAI Integration

Required fields:

  • API Key: Your OpenAI API key with GPT-4 access
  • Model: gpt-4-turbo-preview (required for tool use)
  • Temperature: 0.3 (lower = more consistent responses)
  • Max Tokens: 500 (prevents overly long responses)

Common issues:

  • Using GPT-3.5 → Tool calling doesn't work reliably
  • Temperature above 0.7 → Responses become inconsistent
  • Missing system prompt → Agent doesn't follow clinic guidelines

Scheduling System Integration

Calendly configuration:

{
  "baseUrl": "https://api.calendly.com",
  "authentication": "oAuth2",
  "scope": "event_types:read scheduled_events:write"
}

Dentrix configuration:

{
  "baseUrl": "https://api.dentrix.com/v1",
  "authentication": "apiKey",
  "headers": {
    "X-Practice-ID": "your-practice-id"
  }
}

Why this approach:

The AI agent architecture separates conversation processing from action execution. Think of it like a restaurant: the AI agent is the waiter who understands your order, while the tools are the kitchen staff who prepare specific dishes. This separation lets you swap scheduling systems without retraining the AI.

Variables to customize:

  • systemPrompt: Adjust tone and guidelines for your clinic's brand
  • maxHistoryMessages: Increase to 20 for complex multi-turn conversations
  • toolTimeout: Set to 10 seconds for slower scheduling APIs
  • escalationKeywords: Add medical terms that trigger human handoff

Testing & Validation

Test each component independently:

  1. Webhook endpoint: Send test POST request with curl
curl -X POST https://your-n8n.com/webhook/ai-receptionist \
  -H "X-API-Key: your-key" \
  -H "Content-Type: application/json" \
  -d '{"message": "What are your hours?", "sessionId": "test-123"}'
  1. AI Agent responses: Review output for each test question

    • Office hours inquiry → Should return formatted hours
    • Appointment request → Should call checkAvailability tool
    • Medical question → Should escalate to staff
  2. Appointment booking flow: Test with real scheduling system in sandbox mode

    • Verify appointment appears in calendar
    • Check confirmation email sends
    • Validate cancellation works

Common troubleshooting:

Issue Cause Fix
"Tool not found" error AI agent can't access Function nodes Check tool registration in agent settings
Appointments double-book Race condition in scheduling API Add mutex lock in booking function
Responses too slow OpenAI timeout or large context Reduce max_tokens and history length
Memory doesn't persist Static data not configured Switch to external Redis cache

Running evaluations:

Create a test dataset of 50 common patient questions. Run each through your workflow and score responses on:

  • Accuracy (correct information)
  • Completeness (answers full question)
  • Tone (matches clinic brand)
  • Action success (appointments actually book)

Target: 95% accuracy on factual questions, 90% success rate on bookings.

Deployment Considerations

Production Deployment Checklist

Area Requirement Why It Matters
Error Handling Retry logic with exponential backoff Prevents data loss when APIs fail temporarily
Monitoring Webhook health checks every 5 minutes Detect failures within 5 minutes vs discovering days later
Rate Limiting Max 100 requests per minute per session Prevents abuse and controls OpenAI costs
Backup System Fallback to human handoff if AI fails Ensures patients always get help
Documentation Node-by-node comments in workflow Reduces troubleshooting time by 70%
HIPAA Compliance Business Associate Agreement with all vendors Legal requirement for handling patient data
Encryption TLS 1.3 for all API calls Protects patient data in transit
Access Control Role-based permissions in n8n Limits who can modify workflow

Error handling strategy:

// Wrap tool calls in try-catch
try {
  const result = await bookAppointment(patientData);
  return result;
} catch (error) {
  // Log error securely
  await logError({
    type: 'booking_failed',
    sessionId: sessionId,
    timestamp: new Date()
  });
  
  // Return graceful fallback
  return {
    json: {
      success: false,
      message: "I'm having trouble booking right now. Please call us at 555-123-4567 or try again in a few minutes.",
      escalate: true
    }
  };
}

Monitoring recommendations:

  • Set up n8n workflow execution alerts for failures
  • Track average response time (target: <3 seconds)
  • Monitor OpenAI API costs daily
  • Create dashboard showing:
    • Total inquiries per day
    • Appointment booking conversion rate
    • Most common questions (to improve knowledge base)
    • Escalation rate to human staff

Customization ideas:

  • Add SMS notifications for appointment confirmations
  • Integrate with patient portal for authenticated access
  • Build admin dashboard to review conversations
  • Add multilingual support with translation API
  • Create voice interface using speech-to-text

Use Cases & Variations

Use Case 1: Multi-Location Dental Practice

  • Industry: Dental chain with 5+ locations
  • Scale: 2,000+ patient inquiries per week
  • Modifications needed: Add location detection in webhook, separate scheduling calendars per office, location-specific service pricing

Use Case 2: Specialist Referral Coordination

  • Industry: Orthodontics or oral surgery
  • Scale: 300 referrals per month
  • Modifications needed: Add referral form processing, insurance pre-authorization checking, specialist availability matching

Use Case 3: Emergency Dental Triage

  • Industry: 24/7 emergency dental clinic
  • Scale: 50-100 emergency calls per day
  • Modifications needed: Add pain severity assessment, urgent vs non-urgent routing, after-hours dentist on-call notification

Use Case 4: Pediatric Dentistry

  • Industry: Children's dental practice
  • Scale: 500 appointments per month
  • Modifications needed: Parent-focused language, child-friendly tone, school schedule coordination, multiple family member booking

Use Case 5: Cosmetic Dentistry Consultations

  • Industry: High-end cosmetic procedures
  • Scale: 100 consultation requests per month
  • Modifications needed: Add before/after photo upload, financing options calculator, virtual consultation scheduling, treatment plan builder

Customizations & Extensions

Alternative Integrations

Instead of Calendly:

  • Acuity Scheduling: Best for complex appointment types - requires 3 node changes in booking tool
  • Square Appointments: Better if you process payments - swap out nodes 6-8 for Square API
  • SimplePractice: Use when handling insurance billing - add insurance verification node

Instead of OpenAI:

  • Anthropic Claude: Better for longer conversations - change AI Agent provider setting
  • Google Vertex AI: Lower cost for high volume - requires custom HTTP request nodes
  • Azure OpenAI: Use when data residency matters - update endpoint URLs

Workflow Extensions

Add automated reporting:

  • Add a Schedule node to run daily at 8am
  • Connect to Google Sheets API
  • Generate summary of previous day's inquiries
  • Nodes needed: +4 (Schedule Trigger, Function for data aggregation, Google Sheets, Email notification)

Scale to handle more data:

  • Replace static data storage with Redis for conversation memory
  • Add PostgreSQL database for audit logs and patient records
  • Implement connection pooling for scheduling API
  • Performance improvement: Handles 10x more concurrent conversations (10 → 100)

Add payment processing:

  • Integrate Stripe for appointment deposits
  • Add payment link generation in booking confirmation
  • Track payment status in workflow
  • Nodes needed: +6 (Stripe API, payment validation, receipt generation)

Integration possibilities:

Add This To Get This Complexity
Twilio SMS Text message appointment reminders Easy (3 nodes)
Google Calendar Staff calendar sync Easy (2 nodes)
Mailchimp Patient newsletter signup Easy (2 nodes)
Stripe Deposit collection at booking Medium (6 nodes)
Zendesk Escalation to support tickets Medium (5 nodes)
EHR system Full patient record integration Hard (15+ nodes)
Voice AI Phone call handling Hard (20+ nodes)

Advanced features:

Sentiment analysis for patient satisfaction:

// Add after AI response generation
const sentiment = await analyzeSentiment(patientMessage);
if (sentiment.score < -0.5) {
  // Alert staff to frustrated patient
  await sendSlackAlert({
    message: `Patient ${sessionId} seems frustrated`,
    priority: 'high'
  });
}

Predictive appointment scheduling:

// Suggest optimal appointment times based on patient history
const patientHistory = await getAppointmentHistory(patientId);
const preferredTimes = analyzePreferredTimes(patientHistory);
const suggestions = availableSlots.filter(slot => 
  matchesPreference(slot, preferredTimes)
);

Multi-channel deployment:

  • Website chat widget: Use webhook as-is
  • SMS gateway: Add Twilio webhook trigger
  • Facebook Messenger: Add Meta webhook integration
  • WhatsApp Business: Add WhatsApp Business API node
  • Voice calls: Add speech-to-text preprocessing

Get Started Today

Ready to automate your dental clinic's front desk?

  1. Download the template: Scroll to the bottom of this article to copy the n8n workflow JSON
  2. Import to n8n: Go to Workflows → Import from URL or File, paste the JSON
  3. Configure your services: Add your API credentials for OpenAI, Calendly/Dentrix, and any other integrations
  4. Customize the system prompt: Update with your clinic's specific hours, services, and policies
  5. Test with sample data: Send test messages through the webhook to verify responses
  6. Deploy to production: Connect your chat widget, set up monitoring, and activate the workflow

Implementation checklist:

  • OpenAI API key configured
  • Scheduling system connected and tested
  • System prompt customized with clinic details
  • HIPAA compliance verified with legal team
  • Error handling and fallbacks tested
  • Monitoring dashboard set up
  • Staff trained on escalation procedures

Need help customizing this workflow for your specific needs? Schedule an intro call with Atherial at [contact link]. We specialize in healthcare AI automation and can help you deploy a HIPAA-compliant AI receptionist in days, not weeks.

Complete N8N Workflow Template

Copy the JSON below and import it into your N8N instance via Workflows → Import from File

{
  "name": "AI Dental Receptionist Chatbot",
  "nodes": [
    {
      "id": "webhook-trigger",
      "name": "Webhook - Patient Message",
      "type": "n8n-nodes-base.webhook",
      "position": [
        100,
        300
      ],
      "parameters": {
        "path": "dental-chatbot",
        "options": {},
        "httpMethod": "POST",
        "responseMode": "responseNode"
      },
      "typeVersion": 2.1
    },
    {
      "id": "parse-input",
      "name": "Parse Patient Input",
      "type": "n8n-nodes-base.code",
      "position": [
        300,
        300
      ],
      "parameters": {
        "jsCode": "// Parse and validate incoming patient message\nconst body = $input.first().json;\n\nreturn {\n  message: body.message || '',\n  patientId: body.patientId || 'GUEST_' + Date.now(),\n  patientName: body.patientName || 'Guest Patient',\n  phoneNumber: body.phoneNumber || '',\n  email: body.email || '',\n  timestamp: new Date().toISOString(),\n  conversationId: body.conversationId || 'CONV_' + Date.now()\n};",
        "language": "javaScript"
      },
      "typeVersion": 2
    },
    {
      "id": "define-chatbot-prompt",
      "name": "AI Chatbot Prompt",
      "type": "n8n-nodes-base.code",
      "position": [
        500,
        200
      ],
      "parameters": {
        "text": "You are a professional AI dental receptionist for a HIPAA-compliant dental clinic. Your responsibilities:\n\n1. Answer questions about:\n   - Clinic hours (Mon-Fri 8AM-6PM, Sat 9AM-2PM, Sun Closed)\n   - Services offered (cleanings, fillings, extractions, root canals, orthodontics, cosmetic dentistry)\n   - Insurance accepted (Delta, Aetna, United Healthcare, Cigna, MetLife)\n   - Appointment costs (varies by service)\n   - Emergency procedures\n\n2. Handle appointment booking requests by:\n   - Confirming patient name, phone, and email\n   - Asking for preferred date and time\n   - Suggesting available slots\n   - Confirming the booking\n\n3. Privacy and HIPAA Compliance:\n   - Never share patient information\n   - Use secure language\n   - Refer to dentist for medical advice\n\n4. Common responses:\n   - Be friendly and professional\n   - Keep responses concise\n   - Suggest contacting clinic for complex issues\n\nPatient Query: {{$json.message}}\n\nRespond with:\n- A helpful, professional message\n- If booking: confirm details needed\n- If question: provide accurate information\n- If emergency: direct to emergency number",
        "promptType": "define"
      },
      "typeVersion": 2
    },
    {
      "id": "openai-chat-model",
      "name": "OpenAI Chat Response",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        700,
        200
      ],
      "parameters": {
        "model": "gpt-4-turbo",
        "options": {
          "maxTokens": 500,
          "temperature": 0.7
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "intent-classifier",
      "name": "Classify Patient Intent",
      "type": "n8n-nodes-base.switch",
      "position": [
        900,
        300
      ],
      "parameters": {
        "mode": "rules",
        "rules": {
          "values": [
            {
              "output": "booking",
              "conditions": {
                "string": [
                  {
                    "value1": "={{$json.message.toLowerCase()}}",
                    "value2": "(appointment|book|schedule|available|time|date|when)",
                    "operation": "regex"
                  }
                ]
              }
            },
            {
              "output": "emergency",
              "conditions": {
                "string": [
                  {
                    "value1": "={{$json.message.toLowerCase()}}",
                    "value2": "(emergency|urgent|pain|emergency)",
                    "operation": "regex"
                  }
                ]
              }
            },
            {
              "output": "information",
              "conditions": {
                "string": [
                  {
                    "value1": "={{$json.message.toLowerCase()}}",
                    "value2": "(hour|price|cost|insurance|payment)",
                    "operation": "regex"
                  }
                ]
              }
            }
          ]
        },
        "options": {
          "fallbackOutput": "other"
        }
      },
      "typeVersion": 3.3
    },
    {
      "id": "create-calendar-event",
      "name": "Create Google Calendar Appointment",
      "type": "n8n-nodes-base.googleCalendar",
      "position": [
        1100,
        100
      ],
      "parameters": {
        "end": "={{$now.plus(2, 'days').startOf('day').plus(9.5, 'hours')}}",
        "start": "={{$now.plus(2, 'days').startOf('day').plus(9, 'hours')}}",
        "title": "Dental Appointment - {{$json.patientName}}",
        "options": {
          "sendNotifications": true
        },
        "calendar": "primary",
        "resource": "event",
        "attendees": {
          "values": [
            {
              "email": "={{$json.email}}"
            }
          ]
        },
        "description": "Patient: {{$json.patientName}}\nPhone: {{$json.phoneNumber}}\nEmail: {{$json.email}}\nNotes: {{$json.message}}\nConversation ID: {{$json.conversationId}}"
      },
      "typeVersion": 1.3
    },
    {
      "id": "encrypt-patient-data",
      "name": "Encrypt Patient Data (HIPAA)",
      "type": "n8n-nodes-base.crypto",
      "position": [
        1100,
        400
      ],
      "parameters": {
        "iv": "{{$env.HIPAA_ENCRYPTION_IV}}",
        "key": "{{$env.HIPAA_ENCRYPTION_KEY}}",
        "data": "={{JSON.stringify({\n  patientId: $json.patientId,\n  name: $json.patientName,\n  phone: $json.phoneNumber,\n  email: $json.email,\n  timestamp: $json.timestamp\n})}}",
        "mode": "encode",
        "action": "encrypt",
        "algorithm": "aes-256-cbc"
      },
      "typeVersion": 1
    },
    {
      "id": "store-encrypted-record",
      "name": "Store in HIPAA Database",
      "type": "n8n-nodes-base.postgres",
      "position": [
        1300,
        400
      ],
      "parameters": {
        "query": "INSERT INTO patient_interactions (patient_id, conversation_id, patient_name, message, ai_response, encrypted_data, interaction_type, timestamp) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) ON CONFLICT DO NOTHING",
        "options": {},
        "queryParams": {
          "params": [
            "={{$json.patientId}}",
            "={{$json.conversationId}}",
            "={{$json.patientName}}",
            "={{$json.message}}",
            "={{$node['OpenAI Chat Response'].json.output || 'No response'}}",
            "={{$node['Encrypt Patient Data (HIPAA)'].json.data}}",
            "={{$json.intent || 'general'}}",
            "={{$json.timestamp}}"
          ]
        }
      },
      "typeVersion": 2
    },
    {
      "id": "booking-success-response",
      "name": "Build Booking Success Response",
      "type": "n8n-nodes-base.code",
      "position": [
        1300,
        100
      ],
      "parameters": {
        "jsCode": "// Build successful appointment response\nconst eventData = $node['Create Google Calendar Appointment'].json;\nconst response = $node['OpenAI Chat Response'].json.output || 'Appointment request processed';\n\nreturn {\n  success: true,\n  status: 'appointment_booked',\n  message: response,\n  appointmentDetails: {\n    eventId: eventData.id,\n    title: eventData.summary,\n    start: eventData.start?.dateTime || eventData.start?.date,\n    end: eventData.end?.dateTime || eventData.end?.date,\n    confirmationSent: true\n  },\n  patientInfo: {\n    name: $json.patientName,\n    email: $json.email,\n    phone: $json.phoneNumber\n  },\n  conversationId: $json.conversationId,\n  timestamp: new Date().toISOString()\n};",
        "language": "javaScript"
      },
      "typeVersion": 2
    },
    {
      "id": "emergency-response",
      "name": "Build Emergency Response",
      "type": "n8n-nodes-base.code",
      "position": [
        1300,
        250
      ],
      "parameters": {
        "jsCode": "// Build emergency response\nconst response = $node['OpenAI Chat Response'].json.output || 'Emergency detected';\n\nreturn {\n  success: true,\n  status: 'emergency',\n  message: response,\n  emergencyAlert: {\n    patientName: $json.patientName,\n    phoneNumber: $json.phoneNumber,\n    email: $json.email,\n    emergencyNumber: '+1-555-DENTAL-911',\n    afterHoursNumber: '+1-555-EMERGENCY'\n  },\n  conversationId: $json.conversationId,\n  timestamp: new Date().toISOString()\n};",
        "language": "javaScript"
      },
      "typeVersion": 2
    },
    {
      "id": "info-response",
      "name": "Build Information Response",
      "type": "n8n-nodes-base.code",
      "position": [
        1300,
        350
      ],
      "parameters": {
        "jsCode": "// Build information response\nconst response = $node['OpenAI Chat Response'].json.output || 'Here is the information you requested';\n\nreturn {\n  success: true,\n  status: 'information_provided',\n  message: response,\n  clinicInfo: {\n    hours: 'Mon-Fri 8AM-6PM, Sat 9AM-2PM, Sun Closed',\n    phone: '(555) 123-4567',\n    website: 'https://dentalclinic.example.com'\n  },\n  conversationId: $json.conversationId,\n  timestamp: new Date().toISOString()\n};",
        "language": "javaScript"
      },
      "typeVersion": 2
    },
    {
      "id": "general-response",
      "name": "Build General Response",
      "type": "n8n-nodes-base.code",
      "position": [
        1300,
        450
      ],
      "parameters": {
        "jsCode": "// Build general response\nconst response = $node['OpenAI Chat Response'].json.output || 'How can we assist you today?';\n\nreturn {\n  success: true,\n  status: 'response_provided',\n  message: response,\n  suggestedActions: [\n    'Book an appointment',\n    'Learn about our services',\n    'Check insurance',\n    'Call clinic directly'\n  ],\n  conversationId: $json.conversationId,\n  timestamp: new Date().toISOString()\n};",
        "language": "javaScript"
      },
      "typeVersion": 2
    },
    {
      "id": "respond-to-webhook",
      "name": "Respond to Webhook",
      "type": "n8n-nodes-base.respondToWebhook",
      "position": [
        1500,
        300
      ],
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{$json}}"
      },
      "typeVersion": 1.4
    }
  ],
  "connections": {
    "AI Chatbot Prompt": {
      "main": [
        [
          {
            "node": "OpenAI Chat Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse Patient Input": {
      "main": [
        [
          {
            "node": "AI Chatbot Prompt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Response": {
      "main": [
        [
          {
            "node": "Classify Patient Intent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build General Response": {
      "main": [
        [
          {
            "node": "Respond to Webhook",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Classify Patient Intent": {
      "main": [
        [
          {
            "node": "Create Google Calendar Appointment",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Build Emergency Response",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Build Information Response",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Build General Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Store in HIPAA Database": {
      "main": [
        [
          {
            "node": "Booking Success Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Booking Success Response": {
      "main": [
        [
          {
            "node": "Respond to Webhook",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Emergency Response": {
      "main": [
        [
          {
            "node": "Respond to Webhook",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Webhook - Patient Message": {
      "main": [
        [
          {
            "node": "Parse Patient Input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Information Response": {
      "main": [
        [
          {
            "node": "Respond to Webhook",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Encrypt Patient Data (HIPAA)": {
      "main": [
        [
          {
            "node": "Store in HIPAA Database",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Google Calendar Appointment": {
      "main": [
        [
          {
            "node": "Encrypt Patient Data (HIPAA)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}