Predict customer churn with AI analysis of HubSpot and Google Sheets data
Who it’s for
Built for Customer Success and Account Management teams focused on proactive retention. This workflow helps you automatically identify at-risk customers – before they churn – by combining CRM, usage, and sentiment data into one actionable alert.
What it does
This end-to-end workflow continuously monitors customer health by consolidating data from HubSpot and Google Sheets. Here’s how it works:
- Fetch deals from HubSpot.
- Collect context — linked support tickets and feature usage from a Google Sheet.
- Run sentiment analysis on the tickets to generate a customer health score.
- Evaluate risk — an AI agent reviews deal age, sentiment score, and usage trends against predefined thresholds.
- Send alerts — if churn risk is detected, it automatically sends a clear, data-driven email to the responsible team member with next-step recommendations.
How to set it up
To get started, configure your credentials and parameters in the following nodes:
- Credentials:
- HubSpot: Connect your account (
HubSpot: Get All Deals). - LLM Model: Add credentials for your preferred provider (
Config: Set LLM for Agent & Chains). - Google Sheets: Connect your account (
Tool: Get Feature Usage from Sheets). - Email: Set up your SMTP credentials (
Email: Send Churn Alert).
- HubSpot: Connect your account (
- Tool URLs:
- In Tool: Calculate Sentiment Score, enter the Webhook URL from the
Trigger: Receive Tickets for Scoringnode within this same workflow. - In Tool: Get HubSpot Data, enter the Endpoint URL for your MCP HubSpot data workflow. (Note: This tool does call an external workflow).
- In Tool: Calculate Sentiment Score, enter the Webhook URL from the
- Google Sheet:
- In Tool: Get Feature Usage from Sheets, enter the Document ID for your own Google Sheet.
- Email Details:
- In Email: Send Churn Alert, change the
FromandToemail addresses.
- In Email: Send Churn Alert, change the
Requirements
- HubSpot account with Deals API access
- LLM provider account (e.g. OpenAI)
- Google Sheets tracking customer feature usage
- n8n with LangChain community nodes enabled
- A separate n8n workflow set up to act as an MCP endpoint for fetching HubSpot data (called by
Tool: Get HubSpot Data).
How to customize it
Tailor this workflow to match your business logic:
- Scoring logic: Adjust the JavaScript in the
Code: Convert Sentiment to Scorenode to redefine how customer scores are calculated. - Alert thresholds: Update the prompt in the
AI Chain: Analyze for Churn Risknode to fine-tune when alerts trigger (e.g. deal age, score cutoff, or usage drop). - Data sources: Swap HubSpot or Google Sheets for your CRM or database of choice — like Salesforce or Airtable.
✅ Outcome: A proactive customer health monitoring system that surfaces risks before it’s too late — keeping your team focused on prevention, not firefighting.
n8n Workflow: AI-Powered Customer Churn Prediction and Analysis
This n8n workflow leverages AI to analyze customer data and predict churn, providing insights and enabling proactive communication. It's designed to be triggered manually or via a webhook, allowing for flexible integration into existing systems.
What it does
This workflow orchestrates several key steps to perform AI-driven analysis:
- Triggers Manually or via Webhook: The workflow can be initiated by a manual execution within n8n or by an incoming webhook, making it adaptable to various data input methods.
- Initial Data Processing (Code): A "Code" node is used to prepare the incoming data for AI analysis. This likely involves formatting, extracting relevant fields, or performing initial transformations.
- AI Agent for Analysis: An "AI Agent" node (LangChain Agent) is employed to perform complex analysis on the prepared data. This agent is configured with an "OpenAI Chat Model" for language understanding and generation, and a "Structured Output Parser" to ensure the AI's response is in a usable, structured format (e.g., JSON).
- Sentiment Analysis: A "Sentiment Analysis" node (LangChain Chain) is used to determine the emotional tone of customer feedback or interactions, providing an additional layer of insight into customer satisfaction.
- Data Transformation (Edit Fields & Split Out): The "Edit Fields (Set)" and "Split Out" nodes are used to refine and structure the AI's output, making it ready for further processing or integration.
- Loop Over Items: The "Loop Over Items (Split in Batches)" node processes the AI's output in batches, allowing for efficient handling of multiple analytical results or customer records.
- Merge Data: A "Merge" node combines different streams of data, likely bringing together the original customer data with the AI's analytical results.
- HubSpot Integration: The workflow interacts with HubSpot, potentially to update customer records with churn predictions, sentiment scores, or other AI-generated insights.
- MCP Client Tool (Model Context Protocol): An "MCP Client Tool" is included, suggesting integration with a Model Context Protocol for managing and interacting with AI models.
- Send Email Notification: An "Send Email" node is used to send notifications, likely to relevant stakeholders with the churn predictions or analytical summaries.
- Markdown Formatting: A "Markdown" node formats data into a readable Markdown string, useful for creating reports or messages.
- Respond to Webhook: If triggered by a webhook, the workflow can send a response back to the originating system, confirming completion or providing results.
Prerequisites/Requirements
To use this workflow, you will need:
- n8n Instance: A running instance of n8n.
- OpenAI API Key: For the "OpenAI Chat Model" node to function.
- HubSpot Account: With appropriate credentials configured in n8n for the "HubSpot" node.
- SMTP Credentials: For the "Send Email" node to send emails.
- Model Context Protocol (MCP) Client: If the "MCP Client Tool" is actively used, access to an MCP server or service.
Setup/Usage
- Import the workflow: Download the provided JSON and import it into your n8n instance.
- Configure Credentials:
- Set up your OpenAI API Key credential.
- Configure your HubSpot credential.
- Set up your SMTP credential for sending emails.
- Configure Webhook (if applicable): If you plan to trigger the workflow via a webhook, copy the webhook URL from the "Webhook" node and configure your external system to send data to it.
- Customize Nodes:
- Review the "Code" node to ensure it correctly processes your input data.
- Adjust the prompts and configurations of the "AI Agent", "OpenAI Chat Model", "Structured Output Parser", and "Sentiment Analysis" nodes to match your specific analytical needs.
- Modify the "Edit Fields (Set)" and "Split Out" nodes to correctly handle and structure the AI's output.
- Configure the "HubSpot" node to perform the desired actions (e.g., update contact properties, create tasks).
- Customize the "Send Email" node with the recipient, subject, and body of the email.
- Adjust the "Markdown" node for your desired output format.
- Test the workflow: Run the workflow manually or trigger it via the webhook to ensure it functions as expected.
Related Templates
Auto-create TikTok videos with VEED.io AI avatars, ElevenLabs & GPT-4
💥 Viral TikTok Video Machine: Auto-Create Videos with Your AI Avatar --- 🎯 Who is this for? This workflow is for content creators, marketers, and agencies who want to use Veed.io’s AI avatar technology to produce short, engaging TikTok videos automatically. It’s ideal for creators who want to appear on camera without recording themselves, and for teams managing multiple brands who need to generate videos at scale. --- ⚙️ What problem this workflow solves Manually creating videos for TikTok can take hours — finding trends, writing scripts, recording, and editing. By combining Veed.io, ElevenLabs, and GPT-4, this workflow transforms a simple Telegram input into a ready-to-post TikTok video featuring your AI avatar powered by Veed.io — speaking naturally with your cloned voice. --- 🚀 What this workflow does This automation links Veed.io’s video-generation API with multiple AI tools: Analyzes TikTok trends via Perplexity AI Writes a 10-second viral script using GPT-4 Generates your voiceover via ElevenLabs Uses Veed.io (Fabric 1.0 via FAL.ai) to animate your avatar and sync the lips to the voice Creates an engaging caption + hashtags for TikTok virality Publishes the video automatically via Blotato TikTok API Logs all results to Google Sheets for tracking --- 🧩 Setup Telegram Bot Create your bot via @BotFather Configure it as the trigger for sending your photo and theme Connect Veed.io Create an account on Veed.io Get your FAL.ai API key (Veed Fabric 1.0 model) Use HTTPS image/audio URLs compatible with Veed Fabric Other APIs Add Perplexity, ElevenLabs, and Blotato TikTok keys Connect your Google Sheet for logging results --- 🛠️ How to customize this workflow Change your Avatar: Upload a new image through Telegram, and Veed.io will generate a new talking version automatically. Modify the Script Style: Adjust the GPT prompt for tone (educational, funny, storytelling). Adjust Voice Tone: Tweak ElevenLabs stability and similarity settings. Expand Platforms: Add Instagram, YouTube Shorts, or X (Twitter) posting nodes. Track Performance: Customize your Google Sheet to measure your most successful Veed.io-based videos. --- 🧠 Expected Outcome In just a few seconds after sending your photo and theme, this workflow — powered by Veed.io — creates a fully automated TikTok video featuring your AI avatar with natural lip-sync and voice. The result is a continuous stream of viral short videos, made without cameras, editing, or effort. --- ✅ Import the JSON file in n8n, add your API keys (including Veed.io via FAL.ai), and start generating viral TikTok videos starring your AI avatar today! 🎥 Watch This Tutorial --- 📄 Documentation: Notion Guide Need help customizing? Contact me for consulting and support : Linkedin / Youtube
Automate Dutch Public Procurement Data Collection with TenderNed
TenderNed Public Procurement What This Workflow Does This workflow automates the collection of public procurement data from TenderNed (the official Dutch tender platform). It: Fetches the latest tender publications from the TenderNed API Retrieves detailed information in both XML and JSON formats for each tender Parses and extracts key information like organization names, titles, descriptions, and reference numbers Filters results based on your custom criteria Stores the data in a database for easy querying and analysis Setup Instructions This template comes with sticky notes providing step-by-step instructions in Dutch and various query options you can customize. Prerequisites TenderNed API Access - Register at TenderNed for API credentials Configuration Steps Set up TenderNed credentials: Add HTTP Basic Auth credentials with your TenderNed API username and password Apply these credentials to the three HTTP Request nodes: "Tenderned Publicaties" "Haal XML Details" "Haal JSON Details" Customize filters: Modify the "Filter op ..." node to match your specific requirements Examples: specific organizations, contract values, regions, etc. How It Works Step 1: Trigger The workflow can be triggered either manually for testing or automatically on a daily schedule. Step 2: Fetch Publications Makes an API call to TenderNed to retrieve a list of recent publications (up to 100 per request). Step 3: Process & Split Extracts the tender array from the response and splits it into individual items for processing. Step 4: Fetch Details For each tender, the workflow makes two parallel API calls: XML endpoint - Retrieves the complete tender documentation in XML format JSON endpoint - Fetches metadata including reference numbers and keywords Step 5: Parse & Merge Parses the XML data and merges it with the JSON metadata and batch information into a single data structure. Step 6: Extract Fields Maps the raw API data to clean, structured fields including: Publication ID and date Organization name Tender title and description Reference numbers (kenmerk, TED number) Step 7: Filter Applies your custom filter criteria to focus on relevant tenders only. Step 8: Store Inserts the processed data into your database for storage and future analysis. Customization Tips Modify API Parameters In the "Tenderned Publicaties" node, you can adjust: offset: Starting position for pagination size: Number of results per request (max 100) Add query parameters for date ranges, status filters, etc. Add More Fields Extend the "Splits Alle Velden" node to extract additional fields from the XML/JSON data, such as: Contract value estimates Deadline dates CPV codes (procurement classification) Contact information Integrate Notifications Add a Slack, Email, or Discord node after the filter to get notified about new matching tenders. Incremental Updates Modify the workflow to only fetch new tenders by: Storing the last execution timestamp Adding date filters to the API query Only processing publications newer than the last run Troubleshooting No data returned? Verify your TenderNed API credentials are correct Check that you have setup youre filter proper Need help setting this up or interested in a complete tender analysis solution? Get in touch 🔗 LinkedIn – Wessel Bulte
Automate invoice processing with OCR, GPT-4 & Salesforce opportunity creation
PDF Invoice Extractor (AI) End-to-end pipeline: Watch Drive ➜ Download PDF ➜ OCR text ➜ AI normalize to JSON ➜ Upsert Buyer (Account) ➜ Create Opportunity ➜ Map Products ➜ Create OLI via Composite API ➜ Archive to OneDrive. --- Node by node (what it does & key setup) 1) Google Drive Trigger Purpose: Fire when a new file appears in a specific Google Drive folder. Key settings: Event: fileCreated Folder ID: google drive folder id Polling: everyMinute Creds: googleDriveOAuth2Api Output: Metadata { id, name, ... } for the new file. --- 2) Download File From Google Purpose: Get the file binary for processing and archiving. Key settings: Operation: download File ID: ={{ $json.id }} Creds: googleDriveOAuth2Api Output: Binary (default key: data) and original metadata. --- 3) Extract from File Purpose: Extract text from PDF (OCR as needed) for AI parsing. Key settings: Operation: pdf OCR: enable for scanned PDFs (in options) Output: JSON with OCR text at {{ $json.text }}. --- 4) Message a model (AI JSON Extractor) Purpose: Convert OCR text into strict normalized JSON array (invoice schema). Key settings: Node: @n8n/n8n-nodes-langchain.openAi Model: gpt-4.1 (or gpt-4.1-mini) Message role: system (the strict prompt; references {{ $json.text }}) jsonOutput: true Creds: openAiApi Output (per item): $.message.content → the parsed JSON (ensure it’s an array). --- 5) Create or update an account (Salesforce) Purpose: Upsert Buyer as Account using an external ID. Key settings: Resource: account Operation: upsert External Id Field: taxid_c External Id Value: ={{ $json.message.content.buyer.tax_id }} Name: ={{ $json.message.content.buyer.name }} Creds: salesforceOAuth2Api Output: Account record (captures Id) for downstream Opportunity. --- 6) Create an opportunity (Salesforce) Purpose: Create Opportunity linked to the Buyer (Account). Key settings: Resource: opportunity Name: ={{ $('Message a model').item.json.message.content.invoice.code }} Close Date: ={{ $('Message a model').item.json.message.content.invoice.issue_date }} Stage: Closed Won Amount: ={{ $('Message a model').item.json.message.content.summary.grand_total }} AccountId: ={{ $json.id }} (from Upsert Account output) Creds: salesforceOAuth2Api Output: Opportunity Id for OLI creation. --- 7) Build SOQL (Code / JS) Purpose: Collect unique product codes from AI JSON and build a SOQL query for PricebookEntry by Pricebook2Id. Key settings: pricebook2Id (hardcoded in script): e.g., 01sxxxxxxxxxxxxxxx Source lines: $('Message a model').first().json.message.content.products Output: { soql, codes } --- 8) Query PricebookEntries (Salesforce) Purpose: Fetch PricebookEntry.Id for each Product2.ProductCode. Key settings: Resource: search Query: ={{ $json.soql }} Creds: salesforceOAuth2Api Output: Items with Id, Product2.ProductCode (used for mapping). --- 9) Code in JavaScript (Build OLI payloads) Purpose: Join lines with PBE results and Opportunity Id ➜ build OpportunityLineItem payloads. Inputs: OpportunityId: ={{ $('Create an opportunity').first().json.id }} Lines: ={{ $('Message a model').first().json.message.content.products }} PBE rows: from previous node items Output: { body: { allOrNone:false, records:[{ OpportunityLineItem... }] } } Notes: Converts discount_total ➜ per-unit if needed (currently commented for standard pricing). Throws on missing PBE mapping or empty lines. --- 10) Create Opportunity Line Items (HTTP Request) Purpose: Bulk create OLIs via Salesforce Composite API. Key settings: Method: POST URL: https://<your-instance>.my.salesforce.com/services/data/v65.0/composite/sobjects Auth: salesforceOAuth2Api (predefined credential) Body (JSON): ={{ $json.body }} Output: Composite API results (per-record statuses). --- 11) Update File to One Drive Purpose: Archive the original PDF in OneDrive. Key settings: Operation: upload File Name: ={{ $json.name }} Parent Folder ID: onedrive folder id Binary Data: true (from the Download node) Creds: microsoftOneDriveOAuth2Api Output: Uploaded file metadata. --- Data flow (wiring) Google Drive Trigger → Download File From Google Download File From Google → Extract from File → Update File to One Drive Extract from File → Message a model Message a model → Create or update an account Create or update an account → Create an opportunity Create an opportunity → Build SOQL Build SOQL → Query PricebookEntries Query PricebookEntries → Code in JavaScript Code in JavaScript → Create Opportunity Line Items --- Quick setup checklist 🔐 Credentials: Connect Google Drive, OneDrive, Salesforce, OpenAI. 📂 IDs: Drive Folder ID (watch) OneDrive Parent Folder ID (archive) Salesforce Pricebook2Id (in the JS SOQL builder) 🧠 AI Prompt: Use the strict system prompt; jsonOutput = true. 🧾 Field mappings: Buyer tax id/name → Account upsert fields Invoice code/date/amount → Opportunity fields Product name must equal your Product2.ProductCode in SF. ✅ Test: Drop a sample PDF → verify: AI returns array JSON only Account/Opportunity created OLI records created PDF archived to OneDrive --- Notes & best practices If PDFs are scans, enable OCR in Extract from File. If AI returns non-JSON, keep “Return only a JSON array” as the last line of the prompt and keep jsonOutput enabled. Consider adding validation on parsing.warnings to gate Salesforce writes. For discounts/taxes in OLI: Standard OLI fields don’t support per-line discount amounts directly; model them in UnitPrice or custom fields. Replace the Composite API URL with your org’s domain or use the Salesforce node’s Bulk Upsert for simplicity.