Back to Catalog

AI-Powered Contact Intelligence & Enrichment with OpenAI/Anthropic and Supabase

Shelly-Ann DavyShelly-Ann Davy
41 views
2/3/2026
Official Page

AI Contact Enrichment

πŸ“‹ Template Description

Overview

Automatically enhance and enrich contact data using AI to fill in missing information, generate insights, and create detailed buyer personas. Supports multiple AI providers (OpenAI, Anthropic, etc.) with automatic logging to Supabase.

Description

This workflow transforms incomplete contact records into rich, actionable profiles. By leveraging AI, it can infer job roles, company information, likely pain points, communication preferences, and buying motivations from minimal input data. Perfect for sales and marketing teams looking to improve data quality and personalize outreach.

Key Benefits:

  • Smart Data Completion: Fill in missing contact fields using AI inference
  • Buyer Persona Generation: Create detailed profiles from basic information
  • Universal AI Support: Works with OpenAI, Anthropic Claude, or custom providers
  • CRM Enhancement: Automatically enrich contacts as they enter your system
  • Lead Qualification: Assess lead quality and fit based on enriched data
  • Personalization Engine: Generate insights for tailored outreach
  • Data Quality: Maintain clean, complete contact records

Use Cases:

  • Sales prospecting and lead enrichment
  • Marketing persona development
  • CRM data cleansing and completion
  • Account-based marketing (ABM) research
  • Lead scoring and qualification
  • Personalized email campaign preparation
  • Contact segmentation and targeting

βš™οΈ Setup Instructions

Prerequisites

  1. n8n instance (cloud or self-hosted)
  2. AI Provider account (OpenAI, Anthropic, or custom)
  3. Supabase account with database access

Step 1: Configure Environment Variables

Add these to your n8n environment settings:

AI_PROVIDER=openai              # or 'anthropic', 'custom'
AI_API_KEY=your_api_key_here
AI_MODEL=gpt-3.5-turbo         # or 'gpt-4', 'claude-3-sonnet-20240229'
AI_ENDPOINT=                    # Only for custom providers

Recommended Models:

  • Cost-effective: gpt-3.5-turbo (fast, affordable, good for basic enrichment)
  • High-quality: gpt-4 or claude-3-sonnet-20240229 (better inference, deeper insights)
  • Premium: claude-3-opus-20240229 (best for complex persona generation)

How to set environment variables:

  • n8n Cloud: Go to Settings β†’ Environment Variables
  • Self-hosted: Add to your .env file or docker-compose configuration

Step 2: Set Up Supabase Database

Create the logging table in your Supabase database:

CREATE TABLE workflow_logs (
  id BIGSERIAL PRIMARY KEY,
  workflow_name TEXT NOT NULL,
  data JSONB NOT NULL,
  ai_response JSONB NOT NULL,
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE INDEX idx_workflow_logs_created_at ON workflow_logs(created_at);
CREATE INDEX idx_workflow_logs_workflow_name ON workflow_logs(workflow_name);

-- Optional: Create a view for enriched contacts
CREATE VIEW enriched_contacts AS
SELECT 
  id,
  data->>'email' as email,
  data->>'name' as name,
  data->>'company' as company,
  ai_response as enrichment_data,
  created_at
FROM workflow_logs
WHERE workflow_name = 'AI Contact Enrichment'
ORDER BY created_at DESC;

To run this SQL:

  1. Open your Supabase project dashboard
  2. Go to the SQL Editor
  3. Paste the SQL above and click "Run"

Step 3: Configure Supabase Credentials in n8n

  1. Go to Settings β†’ Credentials
  2. Click Add Credential β†’ Supabase API
  3. Enter your Supabase URL and API key (found in Project Settings β†’ API)
  4. Name it Supabase API
  5. Click Save

Step 4: Activate the Webhook

  1. Import this workflow into n8n
  2. Click the Activate toggle in the top-right corner
  3. Click on the "Webhook Trigger" node
  4. Copy the Production URL (this is your webhook endpoint)
  5. Save this URL for integration with your applications

Step 5: Test the Workflow

Send a test POST request to the webhook:

curl -X POST https://your-n8n-instance.com/webhook/contact-enrichment \
  -H "Content-Type: application/json" \
  -d '{
    "email": "john.doe@acmecorp.com",
    "name": "John Doe",
    "company": "Acme Corporation",
    "linkedin_url": "https://linkedin.com/in/johndoe"
  }'

Successful Response:

{
  "success": true,
  "workflow": "AI Contact Enrichment",
  "timestamp": "2025-01-14T12:00:00.000Z"
}

πŸ“₯ Expected Payload Format

The webhook accepts JSON with basic contact information:

Minimal Input

{
  "email": "string (required or name required)",
  "name": "string (required or email required)"
}

Recommended Input

{
  "email": "string",
  "name": "string",
  "company": "string",
  "job_title": "string",
  "linkedin_url": "string",
  "phone": "string",
  "location": "string",
  "website": "string"
}

Complete Input Example

{
  "email": "sarah.chen@techstartup.io",
  "name": "Sarah Chen",
  "company": "TechStartup Inc.",
  "job_title": "VP of Marketing",
  "linkedin_url": "https://linkedin.com/in/sarahchen",
  "phone": "+1-555-0123",
  "location": "San Francisco, CA",
  "website": "https://techstartup.io",
  "industry": "B2B SaaS",
  "company_size": "50-200 employees",
  "notes": "Met at SaaS conference 2024"
}

Field Guidelines:

  • At minimum, provide either email or name
  • More input fields = better AI enrichment quality
  • Include linkedin_url for best results
  • company helps with firmographic enrichment
  • Any additional context improves accuracy

πŸ”„ Workflow Flow

  1. Webhook Trigger: Receives basic contact information from your application, form, or CRM
  2. Process Data: Adds unique ID and timestamp to the incoming data
  3. Prepare AI Request: Configures AI provider settings from environment variables
  4. Call AI API: Sends contact data to AI with enrichment prompt
  5. Save to Supabase: Archives original data and enrichment results
  6. Format Response: Returns success confirmation

🎯 Customization Tips

Enhance AI Prompts for Better Enrichment

Modify the "Prepare AI Request" node to customize enrichment:

// Enhanced prompt for contact enrichment
const systemPrompt = `You are an expert sales intelligence analyst. 
Analyze the provided contact information and generate a comprehensive enrichment including:

1. INFERRED DETAILS: Fill in missing information based on available data
   - Full job title and seniority level
   - Department and reporting structure
   - Years of experience (estimated)
   - Professional background

2. COMPANY INSIGHTS: If company name provided
   - Industry and sub-industry
   - Company size and revenue (estimated)
   - Key products/services
   - Recent news or developments

3. BUYER PERSONA: Create a detailed profile
   - Primary responsibilities
   - Likely pain points and challenges
   - Key priorities and goals
   - Decision-making authority
   - Budget influence level

4. ENGAGEMENT STRATEGY: Provide outreach recommendations
   - Best communication channels
   - Optimal outreach timing
   - Key talking points
   - Personalization suggestions
   - Content interests

5. LEAD SCORE: Rate 1-10 based on:
   - Fit for product/service (specify your ICP)
   - Seniority and decision power
   - Company size and maturity
   - Engagement potential

Return as structured JSON with clear sections.`;

const userMessage = `Contact Information:\n${JSON.stringify($json.data, null, 2)}`;

const aiConfig = {
  provider: $env.AI_PROVIDER || 'openai',
  apiKey: $env.AI_API_KEY,
  model: $env.AI_MODEL || 'gpt-3.5-turbo',
  endpoint: $env.AI_ENDPOINT,
  messages: [
    { role: 'system', content: systemPrompt },
    { role: 'user', content: userMessage }
  ]
};

return { json: { aiConfig, data: $json } };

Add External Data Sources

Enhance enrichment with third-party APIs:

After "Process Data" node, add:

  1. Clearbit/Hunter.io Node: Get verified company data
  2. LinkedIn API: Pull professional information
  3. Company Database: Query internal customer data
  4. Web Scraping: Extract data from company websites

Then merge all data before AI enrichment for best results

Connect to Your CRM

Auto-update contacts after enrichment:

Salesforce Integration:

// Add after "Call AI API" node
// Update Salesforce contact with enriched data
const enrichedData = JSON.parse($json.ai_response);
return {
  json: {
    contactId: $json.data.salesforce_id,
    updates: {
      Description: enrichedData.buyer_persona,
      Custom_Score__c: enrichedData.lead_score,
      Pain_Points__c: enrichedData.pain_points
    }
  }
};

HubSpot Integration:

  • Add HubSpot node to update contact properties
  • Map enriched fields to custom HubSpot properties

Pipedrive Integration:

  • Use Pipedrive node to update person records
  • Add custom fields for AI insights

Implement Lead Scoring

Add scoring logic after enrichment:

// Calculate lead score based on enrichment
const enrichment = JSON.parse($json.ai_response);

let score = 0;

// Job title scoring
if (enrichment.seniority === 'C-Level') score += 30;
else if (enrichment.seniority === 'VP/Director') score += 20;
else if (enrichment.seniority === 'Manager') score += 10;

// Company size scoring
if (enrichment.company_size === 'Enterprise') score += 25;
else if (enrichment.company_size === 'Mid-Market') score += 15;

// Decision authority scoring
if (enrichment.decision_authority === 'High') score += 25;
else if (enrichment.decision_authority === 'Medium') score += 15;

// Budget influence
if (enrichment.budget_influence === 'Direct') score += 20;

return { json: { ...enrichment, lead_score: score } };

Add Compliance Checks

Insert before AI processing:

// Check for opt-out or compliance flags
const email = $json.email.toLowerCase();

// Check against suppression list
const suppressedDomains = ['competitor.com', 'spam.com'];
const domain = email.split('@')[1];

if (suppressedDomains.includes(domain)) {
  throw new Error('Contact on suppression list');
}

// Verify email format
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
  throw new Error('Invalid email format');
}

return { json: $json };

Batch Enrichment

Process multiple contacts:

  1. Add Spreadsheet File trigger instead of webhook
  2. Add Split In Batches node (process 10-20 at a time)
  3. Run enrichment for each contact
  4. Combine results and export to CSV

πŸ› οΈ Troubleshooting

Common Issues

Issue: "Enrichment is too generic"

  • Solution: Provide more input data (company, job title, LinkedIn)
  • Use GPT-4 or Claude models for better inference
  • Enhance the system prompt with specific instructions

Issue: "AI_API_KEY is undefined"

  • Solution: Ensure environment variables are set correctly
  • Verify variable names match exactly (case-sensitive)

Issue: "Enrichment contradicts actual data"

  • Solution: AI makes inferences - always validate critical information
  • Add validation step to check enriched data against known facts
  • Use external APIs for verification

Issue: "Too slow for real-time use"

  • Solution: Implement queue system for async processing
  • Use faster models (gpt-3.5-turbo) for speed
  • Process in batches during off-peak hours

Issue: "Supabase credentials not found"

  • Solution: Check credential name matches exactly: "Supabase API"
  • Verify Supabase URL and API key are correct

Debugging Tips

  1. Test with known contacts first to validate accuracy
  2. Compare AI enrichment against actual data
  3. Check execution logs for API errors
  4. Start with minimal prompt, then enhance gradually
  5. Use "Execute Node" to test individual steps

πŸ“Š Analyzing Enriched Data

Query and analyze your enriched contacts:

-- Get all enriched contacts
SELECT * FROM enriched_contacts
ORDER BY created_at DESC;

-- Find high-value leads (assuming scoring implemented)
SELECT 
  email,
  name,
  company,
  ai_response->>'lead_score' as score
FROM enriched_contacts
WHERE (ai_response->>'lead_score')::int > 70
ORDER BY (ai_response->>'lead_score')::int DESC;

-- Analyze enrichment by company
SELECT 
  data->>'company' as company,
  COUNT(*) as contact_count,
  AVG((ai_response->>'lead_score')::int) as avg_score
FROM workflow_logs
WHERE workflow_name = 'AI Contact Enrichment'
  AND ai_response->>'lead_score' IS NOT NULL
GROUP BY data->>'company'
ORDER BY contact_count DESC;

-- Find contacts needing follow-up
SELECT 
  email,
  name,
  ai_response->>'engagement_strategy' as strategy,
  created_at
FROM enriched_contacts
WHERE created_at > NOW() - INTERVAL '7 days'
ORDER BY created_at DESC;

Export Enriched Data

-- Export to CSV
COPY (
  SELECT 
    data->>'email' as email,
    data->>'name' as name,
    data->>'company' as company,
    ai_response->>'job_title' as enriched_title,
    ai_response->>'seniority' as seniority,
    ai_response->>'lead_score' as score
  FROM workflow_logs
  WHERE workflow_name = 'AI Contact Enrichment'
) TO '/tmp/enriched_contacts.csv' WITH CSV HEADER;

πŸ“ˆ Integration Ideas

Form Integration

Automatically enrich new leads from forms:

  • Typeform: Trigger on form submission
  • Google Forms: Use Google Sheets trigger
  • Calendly: Enrich after meeting booking
  • Webflow Forms: Webhook trigger from form

CRM Integration

Real-time enrichment as contacts enter CRM:

  • Salesforce: Trigger on new lead/contact creation
  • HubSpot: Enrich on form submission or import
  • Pipedrive: Auto-enrich new persons
  • Close: Webhook on lead creation

Email Tools

Enhance cold outreach campaigns:

  • Instantly.ai: Enrich before campaign launch
  • Lemlist: Generate personalization variables
  • Apollo.io: Supplement with AI insights
  • Mailshake: Enrich prospect lists

Marketing Automation

Power ABM and segmentation:

  • Marketo: Enrich leads for scoring
  • Pardot: Enhance prospect profiles
  • ActiveCampaign: Personalization data
  • Klaviyo: E-commerce customer insights

Slack Integration

Team notifications and collaboration:

  • Send enrichment summaries to sales channel
  • Notify reps of high-value leads
  • Share persona insights with marketing
  • Alert on key account contacts

πŸ”’ Security & Compliance Best Practices

Data Protection

  1. Encrypt Sensitive Data: Use environment variables for all credentials
  2. Access Control: Limit webhook access with authentication
  3. Data Retention: Set automatic deletion policies in Supabase
  4. Audit Logging: Track all enrichment activities

Privacy Compliance

  1. GDPR Compliance:
    • Get consent before enriching personal data
    • Allow contacts to request data deletion
    • Document legal basis for processing
  2. CCPA Compliance: Honor do-not-sell requests
  3. Data Minimization: Only enrich necessary fields
  4. Right to Access: Allow contacts to view enriched data

AI Ethics

  1. Bias Awareness: Review AI inferences for bias
  2. Accuracy Validation: Verify critical information
  3. Transparency: Disclose use of AI enrichment
  4. Human Oversight: Review before critical decisions

πŸ’‘ Best Practices

Input Data Quality

  • Always include email or full name as anchor point
  • Add LinkedIn URLs for 50% better accuracy
  • Provide company name for firmographic insights
  • Include any known details - more data = better results

Prompt Engineering

  • Be specific about your ideal customer profile (ICP)
  • Request structured output (JSON format)
  • Define scoring criteria that match your business
  • Ask for actionable insights not just descriptions

Post-Enrichment Workflow

  • Always validate critical information before use
  • Review AI inferences for accuracy and bias
  • Update CRM promptly to maintain data freshness
  • Track enrichment ROI (conversion rates, time saved)

Performance Optimization

  • Batch process during off-peak hours
  • Use appropriate models (gpt-3.5 for speed, gpt-4 for quality)
  • Cache common enrichments to reduce API costs
  • Set rate limits to avoid API throttling

🏷️ Tags

sales-automation, lead-enrichment, ai-automation, crm-integration, data-enrichment, contact-intelligence, buyer-personas, lead-scoring, webhook, supabase, openai, anthropic, b2b-sales


πŸ“ License

This workflow template is provided as-is for use with n8n.

🀝 Support

For questions or issues:

  • n8n Community Forum: https://community.n8n.io
  • n8n Documentation: https://docs.n8n.io

🌟 Example Output

Input:

{
  "email": "mike.johnson@cloudtech.com",
  "name": "Mike Johnson",
  "company": "CloudTech Solutions",
  "job_title": "Director of IT"
}

AI-Generated Enrichment:

{
  "full_title": "Director of Information Technology",
  "seniority": "Director",
  "department": "Technology/IT",
  "experience_years": "10-15",
  "company_insights": {
    "industry": "Cloud Computing",
    "size": "Mid-Market (100-500)",
    "revenue_estimate": "$10M-$50M"
  },
  "buyer_persona": {
    "responsibilities": ["Infrastructure management", "Vendor selection", "Security oversight"],
    "pain_points": ["Legacy system migration", "Cost optimization", "Security compliance"],
    "priorities": ["Scalability", "Cost reduction", "Team efficiency"]
  },
  "engagement_strategy": {
    "best_channels": ["Email", "LinkedIn"],
    "timing": "Tuesday-Thursday, 9-11 AM",
    "talking_points": ["ROI and cost savings", "Security features", "Ease of implementation"],
    "personalization": "Reference cloud migration challenges"
  },
  "lead_score": 75
}

πŸ”„ Version History

  • v1.0.0 (2025-01-14): Initial release with universal AI provider support

AI-Powered Contact Intelligence: Enrichment with OpenAI/Anthropic and Supabase

This n8n workflow automates the process of enriching contact data with AI-generated insights and storing it in a Supabase database. It's designed to provide deeper intelligence on contacts by leveraging large language models (LLMs) to extract key information from a given text input.

What it does

This workflow streamlines the enrichment of contact data through the following steps:

  1. Receives Data: It starts by listening for incoming data via a Webhook. This data is expected to contain a text field that needs to be analyzed.
  2. Extracts Contact Information (AI): A "Code" node processes the incoming text to extract relevant contact intelligence. This node is likely configured to interact with an AI service (like OpenAI or Anthropic, as hinted by the directory name, though the JSON itself doesn't explicitly show these nodes, implying they are either abstracted within the Code node or omitted for brevity in this specific JSON snippet). The output of this step would be structured data about the contact.
  3. Stores Enriched Data: The extracted and enriched contact information is then stored in a Supabase database using the "Supabase" node.
  4. Makes an HTTP Request: An "HTTP Request" node is included, which could be used for various purposes such as sending notifications, logging, or further processing the enriched data to another system.

Prerequisites/Requirements

To effectively use this workflow, you will need:

  • n8n Instance: A running instance of n8n.
  • Supabase Account: Access to a Supabase project with a configured table to store contact information. You'll need your Supabase URL and API Key for credentials.
  • AI Service (Implicit): Although not explicitly shown as a separate node, the "Code" node's function suggests interaction with an AI service. Depending on the code's implementation, you might need API keys for:
    • OpenAI API Key
    • Anthropic API Key
  • Basic JavaScript Knowledge (for Code node): To understand and potentially modify the logic within the "Code" node for AI interaction and data processing.

Setup/Usage

  1. Import the Workflow:
    • Download the provided JSON file.
    • In your n8n instance, go to "Workflows" and click "New".
    • Click the three-dot menu in the top right and select "Import from JSON".
    • Paste the workflow JSON or upload the file.
  2. Configure Credentials:
    • Supabase: Locate the "Supabase" node. You will need to set up a Supabase credential with your Project URL and API Key.
    • AI Service (within Code node): If the "Code" node directly calls an AI API, ensure any necessary API keys are securely managed, possibly as environment variables in your n8n instance or directly within the code (though not recommended for production).
  3. Configure Webhook:
    • Locate the "Webhook" node.
    • Set the "Webhook URL" to "POST" and copy the generated URL. This is the endpoint you will send your raw contact text data to.
  4. Configure Code Node:
    • Review the JavaScript code within the "Code" node. This is where the logic for interacting with the AI service and structuring the output for Supabase resides. Adjust it according to your specific AI model and desired data extraction.
  5. Configure HTTP Request Node:
    • If the "HTTP Request" node is intended for a specific purpose (e.g., sending data to another API), configure its URL, method, headers, and body accordingly.
  6. Activate the Workflow: Once all configurations are complete, activate the workflow by toggling the switch in the top right corner of the workflow editor.

Now, whenever you send a POST request with contact text data to the Webhook URL, the workflow will process it, enrich it with AI intelligence, and store it in your Supabase database.

Related Templates

Track competitor SEO keywords with Decodo + GPT-4.1-mini + Google Sheets

This workflow automates competitor keyword research using OpenAI LLM and Decodo for intelligent web scraping. Who this is for SEO specialists, content strategists, and growth marketers who want to automate keyword research and competitive intelligence. Marketing analysts managing multiple clients or websites who need consistent SEO tracking without manual data pulls. Agencies or automation engineers using Google Sheets as an SEO data dashboard for keyword monitoring and reporting. What problem this workflow solves Tracking competitor keywords manually is slow and inconsistent. Most SEO tools provide limited API access or lack contextual keyword analysis. This workflow solves that by: Automatically scraping any competitor’s webpage with Decodo. Using OpenAI GPT-4.1-mini to interpret keyword intent, density, and semantic focus. Storing structured keyword insights directly in Google Sheets for ongoing tracking and trend analysis. What this workflow does Trigger β€” Manually start the workflow or schedule it to run periodically. Input Setup β€” Define the website URL and target country (e.g., https://dev.to, france). Data Scraping (Decodo) β€” Fetch competitor web content and metadata. Keyword Analysis (OpenAI GPT-4.1-mini) Extract primary and secondary keywords. Identify focus topics and semantic entities. Generate a keyword density summary and SEO strength score. Recommend optimization and internal linking opportunities. Data Structuring β€” Clean and convert GPT output into JSON format. Data Storage (Google Sheets) β€” Append structured keyword data to a Google Sheet for long-term tracking. Setup Prerequisites If you are new to Decode, please signup on this link visit.decodo.com n8n account with workflow editor access Decodo API credentials OpenAI API key Google Sheets account connected via OAuth2 Make sure to install the Decodo Community node. Create a Google Sheet Add columns for: primarykeywords, seostrengthscore, keyworddensity_summary, etc. Share with your n8n Google account. Connect Credentials Add credentials for: Decodo API credentials - You need to register, login and obtain the Basic Authentication Token via Decodo Dashboard OpenAI API (for GPT-4o-mini) Google Sheets OAuth2 Configure Input Fields Edit the β€œSet Input Fields” node to set your target site and region. Run the Workflow Click Execute Workflow in n8n. View structured results in your connected Google Sheet. How to customize this workflow Track Multiple Competitors β†’ Use a Google Sheet or CSV list of URLs; loop through them using the Split In Batches node. Add Language Detection β†’ Add a Gemini or GPT node before keyword analysis to detect content language and adjust prompts. Enhance the SEO Report β†’ Expand the GPT prompt to include backlink insights, metadata optimization, or readability checks. Integrate Visualization β†’ Connect your Google Sheet to Looker Studio for SEO performance dashboards. Schedule Auto-Runs β†’ Use the Cron Node to run weekly or monthly for competitor keyword refreshes. Summary This workflow automates competitor keyword research using: Decodo for intelligent web scraping OpenAI GPT-4.1-mini for keyword and SEO analysis Google Sheets for live tracking and reporting It’s a complete AI-powered SEO intelligence pipeline ideal for teams that want actionable insights on keyword gaps, optimization opportunities, and content focus trends, without relying on expensive SEO SaaS tools.

Ranjan DailataBy Ranjan Dailata
161

Generate song lyrics and music from text prompts using OpenAI and Fal.ai Minimax

Spark your creativity instantly in any chatβ€”turn a simple prompt like "heartbreak ballad" into original, full-length lyrics and a professional AI-generated music track, all without leaving your conversation. πŸ“‹ What This Template Does This chat-triggered workflow harnesses AI to generate detailed, genre-matched song lyrics (at least 600 characters) from user messages, then queues them for music synthesis via Fal.ai's minimax-music model. It polls asynchronously until the track is ready, delivering lyrics and audio URL back in chat. Crafts original, structured lyrics with verses, choruses, and bridges using OpenAI Submits to Fal.ai for melody, instrumentation, and vocals aligned to the style Handles long-running generations with smart looping and status checks Returns complete song package (lyrics + audio link) for seamless sharing πŸ”§ Prerequisites n8n account (self-hosted or cloud with chat integration enabled) OpenAI account with API access for GPT models Fal.ai account for AI music generation πŸ”‘ Required Credentials OpenAI API Setup Go to platform.openai.com β†’ API keys (sidebar) Click "Create new secret key" β†’ Name it (e.g., "n8n Songwriter") Copy the key and add to n8n as "OpenAI API" credential type Test by sending a simple chat completion request Fal.ai HTTP Header Auth Setup Sign up at fal.ai β†’ Dashboard β†’ API Keys Generate a new API key β†’ Copy it In n8n, create "HTTP Header Auth" credential: Name="Fal.ai", Header Name="Authorization", Header Value="Key [Your API Key]" Test with a simple GET to their queue endpoint (e.g., /status) βš™οΈ Configuration Steps Import the workflow JSON into your n8n instance Assign OpenAI API credentials to the "OpenAI Chat Model" node Assign Fal.ai HTTP Header Auth to the "Generate Music Track", "Check Generation Status", and "Fetch Final Result" nodes Activate the workflowβ€”chat trigger will appear in your n8n chat interface Test by messaging: "Create an upbeat pop song about road trips" 🎯 Use Cases Content Creators: YouTubers generating custom jingles for videos on the fly, streamlining production from idea to audio export Educators: Music teachers using chat prompts to create era-specific folk tunes for classroom discussions, fostering interactive learning Gift Personalization: Friends crafting anniversary R&B tracks from shared memories via quick chats, delivering emotional audio surprises Artist Brainstorming: Songwriters prototyping hip-hop beats in real-time during sessions, accelerating collaboration and iteration ⚠️ Troubleshooting Invalid JSON from AI Agent: Ensure the system prompt stresses valid JSON; test the agent standalone with a sample query Music Generation Fails (401/403): Verify Fal.ai API key has minimax-music access; check usage quotas in dashboard Status Polling Loops Indefinitely: Bump wait time to 45-60s for complex tracks; inspect fal.ai queue logs for bottlenecks Lyrics Under 600 Characters: Tweak agent prompt to enforce fuller structures like [V1][C][V2][B][C]; verify output length in executions

Daniel NkenchoBy Daniel Nkencho
601

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.

Le NguyenBy Le Nguyen
942