# templates

name: Evaluation metric example: RAG document relevance
author_name: David Roberts
author_username: davidn8n
categories: []
created_at: 2025-05-21T08:19:43.930Z
updated_at: 2025-05-21T08:19:43.930Z
url: https://n8n.io/workflows/4273
scraped_at: 2025-06-19 22:50:05
description:
  AI evaluation in n8n

  This is a template for n8n's evaluation feature. 

  Evaluation is a technique for getting confidence that your AI workflow performs reliably, by running a test dataset containing different inputs through the workflow.

  By calculating a metric (score) for each input, you can see where the workflow is performing well and where it isn't.

  How it works

  This template shows how to calculate a workflow evaluation metric: retrieved document relevance (i.e. whether the information retrieved from a vector store is relevant to the question).

  The workflow takes a question and checks whether the information retrieved to answer it is relevant.

  To run this workflow, you need to insert documents into a vector data store, so that they can be retrieved by the agent to answer questions. You can do this by running the top part of the workflow once.

  The main workflow works as follows:

  We use an evaluation trigger to read in our dataset 
  It is wired up in parallel with the regular trigger so that the workflow can be started from either one. More info
  We make sure that the agent outputs the list data from the tools that it used
  If we’re evaluating (i.e. the execution started from the evaluation trigger), we calculate the relevance metric using AI to compare the retrieved documents with the question
  We pass this information back to n8n as a metric
  If we’re not evaluating we avoid calculating the metric, to reduce cost

nodes_used:
  ["n8n-nodes-base.googleSheets","@n8n/n8n-nodes-langchain.agent","@n8n/n8n-nodes-langchain.embeddingsOpenAi","@n8n/n8n-nodes-langchain.lmChatOpenAi","@n8n/n8n-nodes-langchain.textSplitterRecursiveCharacterTextSplitter","@n8n/n8n-nodes-langchain.vectorStoreInMemory","@n8n/n8n-nodes-langchain.documentDefaultDataLoader","@n8n/n8n-nodes-langchain.openAi","n8n-nodes-base.evaluation"]

workflow_json:
  {"meta":{"instanceId":"bf40384a063e00f3b983f4f9bada22b57a8231a04c0fb48d363e26d7b0f2b7e7","templateCredsSetupCompleted":true},"nodes":[{"id":"86d6a658-f056-4434-9720-dfd3ca514cb3","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[420,20],"parameters":{"color":7,"width":300,"height":180,"content":"Check whether the documents returned a relevant to the question"},"typeVersion":1},{"id":"90aac144-164f-4961-89f8-4b8402177202","name":"Sticky Note3","type":"n8n-nodes-base.stickyNote","position":[-1220,-40],"parameters":{"width":200,"height":500,"content":"## How it works\nThis template shows how to calculate a workflow evaluation metric: **retrieved document relevance** (i.e. whether the information retrieved from the vector store is relevant to the question).\n\nThe workflow takes a question and checks whether the information retrieved to answer it is relevant.\n\nYou can find more information on workflow evaluation [here](https://docs.n8n.io/advanced-ai/evaluations/overview), and other metric examples [here](https://docs.n8n.io/advanced-ai/evaluations/metric-based-evaluations/#2-calculate-metrics)."},"typeVersion":1},{"id":"f3970d8c-b205-4348-b375-d919d2f56f94","name":"Sticky Note4","type":"n8n-nodes-base.stickyNote","position":[-960,280],"parameters":{"color":7,"width":220,"height":220,"content":"Read in [this test dataset](https://docs.google.com/spreadsheets/d/1uuPS5cHtSNZ6HNLOi75A2m8nVWZrdBZ_Ivf58osDAS8/edit?gid=630157309#gid=630157309) of questions"},"typeVersion":1},{"id":"677b90c8-aa6f-4cc5-88df-d8e635b0bde2","name":"When fetching a dataset row","type":"n8n-nodes-base.evaluationTrigger","position":[-900,340],"parameters":{"sheetName":{"__rl":true,"mode":"url","value":"https://docs.google.com/spreadsheets/d/1uuPS5cHtSNZ6HNLOi75A2m8nVWZrdBZ_Ivf58osDAS8/edit?gid=630157309#gid=630157309"},"documentId":{"__rl":true,"mode":"url","value":"https://docs.google.com/spreadsheets/d/1uuPS5cHtSNZ6HNLOi75A2m8nVWZrdBZ_Ivf58osDAS8/edit?gid=630157309#gid=630157309"}},"credentials":{"googleSheetsOAuth2Api":{"id":"bpr2LoSELMlxpwnN","name":"Google Sheets account David"}},"typeVersion":4.6},{"id":"c381a3c3-12b6-44fe-a2ed-6adf6f997534","name":"Evaluating?","type":"n8n-nodes-base.evaluation","position":[-60,200],"parameters":{"operation":"checkIfEvaluating"},"typeVersion":4.6},{"id":"e1cf0122-c668-41d2-9316-a173d425d897","name":"When chat message received","type":"@n8n/n8n-nodes-langchain.chatTrigger","position":[-900,100],"webhookId":"d53bc846-db11-446c-8436-9d25dc265663","parameters":{"options":{}},"typeVersion":1.1},{"id":"b521aa40-c8da-4485-b834-50a129c27d3c","name":"Match chat format","type":"n8n-nodes-base.set","position":[-680,340],"parameters":{"options":{},"assignments":{"assignments":[{"id":"93f89095-7918-45ad-aa74-a0bbcf0d5788","name":"chatInput","type":"string","value":"={{ $json.question }}"}]}},"typeVersion":3.4},{"id":"d0170cbd-ba01-45db-a405-aec943bf1608","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[-80,100],"parameters":{"color":7,"width":150,"height":260,"content":"Only calculate metrics if we're evaluating, to reduce costs"},"typeVersion":1},{"id":"a21f98f0-25eb-44cc-a04a-33181d7e5288","name":"Return chat response","type":"n8n-nodes-base.noOp","position":[220,340],"parameters":{},"typeVersion":1},{"id":"fd8628a1-9f31-4f42-88df-b87eda7216ee","name":"Set metrics","type":"n8n-nodes-base.evaluation","position":[820,80],"parameters":{"metrics":{"assignments":[{"id":"230589eb-34c8-4d10-9296-4a78d673077a","name":"similarity","type":"number","value":"={{ $json.message.content.score }}"}]},"operation":"setMetrics"},"typeVersion":4.6},{"id":"eefe3a5a-722a-4cce-b84b-65c0520a225f","name":"Get dataset","type":"n8n-nodes-base.googleSheets","position":[-680,-620],"parameters":{"options":{},"sheetName":{"__rl":true,"mode":"url","value":"https://docs.google.com/spreadsheets/d/1uuPS5cHtSNZ6HNLOi75A2m8nVWZrdBZ_Ivf58osDAS8/edit?gid=630157309#gid=630157309"},"documentId":{"__rl":true,"mode":"url","value":"https://docs.google.com/spreadsheets/d/1uuPS5cHtSNZ6HNLOi75A2m8nVWZrdBZ_Ivf58osDAS8/edit?gid=630157309#gid=630157309"}},"credentials":{"googleSheetsOAuth2Api":{"id":"bpr2LoSELMlxpwnN","name":"Google Sheets account David"}},"typeVersion":4.5},{"id":"ea83d68c-f499-4864-918c-5ccaccf555a5","name":"Remove Duplicates","type":"n8n-nodes-base.removeDuplicates","position":[-460,-620],"parameters":{"compare":"selectedFields","options":{},"fieldsToCompare":"document_id"},"typeVersion":2},{"id":"6bf59dc8-fe59-49cf-971f-e22dac5d0500","name":"Simple Vector Store","type":"@n8n/n8n-nodes-langchain.vectorStoreInMemory","position":[-240,-620],"parameters":{"mode":"insert","memoryKey":"rag_evaluation_demo","clearStore":true},"typeVersion":1.1},{"id":"66dd59b0-b2e4-43c9-b1f5-7f5a65568f5e","name":"Embeddings OpenAI","type":"@n8n/n8n-nodes-langchain.embeddingsOpenAi","position":[-300,-400],"parameters":{"options":{}},"credentials":{"openAiApi":{"id":"Ag9qPAsY7lpIGkvC","name":"JPs n8n openAI key"}},"typeVersion":1.2},{"id":"213b230d-0f40-4e71-b0bf-4783274e2cdb","name":"Default Data Loader","type":"@n8n/n8n-nodes-langchain.documentDefaultDataLoader","position":[-100,-380],"parameters":{"options":{},"jsonData":"={{ $json.document_text }}","jsonMode":"expressionData"},"typeVersion":1},{"id":"64ec7e8c-63f9-4198-9e8d-61345c564c13","name":"Recursive Character Text Splitter","type":"@n8n/n8n-nodes-langchain.textSplitterRecursiveCharacterTextSplitter","position":[-20,-220],"parameters":{"options":{}},"typeVersion":1},{"id":"c561f2ce-ef05-4f42-9b6e-6fabd12d6d23","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[-980,-700],"parameters":{"color":7,"width":1180,"height":620,"content":"### Setup: Populate vector DB\nRun this once before running the main workflow. It inserts the documents from the dataset in the vector store, so they can be queried by the agent below"},"typeVersion":1},{"id":"4a7de6bd-17ac-40df-9b27-2d8f6fdbeb07","name":"When clicking ‘Execute workflow’","type":"n8n-nodes-base.manualTrigger","position":[-900,-620],"parameters":{},"typeVersion":1},{"id":"a0f6211f-6202-462c-8fa3-52e10ad89b5d","name":"Calculate doc relevance metric","type":"@n8n/n8n-nodes-langchain.openAi","position":[440,80],"parameters":{"modelId":{"__rl":true,"mode":"list","value":"gpt-4o-mini","cachedResultName":"GPT-4O-MINI"},"options":{},"messages":{"values":[{"role":"system","content":"=You are a teacher evaluating the relevance of student responses to questions.\n\nYou will be given a QUESTION and one or more FACTS provided by a student. Your task is to determine whether these FACTS are relevant to answering the QUESTION.\n\nGrading criteria:\n(1) Evaluate whether the provided FACTS contain information that is relevant to answering the QUESTION\n(2) A FACT is relevant if it contains keywords or concepts semantically related to the QUESTION\n(3) A FACT is relevant if it provides context, examples, or explanations that address any aspect of the QUESTION\n(4) A FACT may contain some unrelated information and still be considered relevant if it also contains information that satisfies criteria (2) or (3)\n\nScoring:\n- Score 1: At least one of the provided FACTS is relevant to the QUESTION\n- Score 0: All provided FACTS are completely unrelated to the QUESTION\n\nEvaluation process:\n1. Identify the key concepts and requirements in the QUESTION\n2. Examine each provided FACT for keywords or concepts related to these key elements\n3. Consider semantic relationships, not just exact keyword matches\n4. Determine if any FACT contributes useful information toward answering the QUESTION\n5. Provide your reasoning in a detailed, step-by-step manner first\n6. Then create a one-sentence summary of your reasoning\n7. Avoid stating your conclusion at the beginning of your extended reasoning\n\nOutput format:\n{\n  \"extended_reasoning\": \"<detailed step-by-step analysis of how you evaluated the relevance>\",\n  \"reasoning_summary\": \"<one sentence summary of your conclusion>\",\n  \"score\": <number: either 0 or 1>\n}\n\nExamples:\n\nQUESTION: \"What factors contributed to the fall of the Roman Empire?\"\nFACTS: \"The Roman Empire fell due to economic problems, military failures, and political corruption. Germanic tribes invaded from the north while the empire was weakened.\"\nEVALUATION: This would receive a score of 1 because the facts directly address causes of the Roman Empire's fall.\n\nQUESTION: \"What factors contributed to the fall of the Roman Empire?\"\nFACTS: \"The Pythagorean theorem states that a² + b² = c² in a right triangle. Jupiter is the largest planet in our solar system.\"\nEVALUATION: This would receive a score of 0 because neither fact relates to the Roman Empire or its fall."},{"content":"=QUESTION: {{ $('When fetching a dataset row').item.json.question }}\n\nFACTS: \n{{ $json.documents }}"}]},"jsonOutput":true},"credentials":{"openAiApi":{"id":"Ag9qPAsY7lpIGkvC","name":"JPs n8n openAI key"}},"typeVersion":1.8},{"id":"b01d3427-4907-4715-8c15-669500012f89","name":"AI Agent","type":"@n8n/n8n-nodes-langchain.agent","position":[-420,200],"parameters":{"options":{"systemMessage":"You are a helpful assistant. Answer the user's questions using information from your vector knowledge base only.","returnIntermediateSteps":true}},"typeVersion":1.9},{"id":"97e2db38-0114-449f-bb41-0ab490fc7327","name":"OpenAI Chat Model","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[-480,440],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o-mini"},"options":{}},"credentials":{"openAiApi":{"id":"Ag9qPAsY7lpIGkvC","name":"JPs n8n openAI key"}},"typeVersion":1.2},{"id":"5b3679ab-b0a6-4461-9276-89eddb16f699","name":"Extract documents","type":"n8n-nodes-base.set","position":[220,80],"parameters":{"options":{},"assignments":{"assignments":[{"id":"2d771c52-6637-4af0-9ff7-c87368041bfd","name":"documents","type":"string","value":"={{ $json.intermediateSteps.filter(x => x.action.tool == 'vector_knowledge_base')[0].observation }}"}]}},"typeVersion":3.4},{"id":"0e4c4512-7b9f-4881-8ac7-4c7c24a4a446","name":"Simple Vector Store1","type":"@n8n/n8n-nodes-langchain.vectorStoreInMemory","position":[-260,440],"parameters":{"mode":"retrieve-as-tool","toolName":"vector_knowledge_base","memoryKey":"rag_evaluation_demo","toolDescription":"Source of all knowledge to work with"},"typeVersion":1.1},{"id":"edde6c75-dea5-46cc-937e-68e4a925559b","name":"Embeddings OpenAI1","type":"@n8n/n8n-nodes-langchain.embeddingsOpenAi","position":[-220,620],"parameters":{"options":{}},"credentials":{"openAiApi":{"id":"Ag9qPAsY7lpIGkvC","name":"JPs n8n openAI key"}},"typeVersion":1.2},{"id":"e23289e7-a769-4aae-82e6-b7f9e6d903f0","name":"Sticky Note6","type":"n8n-nodes-base.stickyNote","position":[-980,-40],"parameters":{"color":7,"width":2000,"height":820,"content":"### Main workflow"},"typeVersion":1},{"id":"c90baefc-22bd-4782-a8eb-236bfb1d2751","name":"Sticky Note5","type":"n8n-nodes-base.stickyNote","position":[-440,120],"parameters":{"color":7,"width":300,"height":200,"content":"Make sure to enable 'Return intermediate steps' in the agent, to get the list of executed tools"},"typeVersion":1}],"pinData":{},"connections":{"AI Agent":{"main":[[{"node":"Evaluating?","type":"main","index":0}]]},"Evaluating?":{"main":[[{"node":"Extract documents","type":"main","index":0}],[{"node":"Return chat response","type":"main","index":0}]]},"Get dataset":{"main":[[{"node":"Remove Duplicates","type":"main","index":0}]]},"Embeddings OpenAI":{"ai_embedding":[[{"node":"Simple Vector Store","type":"ai_embedding","index":0}]]},"Extract documents":{"main":[[{"node":"Calculate doc relevance metric","type":"main","index":0}]]},"Match chat format":{"main":[[{"node":"AI Agent","type":"main","index":0}]]},"OpenAI Chat Model":{"ai_languageModel":[[{"node":"AI Agent","type":"ai_languageModel","index":0}]]},"Remove Duplicates":{"main":[[{"node":"Simple Vector Store","type":"main","index":0}]]},"Embeddings OpenAI1":{"ai_embedding":[[{"node":"Simple Vector Store1","type":"ai_embedding","index":0}]]},"Default Data Loader":{"ai_document":[[{"node":"Simple Vector Store","type":"ai_document","index":0}]]},"Simple Vector Store1":{"ai_tool":[[{"node":"AI Agent","type":"ai_tool","index":0}]]},"When chat message received":{"main":[[{"node":"AI Agent","type":"main","index":0}]]},"When fetching a dataset row":{"main":[[{"node":"Match chat format","type":"main","index":0}]]},"Calculate doc relevance metric":{"main":[[{"node":"Set metrics","type":"main","index":0}]]},"Recursive Character Text Splitter":{"ai_textSplitter":[[{"node":"Default Data Loader","type":"ai_textSplitter","index":0}]]},"When clicking ‘Execute workflow’":{"main":[[{"node":"Get dataset","type":"main","index":0}]]}}}


name: Convert boring images to stunning photos and videos
author_name: Rish
author_username: b2brish
nodes_used: ["n8n-nodes-base.httpRequest","n8n-nodes-base.telegram"]
categories: []
created_at: 2025-05-21T08:28:17.337Z
updated_at: 2025-05-21T08:28:17.337Z
url: https://n8n.io/workflows/4275
scraped_at: 2025-06-19 22:49:05
description:
  AI Image Editor with Telegram Bot



  Tutorial Video:
  https://www.youtube.com/watch?v=imi7xKQvKh8

  ✨ Transform ordinary photos into AI masterpieces
  This powerful workflow creates a complete AI image editing system that your Telegram contacts can use with a simple message. Let users send images with creative instructions and watch as cutting-edge AI transforms their ideas into reality.

  🤖 What This Workflow Does
  Connect your Telegram bot to OpenAI and Replicate's advanced image models to:

  Edit photos based on text descriptions
  Generate creative variations of original images
  Deliver professional-quality results in seconds
  Handle the entire process automatically

  🎨 Perfect For

  Digital creators seeking quick design iterations
  Photography enthusiasts wanting AI enhancements
  Product marketers creating concept visualizations
  Community managers offering image editing services
  Anyone looking to explore AI image capabilities

  🔧 Easy Setup
  Just configure your API credentials, customize a few prompts, and your Telegram bot becomes a powerful AI image editor. The workflow handles all the technical complexity including file conversions, API communications, and asynchronous processing.

  💡 Expandable Design
  Built with flexibility in mind, you can easily:

  Add additional AI models
  Implement image moderation
  Create branching paths based on user requests
  Integrate with other services like cloud storage

  Elevate your image editing capabilities with this seamless blend of messaging and AI technology!

workflow_json:
  {"meta":{"instanceId":"e5aa7986ab694604988fd614f16d3dd8cb275c306d75d6a818e14c909713473c"},"nodes":[{"id":"0db7b2f0-dfb2-4c92-98c8-d5eb27ca54f3","name":"Telegram Bot Trigger","type":"n8n-nodes-base.telegramTrigger","position":[-280,380],"webhookId":"ab3c5adb-2300-4fcc-9d5c-7402e7456415","parameters":{},"description":"Listens for incoming messages with images from a Telegram bot","typeVersion":1.2},{"id":"434d739e-54d7-4f75-955f-e1181ff23db8","name":"Workflow Start Documentation","type":"n8n-nodes-base.stickyNote","position":[-380,-20],"parameters":{"content":""},"typeVersion":1},{"id":"dc5ddb08-76b8-4a1f-a2fb-315c64199157","name":"Workflow Overview","type":"n8n-nodes-base.stickyNote","position":[-1000,-220],"parameters":{"content":""},"typeVersion":1},{"id":"b4682f5b-4c6e-4ba0-a40b-c2851c64bfef","name":"OpenAI API Documentation","type":"n8n-nodes-base.stickyNote","position":[60,-240],"parameters":{"content":""},"typeVersion":1},{"id":"a7266711-bee5-40a2-afc2-86affd226abc","name":"Conversion Documentation","type":"n8n-nodes-base.stickyNote","position":[460,-120],"parameters":{"content":""},"typeVersion":1},{"id":"f651bd6f-dc2f-4d60-b896-2c860ef0673f","name":"Edit Image (OpenAI)","type":"n8n-nodes-base.httpRequest","position":[160,280],"parameters":{},"description":"Sends image to OpenAI for AI-powered editing based on the caption","typeVersion":4.2},{"id":"8e50ff8a-6c4b-486e-9307-9624fc7ff274","name":"Convert to Binary Image","type":"n8n-nodes-base.convertToFile","position":[580,280],"parameters":{},"description":"Converts base64 encoded image to binary format for sending","typeVersion":1.1},{"id":"e8096804-b5a7-4f2f-943b-e4a5db0929fb","name":"Send Edited Image","type":"n8n-nodes-base.telegram","position":[880,740],"webhookId":"6d8b80b6-8450-49c9-98dc-0f34e14da588","parameters":{},"description":"Sends the edited image back to the user via Telegram","typeVersion":1.2},{"id":"d33a7637-4046-40a9-90e6-6d8b8fc2f4b6","name":"Replicate Documentation","type":"n8n-nodes-base.stickyNote","position":[1460,120],"parameters":{"content":""},"typeVersion":1},{"id":"d0894342-ab6a-473c-9ad0-667987801a9f","name":"Wait Node Documentation","type":"n8n-nodes-base.stickyNote","position":[2000,180],"parameters":{"content":""},"typeVersion":1},{"id":"5f0417a3-7682-481c-b642-c2b45142839e","name":"File Retrieval Documentation","type":"n8n-nodes-base.stickyNote","position":[1100,-40],"parameters":{"content":""},"typeVersion":1},{"id":"906ba4d2-445c-477f-8732-be7e9d828ba0","name":"Generate Variation (Replicate)","type":"n8n-nodes-base.httpRequest","position":[1620,640],"parameters":{},"description":"Sends the original image to Replicate for AI-powered variation","typeVersion":4.2},{"id":"ab244f36-31e3-4dea-9c8e-e4935335810a","name":"Retrieve Generated Image","type":"n8n-nodes-base.httpRequest","position":[2540,840],"parameters":{},"description":"Gets the final generated image from Replicate after processing","typeVersion":4.2},{"id":"fee42f2b-09d2-47f9-842a-52139e8c8de6","name":"Send Variation Image","type":"n8n-nodes-base.telegram","position":[2740,280],"webhookId":"c2af49c2-2c87-4020-928a-ce18f14e557f","parameters":{},"description":"Sends the AI-generated variation back to the user","typeVersion":1.2},{"id":"93c43617-3c40-451f-b3b5-eb1d276db1ba","name":"Get File Path","type":"n8n-nodes-base.httpRequest","position":[1220,340],"parameters":{},"description":"Retrieves the file path from Telegram's servers","typeVersion":4.2},{"id":"71391d58-693a-4c6e-9180-a7b5819bdd3f","name":"Wait for Processing","type":"n8n-nodes-base.wait","position":[2080,600],"webhookId":"eb746bd1-bead-4d9c-b5d5-6c1a1b605c20","parameters":{},"description":"Waits for Replicate to complete the image generation (45 seconds)","typeVersion":1.1},{"id":"736f5bc9-3785-486d-a93a-d6e9cbd5e45b","name":"Setup Documentation","type":"n8n-nodes-base.stickyNote","position":[-1000,380],"parameters":{"content":""},"typeVersion":1},{"id":"2873e80c-d160-4bbc-88e7-89097adaa0bd","name":"Note: Send Replicate Output","type":"n8n-nodes-base.stickyNote","position":[2640,20],"parameters":{"content":""},"typeVersion":1},{"id":"65e13c0b-cf11-4c15-8de4-a6633e621a43","name":"Note: Get Replicate Result","type":"n8n-nodes-base.stickyNote","position":[2420,580],"parameters":{"content":""},"typeVersion":1},{"id":"d6f4bd9c-6016-45a1-9318-c37aa5786e34","name":"Note: Send Edited Image","type":"n8n-nodes-base.stickyNote","position":[800,500],"parameters":{"content":""},"typeVersion":1}],"pinData":{},"connections":{"Get File Path":{"main":[[{"node":"Generate Variation (Replicate)","type":"main","index":0}]]},"Send Edited Image":{"main":[[{"node":"Get File Path","type":"main","index":0}]]},"Edit Image (OpenAI)":{"main":[[{"node":"Convert to Binary Image","type":"main","index":0}]]},"Wait for Processing":{"main":[[{"node":"Retrieve Generated Image","type":"main","index":0}]]},"Telegram Bot Trigger":{"main":[[{"node":"Edit Image (OpenAI)","type":"main","index":0}]]},"Convert to Binary Image":{"main":[[{"node":"Send Edited Image","type":"main","index":0}]]},"Retrieve Generated Image":{"main":[[{"node":"Send Variation Image","type":"main","index":0}]]},"Generate Variation (Replicate)":{"main":[[{"node":"Wait for Processing","type":"main","index":0}]]}}}


name: Real Estate Intelligence Tracker with Bright Data & OpenAI
author_name: Ranjan Dailata
author_username: ranjancse
categories: []
created_at: 2025-05-21T13:33:31.376Z
updated_at: 2025-05-21T13:33:31.376Z
url: https://n8n.io/workflows/4281
scraped_at: 2025-06-19 22:48:56
description:
  Who this is for
  The Real Estate Intelligence Tracker is a powerful automated workflow designed for real estate analysts, investors, proptech startups, and market researchers who need to collect and analyze structured data from real estate listings across the web at scale.

  This workflow is tailored for:

  Real Estate Analysts** - Tracking property prices, locations, and market trends

  Investment Firms** - Sourcing high-opportunity listings for portfolio decisions

  PropTech Developers** - Automating listing insights for SaaS platforms

  Market Researchers** - Extracting insights from competitive housing data

  Growth Teams** - Monitoring geographic property trends and pricing fluctuations

  What problem is this workflow solving?
  Collecting structured real estate listing data from property websites is difficult due to bot protections and unstructured HTML content. Manual data collection is slow and error-prone, and traditional scrapers often get blocked or miss context.

  This workflow solves:

  Automated bypass of anti-bot protection using Bright Data Web Unlocker

  Conversion of unstructured HTML content into clean text using a Markdown-to-text LLM pipeline

  Structured extraction of key listing data like price, location, property type, and features using OpenAI

  Aggregation and delivery of insights to Google Sheets, local storage, and webhook-based alerts

  What this workflow does

  Convert to Text: Transforms scraped HTML/markdown into clean text using a Basic LLM Chain

  Structured Data Extraction: Uses OpenAI GPT-4o with the Information Extractor node to parse property attributes (price, address, area, type, etc.)

  Aggregate & Merge: Combines data from multiple pages or listings into a cohesive structure

  Outbound Data Handling:

  Google Sheets** – Appends the structured real estate data for further analysis

  Save to Disk** – Persists structured JSON/text data locally

  Webhook Notification** – Sends data alerts or summaries to any third-party platform

  Pre-conditions

  You need to have a Bright Data account and do the necessary setup as mentioned in the "Setup" section below.
  You need to have an OpenAI Account.

  Setup
  Sign up at Bright Data.
  Navigate to Proxies & Scraping and create a new Web Unlocker zone by selecting Web Unlocker API under Scraping Solutions.
  In n8n, configure the Header Auth account under Credentials (Generic Auth Type: Header Authentication).

  The Value field should be set with the
  Bearer XXXXXXXXXXXXXX. The XXXXXXXXXXXXXX should be replaced by the Web Unlocker Token.
  In n8n, Configure the Google Sheet Credentials with your own account. Follow this documentation - Set Google Sheet Credential
  In n8n, configure the OpenAi account credentials.
  Ensure the URL and Bright Data zone name are correctly set in the Set URL, Filename and Bright Data Zone node.
  Set the desired local path in the Write a file to disk node to save the responses.

  How to customize this workflow to your needs

  Target Multiple Sites or Locations

  Update the Bright Data URL node dynamically with a list of regional real estate websites

  Loop through different city/state filter URLs

  Customize Extracted Fields

  Modify the Information Extractor prompt to extract fields like:

  Property size, number of bedrooms/bathrooms

  Days on market

  Nearby amenities or schools

  Agent contact details

  Integrate with More Destinations

  Add nodes to export data to Notion, Airtable, HubSpot, or your custom database

  Generate automated reports using PDF generators and email them

  Data Quality and Logging

  Add validation checks (e.g., missing price or address)

  Save intermediate files (markdown, raw HTML, JSON output) to disk for audit purposes

nodes_used:
  ["n8n-nodes-base.googleSheets","n8n-nodes-base.httpRequest","@n8n/n8n-nodes-langchain.chainLlm","@n8n/n8n-nodes-langchain.lmChatOpenAi","@n8n/n8n-nodes-langchain.informationExtractor"]

workflow_json:
  {"id":"M3htaKFJfCuko2uB","meta":{"instanceId":"885b4fb4a6a9c2cb5621429a7b972df0d05bb724c20ac7dac7171b62f1c7ef40","templateCredsSetupCompleted":true},"name":"Real Estate Intelligence Tracker with Bright Data & OpenAI","tags":[{"id":"Kujft2FOjmOVQAmJ","name":"Engineering","createdAt":"2025-04-09T01:31:00.558Z","updatedAt":"2025-04-09T01:31:00.558Z"},{"id":"ZOwtAMLepQaGW76t","name":"Building Blocks","createdAt":"2025-04-13T15:23:40.462Z","updatedAt":"2025-04-13T15:23:40.462Z"},{"id":"ddPkw7Hg5dZhQu2w","name":"AI","createdAt":"2025-04-13T05:38:08.053Z","updatedAt":"2025-04-13T05:38:08.053Z"}],"nodes":[{"id":"7dc6c3d9-55e0-4f32-b00d-96c92482eca8","name":"When clicking ‘Test workflow’","type":"n8n-nodes-base.manualTrigger","position":[-1700,-210],"parameters":{},"typeVersion":1},{"id":"196a1630-ca74-4fee-a7bf-0555a3693908","name":"Set URL and Bright Data Zone","type":"n8n-nodes-base.set","position":[-1480,-210],"parameters":{"options":{},"assignments":{"assignments":[{"id":"3aedba66-f447-4d7a-93c0-8158c5e795f9","name":"url","type":"string","value":"https://www.redfin.com/IL/Chicago/5814-W-Roscoe-St-60634/home/13464782"},{"id":"4e7ee31d-da89-422f-8079-2ff2d357a0ba","name":"zone","type":"string","value":"web_unlocker1"}]}},"typeVersion":3.4},{"id":"80131d8e-b359-4b2a-8291-faf9c4e8892f","name":"Perform Bright Data Web Request","type":"n8n-nodes-base.httpRequest","position":[-1260,-210],"parameters":{"url":"https://api.brightdata.com/request","method":"POST","options":{},"sendBody":true,"sendHeaders":true,"authentication":"genericCredentialType","bodyParameters":{"parameters":[{"name":"zone","value":"={{ $json.zone }}"},{"name":"url","value":"={{ $json.url }}"},{"name":"format","value":"raw"},{"name":"data_format","value":"markdown"}]},"genericAuthType":"httpHeaderAuth","headerParameters":{"parameters":[{}]}},"credentials":{"httpHeaderAuth":{"id":"kdbqXuxIR8qIxF7y","name":"Header Auth account"}},"typeVersion":4.2},{"id":"2b0c3867-3c8d-4dc2-b9e9-fc9f074efaea","name":"Markdown to Textual Data Extractor","type":"@n8n/n8n-nodes-langchain.chainLlm","position":[-1040,-210],"parameters":{"text":"=You need to analyze the below markdown and convert to textual data. Please do not output with your own thoughts. Make sure to output with textual data only with no links, scripts, css etc.\n\n{{ $json.data }}","messages":{"messageValues":[{"message":"You are a markdown expert"}]},"promptType":"define"},"typeVersion":1.6},{"id":"52dc4add-92e6-4118-948e-63c4a706a017","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[-1720,-640],"parameters":{"width":400,"height":320,"content":"## Note\n\nDeals with the Realestate data extraction by utilizing the Bright Data Web Unlocker Product.\n\n**Please make sure to set the Real-estate website URL with the Bright Data zone name. Also update the Webhook Notification URL of your interest**"},"typeVersion":1},{"id":"0b64779e-d4c6-4c67-8b67-fcddac760db6","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[-1260,-640],"parameters":{"width":480,"height":320,"content":"## LLM Usages\n\nOpenAI GPT 4o model is being used.\n\nBasic LLM Chain for converting the markdown to textual content.\n\nInformation Extractor is being used for the structured data extraction."},"typeVersion":1},{"id":"9d4eaebe-eb56-4d57-abe6-7d2beaff5af0","name":"Review Data Extractor","type":"@n8n/n8n-nodes-langchain.informationExtractor","position":[-500,-560],"parameters":{"text":"=Extract all the reviews from the provided content\n\n {{ $json.text }}","options":{},"schemaType":"fromJson","jsonSchemaExample":"[{\n      \"@type\": \"Review\",\n      \"datePublished\": \"2025-04-29\",\n      \"review\": \"Incredible support and empathy. Shemi truly listened and understood my concerns. Outstanding service!\",\n      \"rating\": {\n        \"@type\": \"Rating\",\n        \"value\": \"5\"\n      }\n    }]"},"typeVersion":1},{"id":"84473d2e-4243-402a-98b3-b80179b9a5ae","name":"Structured Data Extractor","type":"@n8n/n8n-nodes-langchain.informationExtractor","position":[-500,-100],"parameters":{"text":"=Extract structured data from the provided content\n\n {{ $json.text }}","options":{},"schemaType":"fromJson","jsonSchemaExample":"{\n  \"@context\": \"https://schema.org\",\n  \"@type\": \"Offer\",\n  \"itemOffered\": {\n    \"@type\": \"SingleFamilyResidence\",\n    \"name\": \"Luxury 4BHK Villa with Pool in Herzliya\",\n    \"description\": \"A stunning 4-bedroom villa featuring private pool, garden, smart-home automation, and ocean views. Located in one of Herzliya’s premium neighborhoods.\",\n    \"address\": {\n      \"@type\": \"PostalAddress\",\n      \"streetAddress\": \"456 Seaside Road\",\n      \"addressLocality\": \"Herzliya\",\n      \"postalCode\": \"4685105\",\n      \"addressCountry\": \"IL\"\n    },\n    \"floorSize\": {\n      \"@type\": \"QuantitativeValue\",\n      \"value\": 300,\n      \"unitCode\": \"MTK\"\n    },\n    \"numberOfRooms\": 7,\n    \"numberOfBedrooms\": 4,\n    \"numberOfBathroomsTotal\": 3,\n    \"amenityFeature\": [\n      {\n        \"@type\": \"LocationFeatureSpecification\",\n        \"name\": \"Swimming Pool\",\n        \"value\": true\n      },\n      {\n        \"@type\": \"LocationFeatureSpecification\",\n        \"name\": \"Smart Home Enabled\",\n        \"value\": true\n      },\n      {\n        \"@type\": \"LocationFeatureSpecification\",\n        \"name\": \"Sea View\",\n        \"value\": true\n      }\n    ],\n    \"image\": [\n      \"https://brightrealty.com/listings/villa1_front.jpg\",\n      \"https://brightrealty.com/listings/villa1_pool.jpg\",\n      \"https://brightrealty.com/listings/villa1_living.jpg\"\n    ],\n    \"petsAllowed\": \"Yes\",\n    \"url\": \"https://brightrealty.com/properties/luxury-4bhk-villa-herzliya\"\n  },\n  \"priceCurrency\": \"ILS\",\n  \"price\": \"8500000\",\n  \"availability\": \"https://schema.org/InStock\",\n  \"seller\": {\n    \"@type\": \"RealEstateAgent\",\n    \"name\": \"Bright Realty Services\",\n    \"url\": \"https://brightrealty.com\",\n    \"telephone\": \"+972-3-1234567\",\n    \"email\": \"sales@brightrealty.com\",\n    \"address\": {\n      \"@type\": \"PostalAddress\",\n      \"streetAddress\": \"123 Main St\",\n      \"addressLocality\": \"Tel Aviv\",\n      \"postalCode\": \"6100000\",\n      \"addressCountry\": \"IL\"\n    }\n  }\n}"},"typeVersion":1},{"id":"d1b44002-2a50-4c0c-bf55-bf57a994bd2b","name":"Google Sheets","type":"n8n-nodes-base.googleSheets","position":[460,-520],"parameters":{"columns":{"value":{"data":"={{ $json.data }}"},"schema":[{"id":"data","type":"string","display":true,"removed":false,"required":false,"displayName":"data","defaultMatch":false,"canBeUsedToMatch":true}],"mappingMode":"defineBelow","matchingColumns":["data"],"attemptToConvertTypes":false,"convertFieldsToString":false},"options":{},"operation":"appendOrUpdate","sheetName":{"__rl":true,"mode":"list","value":"gid=0","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1DGx_-sZ59wZlrhQRfj-qyMFMF6Z1IxpJrSNHD8rTZR8/edit#gid=0","cachedResultName":"Sheet1"},"documentId":{"__rl":true,"mode":"list","value":"1DGx_-sZ59wZlrhQRfj-qyMFMF6Z1IxpJrSNHD8rTZR8","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1DGx_-sZ59wZlrhQRfj-qyMFMF6Z1IxpJrSNHD8rTZR8/edit?usp=drivesdk","cachedResultName":"Real-estate data"}},"credentials":{"googleSheetsOAuth2Api":{"id":"Zjoxh2BUZ6VXGQhA","name":"Google Sheets account"}},"typeVersion":4.5},{"id":"9f203292-0806-48a9-a409-f64706b1b0b6","name":"Create a binary data for Structured Data Extract","type":"n8n-nodes-base.function","position":[460,-320],"parameters":{"functionCode":"items[0].binary = {\n  data: {\n    data: new Buffer(JSON.stringify(items[0].json, null, 2)).toString('base64')\n  }\n};\nreturn items;"},"typeVersion":1},{"id":"9a64deed-1f56-4e10-9e11-31bfcfd6abac","name":"Write the structured content to disk","type":"n8n-nodes-base.readWriteFile","position":[680,-320],"parameters":{"options":{},"fileName":"=d:\\Realestate-StructuredData.json","operation":"write"},"typeVersion":1},{"id":"83e7f6d7-216c-496b-9011-47d0b95561ba","name":"Merge the responses","type":"n8n-nodes-base.merge","position":[20,-320],"parameters":{},"typeVersion":3.1},{"id":"cf515b99-e139-48f8-9878-7950fa352d1e","name":"Aggregate the responses","type":"n8n-nodes-base.aggregate","position":[240,-320],"parameters":{"options":{},"aggregate":"aggregateAllItemData"},"typeVersion":1},{"id":"a93e59ab-f384-4b05-90f8-71b305a3bfb7","name":"Initiate a Webhook Notification for the Structured Data","type":"n8n-nodes-base.httpRequest","position":[460,-120],"parameters":{"url":"https://webhook.site/7b5380a0-0544-48dc-be43-0116cb2d52c2","options":{},"sendBody":true,"bodyParameters":{"parameters":[{"name":"summary","value":"={{ $json.data }}"}]}},"typeVersion":4.2},{"id":"a2f0de15-7d1d-42bb-aa22-1a3bd359ead5","name":"Sticky Note5","type":"n8n-nodes-base.stickyNote","position":[-1720,-1100],"parameters":{"color":7,"width":400,"height":400,"content":"## Logo\n\n\n![logo](https://images.seeklogo.com/logo-png/43/1/brightdata-logo-png_seeklogo-439974.png)\n"},"typeVersion":1},{"id":"6ecb7f50-2d16-43e2-b999-98492ec81668","name":"OpenAI Chat Model for Markdown to Textual","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[-960,20],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o-mini"},"options":{}},"credentials":{"openAiApi":{"id":"vPKynKbDzJ5ZU4cU","name":"OpenAi account"}},"typeVersion":1.2},{"id":"fe6f00e3-efaa-4d57-8abd-1fbc789152a9","name":"OpenAI Chat Model for Structured Data","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[-420,120],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o-mini"},"options":{}},"credentials":{"openAiApi":{"id":"vPKynKbDzJ5ZU4cU","name":"OpenAi account"}},"typeVersion":1.2},{"id":"4ce2647e-9796-4bfd-8dc2-0aa7f7466824","name":"OpenAI Chat Model for Review Data Extractor","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[-420,-340],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o-mini"},"options":{}},"credentials":{"openAiApi":{"id":"vPKynKbDzJ5ZU4cU","name":"OpenAi account"}},"typeVersion":1.2},{"id":"fad15f6e-0ccb-4810-94d6-bc4f42527071","name":"Sticky Note4","type":"n8n-nodes-base.stickyNote","position":[-60,-640],"parameters":{"color":3,"width":1000,"height":760,"content":"## Outbound Data Push\nOutbound data handling by merging, aggregating the data and pushing the same to multiple sources such as Google Sheets, Save to Disk, Webhook Notification"},"typeVersion":1}],"active":false,"pinData":{},"settings":{"executionOrder":"v1"},"versionId":"db35bf88-1a4c-482e-abfd-49349b35952b","connections":{"Merge the responses":{"main":[[{"node":"Aggregate the responses","type":"main","index":0}]]},"Review Data Extractor":{"main":[[{"node":"Merge the responses","type":"main","index":0}]]},"Aggregate the responses":{"main":[[{"node":"Google Sheets","type":"main","index":0},{"node":"Initiate a Webhook Notification for the Structured Data","type":"main","index":0},{"node":"Create a binary data for Structured Data Extract","type":"main","index":0}]]},"Structured Data Extractor":{"main":[[{"node":"Merge the responses","type":"main","index":1}]]},"Set URL and Bright Data Zone":{"main":[[{"node":"Perform Bright Data Web Request","type":"main","index":0}]]},"Perform Bright Data Web Request":{"main":[[{"node":"Markdown to Textual Data Extractor","type":"main","index":0}]]},"When clicking ‘Test workflow’":{"main":[[{"node":"Set URL and Bright Data Zone","type":"main","index":0}]]},"Markdown to Textual Data Extractor":{"main":[[{"node":"Review Data Extractor","type":"main","index":0},{"node":"Structured Data Extractor","type":"main","index":0}]]},"OpenAI Chat Model for Structured Data":{"ai_languageModel":[[{"node":"Structured Data Extractor","type":"ai_languageModel","index":0}]]},"OpenAI Chat Model for Markdown to Textual":{"ai_languageModel":[[{"node":"Markdown to Textual Data Extractor","type":"ai_languageModel","index":0}]]},"OpenAI Chat Model for Review Data Extractor":{"ai_languageModel":[[{"node":"Review Data Extractor","type":"ai_languageModel","index":0}]]},"Create a binary data for Structured Data Extract":{"main":[[{"node":"Write the structured content to disk","type":"main","index":0}]]}}}


name: Automatically Delete Spam Emails in Gmail on Schedule
author_name: Bao Duy Nguyen
author_username: duynb
nodes_used: ["n8n-nodes-base.gmail"]
categories: []
created_at: 2025-05-21T14:19:52.816Z
updated_at: 2025-05-21T14:19:52.816Z
url: https://n8n.io/workflows/4285
scraped_at: 2025-06-19 22:49:27
description:
  Who is this for?
  If you hate SPAM emails or don't want to clean them up frequently.

  What problem is this workflow solving?
  It automatically deletes SPAM emails for you, so you don't have to. Save a bit of your time.

  What this workflow does
  You can specify when to execute the workflow: daily, weekly, or monthly.

  Setup
  Select the preferred execution time
  Configure credentials for Gmail OAuth2

  How to customize this workflow to your needs
  There's no need. It just works!

workflow_json:
  {"id":"DzNTc1Td148ti7RU","meta":{"instanceId":"e76981884963d13b9deb7bc5a6b15daf6838937e1dd529f22f2c146d8b79cae4","templateCredsSetupCompleted":true},"name":"Automatically delete SPAM emails","tags":[{"id":"yjDYtffFaPyJlYcC","name":"template","createdAt":"2025-05-21T14:11:32.813Z","updatedAt":"2025-05-21T14:11:32.813Z"}],"nodes":[{"id":"a4fa3e50-5b63-4e69-97eb-534b1170ebab","name":"Trigger at Sunday midnight","type":"n8n-nodes-base.scheduleTrigger","position":[-260,-20],"parameters":{"rule":{"interval":[{"field":"weeks"}]}},"typeVersion":1.2},{"id":"286e5c34-18ab-46da-b184-cfabf796b21d","name":"Delete SPAM emails","type":"n8n-nodes-base.gmail","position":[160,-20],"webhookId":"46b0fe0f-cc00-4994-8364-9048c888e9ef","parameters":{"messageId":"={{ $json.id }}","operation":"delete"},"credentials":{"gmailOAuth2":{"id":"yz4iqcG5X1s5wlgS","name":"Gmail account"}},"typeVersion":2.1},{"id":"b755451e-7fc3-4c3b-b669-69d700c38fa4","name":"Get all SPAM emails","type":"n8n-nodes-base.gmail","position":[-60,-20],"webhookId":"c47419de-278c-40d1-a5da-c9414d3f89c6","parameters":{"filters":{"labelIds":["SPAM"]},"operation":"getAll","returnAll":true},"credentials":{"gmailOAuth2":{"id":"yz4iqcG5X1s5wlgS","name":"Gmail account"}},"typeVersion":2.1},{"id":"cc3c9d36-a26e-47cb-bb74-3a1027b996cd","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[-580,-260],"parameters":{"color":7,"width":340,"height":200,"content":"## Automatically delete your SPAM emails on frequent basis\n\nThis automation will run repeatedly at a particular time to delete all your SPAM emails\n\n"},"typeVersion":1},{"id":"86749abf-16c8-4406-9394-b22a384b4e89","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[-280,140],"parameters":{"color":7,"width":150,"height":200,"content":"## :point_up: UPDATE ME\nSelect when to trigger the workflow"},"typeVersion":1}],"active":false,"pinData":{},"settings":{"executionOrder":"v1"},"versionId":"f47d2f29-89d0-4719-a47b-55b43e84466b","connections":{"Get all SPAM emails":{"main":[[{"node":"Delete SPAM emails","type":"main","index":0}]]},"Trigger at Sunday midnight":{"main":[[{"node":"Get all SPAM emails","type":"main","index":0}]]}}}


name: Convert RSS News to AI Avatar Videos with Heygen & GPT-4o
author_name: David Olusola
author_username: dae221
categories: []
created_at: 2025-05-21T17:52:54.270Z
updated_at: 2025-05-21T17:52:54.270Z
url: https://n8n.io/workflows/4288
scraped_at: 2025-06-19 22:49:37
description:
  🎬 Automated News-to-Video Workflow (n8n + Heygen + GPT-4o)

  📄 Overview:

  This n8n workflow turns news from an RSS feed (e.g., CNN) into short, AI-generated avatar videos using Heygen. It:

  Fetches news from an RSS feed.
  Logs headlines to Google Sheets.
  Uses GPT-4o or Google Gemini to generate a 30–60 sec script.
  Sends the script to Heygen to create an avatar video.
  Monitors and retrieves the final video.
  Logs video metadata (title, link, etc.) to Google Sheets.

  🎯 Ideal for content creators, marketers, or media pages repurposing written news into video content at scale.

  ⚙️ Setup Guide (No Sensitive Info)

  🔑 1. Heygen API

  Paid Heygen plan required.
  Add your API key in the Setup Heygen node:

      "heygen_api_key": "your_key_here"
    Optional: Set "avatar_id" and "voice_id" as desired.

  💡 2. AI Model: GPT-4o or Gemini

  GPT-4o**: Use OpenAI’s node or HTTP request with your API key.
  Gemini**: Link your Google Cloud project and connect the Gemini node using OAuth2 credentials.

  📥 3. RSS Feed

  Add an RSS node (e.g., CNN).
  Extract title, link, and content.

  📊 4. Google Sheets + Drive

  Connect via OAuth2:

    "Google Sheets account 2"
    "Google Drive account 2"
  Replace sheet IDs in:

    Log news to sheets
    Log video URL and title to sheets

  📹 5. Create Video (Heygen)

  Send a POST request to Heygen's API using the generated script, avatar, and voice ID.

  ⏳ 6. Monitor Status

  Poll the status endpoint until video is ready.
  Capture the download link.

  🧾 7. Log Final Output

  Save video metadata to a Google Sheet for publishing or archiving.

  Set up video: Link in Workflow 

nodes_used:
  ["n8n-nodes-base.googleSheets","n8n-nodes-base.httpRequest","n8n-nodes-base.googleDrive","n8n-nodes-base.code","@n8n/n8n-nodes-langchain.agent","@n8n/n8n-nodes-langchain.lmChatOpenAi"]

workflow_json:
  {"id":"lOnfQBQ1O7BLR1S5","meta":{"instanceId":"2000c64071c20843606b95c63795bb0797c41036047055a6586498e855b96efc","templateCredsSetupCompleted":true},"name":"AI-Powered News to Video Generator with Heygen & GPT4o","tags":[],"nodes":[{"id":"7012dfef-7b35-4cbc-b970-923ddae3cd79","name":"AI Agent","type":"@n8n/n8n-nodes-langchain.agent","position":[-1900,580],"parameters":{},"typeVersion":1.8},{"id":"ef12f30b-83f9-4295-9fa9-b89cd46c80dd","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[-2040,-40],"parameters":{"content":""},"typeVersion":1},{"id":"04735893-dcdf-49f7-90af-011208fa3790","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[-1100,-40],"parameters":{"content":""},"typeVersion":1},{"id":"bbb05e02-6f71-4844-a042-5fbe6412872b","name":"Sticky Note3","type":"n8n-nodes-base.stickyNote","position":[-1060,980],"parameters":{"content":""},"typeVersion":1},{"id":"01f46028-7341-468e-8788-95da905dab77","name":"RSS Read","type":"n8n-nodes-base.rssFeedRead","position":[-1760,260],"parameters":{},"typeVersion":1.1},{"id":"9721845d-eb1c-4299-8a37-cac6ff80eca5","name":"When clicking ‘Test workflow’","type":"n8n-nodes-base.manualTrigger","position":[-1940,260],"parameters":{},"typeVersion":1},{"id":"18e3bab3-0e9e-4cab-8fe7-8f67ba1b39ef","name":"Wait","type":"n8n-nodes-base.wait","position":[-560,580],"webhookId":"d9404622-0a06-4a65-959e-badd4fd87465","parameters":{},"typeVersion":1.1,"alwaysOutputData":false},{"id":"772f5854-1dd6-42e7-bf9d-b2948a6394e0","name":"Get Avatar Video","type":"n8n-nodes-base.httpRequest","position":[-300,580],"parameters":{},"typeVersion":4.2},{"id":"d4bd5011-9986-4d8f-b10a-b919e367611e","name":"Create Avatar Video","type":"n8n-nodes-base.httpRequest","position":[-800,580],"parameters":{},"typeVersion":4.2},{"id":"e728589c-784c-4c9c-a7b1-37da4ddda043","name":"Setup Heygen","type":"n8n-nodes-base.set","position":[-1040,580],"parameters":{},"typeVersion":3.4},{"id":"cab70adc-73bf-4e5b-8a2c-afef28983dbf","name":"Download video","type":"n8n-nodes-base.httpRequest","position":[-20,580],"parameters":{},"typeVersion":4.2},{"id":"cdc50948-e5fa-4ad6-b0f6-ad79afa37e98","name":"Limit","type":"n8n-nodes-base.limit","position":[-1260,260],"parameters":{},"typeVersion":1},{"id":"5433be24-3061-4d94-9de3-3d75aa1be40a","name":"Google Drive","type":"n8n-nodes-base.googleDrive","disabled":true,"position":[280,580],"parameters":{},"typeVersion":3},{"id":"9b503ab4-4834-43d5-9b2d-7823715c50ee","name":"parse caption","type":"n8n-nodes-base.code","position":[-1540,580],"parameters":{},"typeVersion":2},{"id":"b3a2a7ef-c055-4d49-b79c-9eea7ce89bab","name":"Limit1","type":"n8n-nodes-base.limit","position":[-1600,260],"parameters":{},"typeVersion":1},{"id":"03814c51-6323-4c90-b8bd-4fa5feaf187b","name":"log news to sheets","type":"n8n-nodes-base.googleSheets","position":[-1420,260],"parameters":{},"typeVersion":4.5},{"id":"efad1b71-33fc-4070-b2c4-d5976cb9dd76","name":"Log video url and title to sheets","type":"n8n-nodes-base.googleSheets","position":[-140,780],"parameters":{},"typeVersion":4.5},{"id":"63ee3aff-4b8b-4a26-b8e0-d8d844572d6f","name":"write script","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[-1880,800],"parameters":{},"typeVersion":1.2}],"active":false,"pinData":{},"settings":{"executionOrder":"v1"},"versionId":"0d647d48-28ad-408b-99b6-056d6903dca9","connections":{"Wait":{"main":[[{"node":"Get Avatar Video","type":"main","index":0}]]},"Limit":{"main":[[{"node":"AI Agent","type":"main","index":0}]]},"Limit1":{"main":[[{"node":"log news to sheets","type":"main","index":0}]]},"AI Agent":{"main":[[{"node":"parse caption","type":"main","index":0}]]},"RSS Read":{"main":[[{"node":"Limit1","type":"main","index":0}]]},"Setup Heygen":{"main":[[{"node":"Create Avatar Video","type":"main","index":0}]]},"write script":{"ai_languageModel":[[{"node":"AI Agent","type":"ai_languageModel","index":0}]]},"parse caption":{"main":[[{"node":"Setup Heygen","type":"main","index":0}]]},"Download video":{"main":[[{"node":"Google Drive","type":"main","index":0}]]},"Get Avatar Video":{"main":[[{"node":"Download video","type":"main","index":0},{"node":"Log video url and title to sheets","type":"main","index":0}]]},"log news to sheets":{"main":[[{"node":"Limit","type":"main","index":0}]]},"Create Avatar Video":{"main":[[{"node":"Wait","type":"main","index":0}]]},"When clicking ‘Test workflow’":{"main":[[{"node":"RSS Read","type":"main","index":0}]]}}}


name: Automate Business Lead Scraping from Apify to Google Sheets with Data Cleaning
author_name: David Olusola
author_username: dae221
nodes_used: ["n8n-nodes-base.googleSheets","n8n-nodes-base.httpRequest","n8n-nodes-base.code"]
categories: []
created_at: 2025-05-21T18:47:26.249Z
updated_at: 2025-05-21T18:47:26.249Z
url: https://n8n.io/workflows/4295
scraped_at: 2025-06-19 22:48:42
description:
  🚀 Automated Lead Scraper Workflow (Apify + n8n + Google Sheets)

  🧠 What It Does

  This n8n workflow automates the process of scraping leads using Apify, cleaning the extracted data, and exporting it to Google Sheets—ready for use in outreach, prospecting, or CRM pipelines.

  🔄 Workflow Steps

  ✅ Start – Manually triggers the workflow.
  🧩 Set Variables – Stores required Apify credentials:

     APIFY_TOKEN: Your Apify token.
     APIFY_TASK_ID: The Apify task to run.
  🕸️ Run Apify Scraper – Launches the scraper and fetches the dataset.
  🧹 Clean Data – Processes scraped results to:

     ✂️ Strip non-numeric characters from phone numbers.
     ✉️ Format emails (lowercase + trimmed).
  📊 Export to Google Sheets – Appends clean data to your spreadsheet:

     🏢 company name → from title
     📞 phone → cleaned number
     📍 address → from scraped info

  🛠️ Requirements

  🕷️ Apify Account

    A valid APIFY_TOKEN
    An existing Apify task (APIFY_TASK_ID)

  📗 Google Sheets Access

    OAuth2 credentials set up in n8n (e.g., "Google Sheets account 2")

  🚦 How to Use

  ⚙️ Open the Variables node and plug in your Apify credentials.
  📄 Confirm the Google Sheets node points to your desired spreadsheet.
  ▶️ Run the workflow manually from the Start node.

  📥 Output

  A ready-to-use sheet of cleaned lead data containing:

  Company names
  Phone numbers
  Addresses

  💼 Perfect For:

  Sales teams doing outbound prospecting
  Marketers building lead lists
  Agencies running data aggregation tasks

workflow_json:
  {"id":"8dpOtivR6zGMa8Nf","meta":{"instanceId":"2000c64071c20843606b95c63795bb0797c41036047055a6586498e855b96efc","templateCredsSetupCompleted":true},"name":"Automated Lead Scraper: Apify to Google Sheets","tags":[],"nodes":[{"id":"331e904a-362e-4b18-ac01-60bd138a7ee1","name":"Manual Trigger","type":"n8n-nodes-base.manualTrigger","position":[-1740,-300],"parameters":{},"typeVersion":1},{"id":"c8c72d6e-4558-4ab1-9c19-2b8e3cefc856","name":"Run Apify Scraper","type":"n8n-nodes-base.httpRequest","position":[-1280,-300],"parameters":{"url":"={{ 'https://api.apify.com/v2/actor-tasks/' + $json.APIFY_TASK_ID + '/run-sync-get-dataset-items?token=' +$json.APIFY_TOKEN}}","options":{"splitIntoItems":true}},"typeVersion":1},{"id":"fb61d5a9-0352-4079-a00f-c42df06bb09e","name":"Clean Data","type":"n8n-nodes-base.code","position":[-1080,-300],"parameters":{"jsCode":"// Clean scraped data before LLM processing\nreturn $input.all().map(item => ({\n  ...item.json,\n  phone: item.json.phone?.replace(/[^\\d+]/g, '') || '',\n  email: item.json.email?.toLowerCase().trim() || ''\n}));"},"typeVersion":2},{"id":"a6988139-87e5-423c-bec9-ce155f617dab","name":"Export to Google Sheets","type":"n8n-nodes-base.googleSheets","position":[-760,-300],"parameters":{"columns":{"value":{"phone":"={{ $json.phone }}","Address":"={{ $json.address }}","company name":"={{ $json.title }}"},"schema":[{"id":"company name","type":"string","display":true,"required":false,"displayName":"company name","defaultMatch":false,"canBeUsedToMatch":true},{"id":"website","type":"string","display":true,"required":false,"displayName":"website","defaultMatch":false,"canBeUsedToMatch":true},{"id":"phone","type":"string","display":true,"required":false,"displayName":"phone","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Address","type":"string","display":true,"required":false,"displayName":"Address","defaultMatch":false,"canBeUsedToMatch":true}],"mappingMode":"defineBelow","matchingColumns":[],"attemptToConvertTypes":false,"convertFieldsToString":false},"options":{},"operation":"append","sheetName":{"__rl":true,"mode":"list","value":"Sheet1","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1UHkd_OuK1Xzc0ZXo7FPrsd5M1JlsIY9pJDC3fsJ3oq8/edit#gid=0","cachedResultName":"Sheet1"},"documentId":{"__rl":true,"mode":"list","value":"YOUR_GOOGLE_SHEET_ID","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1UHkd_OuK1Xzc0ZXo7FPrsd5M1JlsIY9pJDC3fsJ3oq8/edit?usp=drivesdk","cachedResultName":"leas list solar"}},"typeVersion":4.5},{"id":"f4398fd2-bff0-4e9c-ae1b-f5950be0a384","name":"Variables","type":"n8n-nodes-base.set","position":[-1500,-300],"parameters":{"options":{},"assignments":{"assignments":[{"id":"4486360c-2296-41ad-a48f-706e24c49a4f","name":"APIFY_TOKEN","type":"string","value":"YOUR_APIFY_API_TOKEN"},{"id":"6e56b0e3-36ae-4f1e-b0e5-38767bbe8af9","name":"APIFY_TASK_ID","type":"string","value":"YOUR_APIFY_TASK_ID"}]}},"typeVersion":3.4},{"id":"04a980cf-365b-4cc3-8439-fd71cb1f05a3","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[-1860,-820],"parameters":{"color":7,"width":1660,"height":780,"content":"## Automated Business Lead Scraper with Apify to Google Sheets\n**Purpose:** Automates scraping business leads using Apify, cleaning the data, and exporting them to Google Sheets.\n\n**Workflow Steps:**\n1. **Manual Trigger**: Starts the workflow manually.\n2. **Set API Credentials**: Add your `APIFY_TOKEN` and `APIFY_TASK_ID`.\n3. **Run Apify Scraper**: Fetches leads using Apify HTTP API.\n4. **Clean Data**: Formats phone numbers and emails.\n5. **Export to Google Sheets**: Appends data to your spreadsheet.\n\n**Google Sheet Requirements:**\n- Sheet name: `Sheet1`\n- Columns: `company name`, `phone`, `Address`\n\n**Customization Tips:**\n- Add more fields like `email`, `website` in Clean Data and mapping.\n- Add conditions or filters before exporting.\n- Add email alerts if needed.\n"},"typeVersion":1}],"active":false,"pinData":{},"settings":{"executionOrder":"v1"},"versionId":"47bf9abd-67aa-49c8-81c9-761e75ee731f","connections":{"Start":{"main":[[{"node":"Variables","type":"main","index":0}]]},"Variables":{"main":[[{"node":"Run Apify Scraper","type":"main","index":0}]]},"Clean Data":{"main":[[{"node":"Export to Google Sheets","type":"main","index":0}]]},"Run Apify Scraper":{"main":[[{"node":"Clean Data","type":"main","index":0}]]}}}


name: Auto-Generate Blog & AI Image from YouTube Videos with Dumpling AI & GPT-4o
author_name: Yang
author_username: yang
categories: []
created_at: 2025-05-22T21:00:31.600Z
updated_at: 2025-05-22T21:00:31.600Z
url: https://n8n.io/workflows/4327
scraped_at: 2025-06-19 22:50:22
description:
  Who is this for?

  This template is designed for content creators, marketing teams, educators, or media managers who want to repurpose video content into written blog posts with visuals. It's ideal for anyone looking to automate the process of transforming YouTube videos into professional blog articles and custom images.

  What problem is this workflow solving?

  Creating written content from video material is time-consuming and manual. This workflow solves that by automating the entire pipeline: from detecting new YouTube video uploads to transcribing the audio, turning it into an engaging blog post, generating a matching visual, and saving both in Airtable. It saves hours of work while keeping your blog or social feed active and consistent.

  What this workflow does

  This automation listens for new YouTube videos added to a Google Drive folder, extracts the full transcript using Dumpling AI, and sends it to GPT-4o to generate a blog post and image prompt. Dumpling AI then turns the prompt into a 16:9 visual. The blog and visual are saved into Airtable for easy publishing or curation.

  Setup

  Google Drive Trigger
     Create a folder in Google Drive and upload your YouTube videos there.
     Link this folder in the "Watch Folder for New YouTube Videos" node.
     Enable polling every minute or adjust as needed.

  Download & Prepare the Video
     The video is downloaded and converted into base64 format by the next two nodes:  
       Download Video File and Convert Downloaded Video to Base64.

  Transcription with Dumpling AI
     The base64 video is sent to Dumpling AI’s extract-video endpoint.
     You must have a Dumpling AI account and an API key with access to this endpoint: Dumpling AI Docs

  Generate Blog Content with GPT-4o
     GPT-4o takes the transcript and generates:
       A human-like blog post
       A descriptive prompt for AI image generation
     Make sure your OpenAI credentials are configured.

  Generate the Visual
     The prompt is passed to Dumpling AI’s generate-ai-image endpoint using model FLUX.1-pro.
     The result is a clean 1024x576 image.

  Save to Airtable
     Blog content is stored under the Content field in Airtable.
     The image prompt is also added to the Attachments column as a visual reference.
     Ensure Airtable base and table are preconfigured with the correct field names.

  How to customize this workflow to your needs

  Change the GPT prompt to alter the tone or format of the blog post (e.g., add bullet points or SEO tags).
  Modify the Dumpling AI prompt to generate different image styles.
  Add a scheduler or webhook trigger to run at different intervals or through other integrations.
  Connect this output to Ghost, Notion, or your CMS using additional nodes.

  🧠 Sticky Note Summary

  Part 1: Transcription & Blog Prompt
  Watches a Google Drive folder for new video uploads.
  Downloads and encodes the video.
  Transcribes full audio with Dumpling AI.
  GPT-4o writes a blog post and descriptive image prompt.

  Part 2: Image Generation & Airtable Save
  Dumpling AI generates a visual from the image prompt.
  Blog content is saved to Airtable.
  The image prompt is patched into the Attachments field in the same record.

  ✅ Use this if you want to automate repurposing YouTube videos into blog content with zero manual work.

nodes_used:
  ["n8n-nodes-base.airtable","n8n-nodes-base.httpRequest","n8n-nodes-base.googleDrive","@n8n/n8n-nodes-langchain.openAi"]

workflow_json:
  {"id":"kyDSmFJkvi8CYHh2","meta":{"instanceId":"a1ae5c8dc6c65e674f9c3947d083abcc749ef2546dff9f4ff01de4d6a36ebfe6","templateCredsSetupCompleted":true},"name":"Auto-Generate Blog & AI Image from YouTube Videos with Dumpling AI & GPT-4o","tags":[],"nodes":[{"id":"7847f8a8-a60e-4b2c-afa1-8d586cb42d5c","name":"Watch Folder for New YouTube Videos","type":"n8n-nodes-base.googleDriveTrigger","position":[-2960,-420],"parameters":{"event":"fileCreated","options":{},"pollTimes":{"item":[{"mode":"everyMinute"}]},"triggerOn":"specificFolder","folderToWatch":{"__rl":true,"mode":"list","value":"","cachedResultUrl":"https://drive.google.com/drive/folders/1mde_V0ePcJEebVydygVKT7GDiABjj2A4","cachedResultName":"Youtube Videos"}},"credentials":{"googleDriveOAuth2Api":{"id":"B0Hulh0j065xznhI","name":"Google Drive account 2"}},"typeVersion":1},{"id":"cee77d1b-a91a-4fae-b5ae-eac34a9b0a03","name":"Download Video File","type":"n8n-nodes-base.googleDrive","position":[-2740,-420],"parameters":{"fileId":{"__rl":true,"mode":"id","value":"={{ $json.id }}"},"options":{},"operation":"download"},"credentials":{"googleDriveOAuth2Api":{"id":"B0Hulh0j065xznhI","name":"Google Drive account 2"}},"typeVersion":3},{"id":"7b5ae3f4-d89d-4506-985d-a4c2afc5c0f5","name":"Convert Downloaded Video to Base64","type":"n8n-nodes-base.extractFromFile","position":[-2520,-420],"parameters":{"options":{},"operation":"binaryToPropery"},"typeVersion":1},{"id":"e94c073a-e8e3-4b7e-9b86-21f7568b98cb","name":"Transcribe Video with Dumpling AI (Full Transcript)","type":"n8n-nodes-base.httpRequest","position":[-2300,-420],"parameters":{"url":"https://app.dumplingai.com/api/v1/extract-video","method":"POST","options":{},"jsonBody":"={\n  \"inputMethod\": \"base64\",\n  \"video\": \"{{ $json.data }}\",\n  \"prompt\": \"Please transcribe the entire audio content of this video. I need a clear, complete, and accurate transcript of everything that was said, without summarizing or skipping any part. Include all spoken words, even fillers or pauses like 'um' or 'uh', if present. Format the transcript in clean readable text, broken into paragraphs where appropriate.\",\n  \"jsonMode\": \"false\"\n}\n","sendBody":true,"specifyBody":"json","authentication":"genericCredentialType","genericAuthType":"httpHeaderAuth"},"credentials":{"httpBasicAuth":{"id":"ZqOKe2AhRqsTlTR1","name":"n8n connections"},"httpHeaderAuth":{"id":"RLFzAcGRepr5eXZB","name":"n8n"}},"typeVersion":4.2},{"id":"29e09351-0d8e-40c4-8a41-d00bff9e93a4","name":"Generate Blog & Image Prompt using GPT-4o","type":"@n8n/n8n-nodes-langchain.openAi","position":[-2080,-420],"parameters":{"modelId":{"__rl":true,"mode":"list","value":"gpt-4o","cachedResultName":"GPT-4O"},"options":{},"messages":{"values":[{"role":"system","content":"=You are an experienced blog writer and creative AI assistant. Based on the transcript I will provide, generate:\n\nA blog post that summarizes and expands on the key message of the video in a clear, engaging, and human tone.\n\nAn image prompt for AI image generation that visually supports the content of the blog post.\n\nBlog Post Guidelines:\n\nThe blog post should be written in a natural and conversational tone.\n\nIt must start with a strong opening paragraph that hooks the reader.\n\nFollow with 2 to 4 short paragraphs that explain or expand on the main ideas in the transcript.\n\nEnd with a clear conclusion or takeaway that wraps up the message or encourages readers to take action.\n\nDo not use overly technical or robotic language. Keep it clear and useful for the average reader.\n\nImage Prompt Guidelines:\n\nCreate a short, descriptive image prompt that visually represents the core message of the blog.\n\nThe image prompt should be suitable for AI image generation models like \nFLUX.1-pro.\n\nIt should be visually specific, using descriptive words that reflect the theme and tone of the blog.\n\nReturn your response in this exact JSON format:\n\n{\n  \"blog_post\": \"Your full blog content here\",\n  \"image_prompt\": \"Your image generation prompt here\"\n}"},{"content":"=Here is the transcript to work with:[{{ $json.results }} ] "}]},"jsonOutput":true},"credentials":{"openAiApi":{"id":"fdhWALG84tBLgSZT","name":"OpenAi account"}},"typeVersion":1.8},{"id":"d68ab832-0c22-4ee7-8406-f1aba6911f70","name":"Generate Visual from Blog Prompt with Dumpling AI","type":"n8n-nodes-base.httpRequest","position":[-1700,-420],"parameters":{"url":"https://app.dumplingai.com/api/v1/generate-ai-image","method":"POST","options":{},"jsonBody":"={\n  \"model\": \"FLUX.1-pro\",\n  \"input\": {\n    \"prompt\": \"{{ $json.message.content.image_prompt }}\",\n    \"width\": 1024,\n    \"height\": 576,\n    \"aspect_ratio\": \"16:9\"\n  }\n}\n","sendBody":true,"specifyBody":"json","authentication":"genericCredentialType","genericAuthType":"httpHeaderAuth"},"credentials":{"httpHeaderAuth":{"id":"RLFzAcGRepr5eXZB","name":"n8n"}},"typeVersion":4.2},{"id":"34b5a7a2-2cab-49a4-a905-dd6611de33f1","name":"Save Blog Post to Airtable","type":"n8n-nodes-base.airtable","position":[-1480,-420],"parameters":{"base":{"__rl":true,"mode":"list","value":"","cachedResultUrl":"https://airtable.com/appPSvSKdA6075xJC","cachedResultName":"Testing n8n"},"table":{"__rl":true,"mode":"list","value":"","cachedResultUrl":"https://airtable.com/appPSvSKdA6075xJC/tblboiRp54hqA813K","cachedResultName":"social post"},"columns":{"value":{"Content":"={{ $('Generate Blog & Image Prompt using GPT-4o').item.json.message.content.blog_post }}"},"schema":[{"id":"ID","type":"string","display":true,"removed":true,"readOnly":true,"required":false,"displayName":"ID","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Content","type":"string","display":true,"removed":false,"readOnly":false,"required":false,"displayName":"Content","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Attachments","type":"array","display":true,"removed":false,"readOnly":false,"required":false,"displayName":"Attachments","defaultMatch":false,"canBeUsedToMatch":true}],"mappingMode":"defineBelow","matchingColumns":[],"attemptToConvertTypes":false,"convertFieldsToString":false},"options":{},"operation":"create"},"credentials":{"airtableTokenApi":{"id":"H8PVkBgUPCcUhhRC","name":"Airtable Personal Access Token account"}},"typeVersion":2.1},{"id":"cc6c3c98-d639-4bd4-b727-3556e33c3397","name":"Upload Blog post Image to Airtable","type":"n8n-nodes-base.httpRequest","position":[-1260,-420],"parameters":{"url":"=https://api.airtable.com/v0///{{ $json.id }}","method":"PATCH","options":{},"jsonBody":"={\n  \"fields\": {\n    \"Attachments\": [\n      {\n        \"url\": \"{{ $('Generate Blog & Image Prompt using GPT-4o').item.json.message.content.image_prompt }}\"\n      }\n    ]\n  }\n}\n","sendBody":true,"sendHeaders":true,"specifyBody":"json","authentication":"genericCredentialType","genericAuthType":"httpHeaderAuth","headerParameters":{"parameters":[{}]}},"credentials":{"httpHeaderAuth":{"id":"VyzU59iFznTo7K6r","name":"Airtable Connection"}},"typeVersion":4.2},{"id":"aa4fb418-c654-413e-986f-df5bad418703","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[-2960,-620],"parameters":{"width":700,"height":240,"content":"### 🎥 From Video Upload to Blog Prompt\n\nThis part of the workflow starts when a new video is added to a designated Google Drive folder. It downloads the video and converts it into base64 format. That base64 video is then sent to Dumpling AI’s `extract-video` endpoint, which transcribes the entire audio content. The transcription is passed to GPT-4o, which writes a full blog post and also creates a descriptive image prompt based on the video's message.\n"},"typeVersion":1},{"id":"8a379ab7-b7ba-409f-a072-c3e0c7e20f7e","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[-2040,-620],"parameters":{"width":820,"height":260,"content":"### 📝 Generate Image and Save Blog to Airtable\n\nThe AI-generated image prompt is sent to Dumpling AI’s `generate-ai-image` endpoint (model FLUX.1-pro) to produce a visual that aligns with the blog post. The blog content is stored in Airtable under the `Content` field. Finally, the image prompt is also patched into the Airtable record under `Attachments` to complete the post entry for social use or publishing.\n"},"typeVersion":1}],"active":false,"pinData":{},"settings":{"executionOrder":"v1"},"versionId":"41c42227-95ae-4535-be56-1cc8a71490ac","connections":{"Download Video File":{"main":[[{"node":"Convert Downloaded Video to Base64","type":"main","index":0}]]},"Save Blog Post to Airtable":{"main":[[{"node":"Upload Blog post Image to Airtable","type":"main","index":0}]]},"Convert Downloaded Video to Base64":{"main":[[{"node":"Transcribe Video with Dumpling AI (Full Transcript)","type":"main","index":0}]]},"Watch Folder for New YouTube Videos":{"main":[[{"node":"Download Video File","type":"main","index":0}]]},"Generate Blog & Image Prompt using GPT-4o":{"main":[[{"node":"Generate Visual from Blog Prompt with Dumpling AI","type":"main","index":0}]]},"Generate Visual from Blog Prompt with Dumpling AI":{"main":[[{"node":"Save Blog Post to Airtable","type":"main","index":0}]]},"Transcribe Video with Dumpling AI (Full Transcript)":{"main":[[{"node":"Generate Blog & Image Prompt using GPT-4o","type":"main","index":0}]]}}}


name: Automated Resume Job Matching Engine with Bright Data MCP & OpenAI 4o mini
author_name: Ranjan Dailata
author_username: ranjancse
categories: []
created_at: 2025-05-23T00:01:02.829Z
updated_at: 2025-05-23T00:01:02.829Z
url: https://n8n.io/workflows/4330
scraped_at: 2025-06-19 22:49:54
description:
  Notice
  Community nodes can only be installed on self-hosted instances of n8n.

  Who this is for
  The Automated Resume Job Matching Engine is an intelligent workflow designed for career platforms, HR tech startups, recruiting firms, and AI developers who want to streamline job-resume matching using real-time data from LinkedIn and job boards.

  This workflow is tailored for:

  HR Tech Founders** - Building next-gen recruiting products

  Recruiters & Talent Sourcers** - Seeking automated candidate-job fit evaluation

  Job Boards & Portals** - Enriching user experience with AI-driven job recommendations

  Career Coaches & Resume Writers** - Offering personalized job fit analysis

  AI Developers** - Automating large-scale matching tasks using LinkedIn and job data

  What problem is this workflow solving?
  Manually matching a resume to job description is time-consuming, biased, and inefficient. Additionally, accessing live job postings and candidate profiles requires overcoming web scraping limitations.

  This workflow solves:

  Automated LinkedIn profile and job post data extraction using Bright Data MCP infrastructure

  Semantic matching between job requirements and candidate resume using OpenAI 4o mini

  Pagination handling for high-volume job data

  End-to-end automation from scraping to delivery via webhook and persisting the job matched response to disk

  What this workflow does

  Bright Data MCP for Job Data Extraction
  Uses Bright Data MCP Clients to extract multiple job listings (supports pagination)

  Pulls job data from LinkedIn with the pre-defined filtering criteria's

  OpenAI 4o mini LLM Matching Engine
  Extracts paginated job data from the Bright Data MCP extracted info via the MCP scrape_as_html tool.

  Extracts textual job description information via the scraped job information by leveraging the Bright Data MCP scrape_as_html tool.

  AI Job Matching node handles the job description and the candidate resume compare to generate match scores with insights

  Data Delivery
  Sends final match report to a Webhook Notification endpoint

  Persistence of AI matched job response to disk 

  Pre-conditions

  Knowledge of Model Context Protocol (MCP) is highly essential. Please read this blog post - model-context-protocol
  You need to have the Bright Data account and do the necessary setup as mentioned in the Setup section below.
  You need to have the Google Gemini API Key. Visit Google AI Studio
  You need to install the Bright Data MCP Server @brightdata/mcp
  You need to install the n8n-nodes-mcp

  Setup

  Please make sure to setup n8n locally with MCP Servers by navigating to n8n-nodes-mcp
  Please make sure to install the Bright Data MCP Server @brightdata/mcp  on your local machine.
  Sign up at Bright Data.
  Navigate to Proxies & Scraping and create a new Web Unlocker zone by selecting Web Unlocker API under Scraping Solutions.
  Create a Web Unlocker proxy zone called mcp_unlocker on Bright Data control panel.
  In n8n, configure the OpenAi account credentials.
  In n8n, configure the credentials to connect with MCP Client (STDIO) account with the Bright Data MCP Server as shown below.

  Make sure to copy the Bright Data API_TOKEN within the Environments textbox above as API_TOKEN=&lt;your-token&gt;.
  Update the Set input fields for candidate resume, keywords and other filtering criteria's.
  Update the Webhook HTTP Request node with the Webhook endpoint of your choice.
  Update the file name and path to persist on disk.

  How to customize this workflow to your needs

  Target Different Job Boards

  Set input fields with the sites like Indeed, ZipRecruiter, or Monster

  Customize Matching Criteria
  Adjust the prompt inside the AI Job Match node

  Include scoring metrics like skills match %, experience relevance, or cultural fit

  Automate Scheduling
  Use a Cron Node to periodically check for new jobs matching a profile

  Set triggers based on webhook or input form submissions

  Output Customization
  Add Markdown/PDF formatting for report summaries

  Extend with Google Sheets export for internal analytics

  Enhance Data Security
  Mask personal info before sending to external endpoints

nodes_used:
  ["n8n-nodes-base.httpRequest","@n8n/n8n-nodes-langchain.chainLlm","@n8n/n8n-nodes-langchain.lmChatOpenAi","@n8n/n8n-nodes-langchain.outputParserStructured","@n8n/n8n-nodes-langchain.informationExtractor"]

workflow_json:
  {"id":"gIdIv8qN7zruqLbG","meta":{"instanceId":"885b4fb4a6a9c2cb5621429a7b972df0d05bb724c20ac7dac7171b62f1c7ef40","templateCredsSetupCompleted":true},"name":"Automated Resume Job Matching Engine with Bright Data & OpenAI 4o mini","tags":[{"id":"Kujft2FOjmOVQAmJ","name":"Engineering","createdAt":"2025-04-09T01:31:00.558Z","updatedAt":"2025-04-09T01:31:00.558Z"},{"id":"ZOwtAMLepQaGW76t","name":"Building Blocks","createdAt":"2025-04-13T15:23:40.462Z","updatedAt":"2025-04-13T15:23:40.462Z"},{"id":"ddPkw7Hg5dZhQu2w","name":"AI","createdAt":"2025-04-13T05:38:08.053Z","updatedAt":"2025-04-13T05:38:08.053Z"},{"id":"rKOa98eAi3IETrLu","name":"HR","createdAt":"2025-04-13T04:59:30.580Z","updatedAt":"2025-04-13T04:59:30.580Z"}],"nodes":[{"id":"a75e1f8d-9dd4-4c87-b1ab-05c502b8cae7","name":"Loop Over Items","type":"n8n-nodes-base.splitInBatches","position":[736,115],"parameters":{"options":{}},"typeVersion":3},{"id":"92f0272d-dc5d-4424-9d96-cc2521e8a4ae","name":"When clicking ‘Test workflow’","type":"n8n-nodes-base.manualTrigger","position":[-740,115],"parameters":{},"typeVersion":1},{"id":"3820c9d3-be68-4a60-a810-943a9795bdbd","name":"List all tools for Bright Data","type":"n8n-nodes-mcp.mcpClient","position":[-520,115],"parameters":{},"credentials":{"mcpClientApi":{"id":"JtatFSfA2kkwctYa","name":"MCP Client (STDIO) account"}},"typeVersion":1},{"id":"83219c20-7341-4e42-8cae-cc2e1e8e9b8e","name":"Set the Input fields","type":"n8n-nodes-base.set","position":[-300,115],"parameters":{"options":{},"assignments":{"assignments":[{"id":"214e61a0-3587-453f-baf5-eac013990857","name":"resume","type":"string","value":"I am Pechi, Senior Python Developer with 9+ years of experience."},{"id":"98c64f52-1564-4889-811d-39cac3951cc3","name":"keywords","type":"string","value":"Python"},{"id":"34202143-4b07-4301-b5e9-767430952214","name":"location","type":"string","value":"India"},{"id":"47d01515-302b-4a91-b9db-3af0033a56e1","name":"job_search_base_url","type":"string","value":"https://www.linkedin.com/jobs/search/"}]}},"typeVersion":3.4},{"id":"40a70c2b-5dcc-44f7-8fde-9c28748181cd","name":"Bright Data MCP Client For Jobs Extraction","type":"n8n-nodes-mcp.mcpClient","notes":"Scrape a single webpage URL with advanced options for content extraction and get back the results in MarkDown language.","position":[-80,115],"parameters":{"toolName":"scrape_as_html","operation":"executeTool","toolParameters":"={\n   \"url\": \"{{ $json.job_search_base_url }}?keywords={{ $json.keywords }}&location={{ $json.location }}\"\n} "},"credentials":{"mcpClientApi":{"id":"JtatFSfA2kkwctYa","name":"MCP Client (STDIO) account"}},"notesInFlow":true,"typeVersion":1},{"id":"ff3193e5-cd22-40f4-8180-b76ad32055b3","name":"Split Out","type":"n8n-nodes-base.splitOut","position":[516,115],"parameters":{"options":{},"fieldToSplitOut":"output"},"typeVersion":1},{"id":"cd1fcbd8-acf3-4a91-8158-f664aaa839e7","name":"Bright Data MCP Client For Jobs Extraction within a Loop","type":"n8n-nodes-mcp.mcpClient","notes":"Scrape a single webpage URL with advanced options for content extraction and get back the results in MarkDown language.","position":[956,-10],"parameters":{"toolName":"scrape_as_html","operation":"executeTool","toolParameters":"={\n   \"url\": \"{{ $json.output }}\"\n} "},"credentials":{"mcpClientApi":{"id":"JtatFSfA2kkwctYa","name":"MCP Client (STDIO) account"}},"notesInFlow":true,"typeVersion":1},{"id":"d9f78a12-9eaa-4d9b-9e5c-5150d6e40e95","name":"Job Desc Information Extractor","type":"@n8n/n8n-nodes-langchain.informationExtractor","position":[1176,-10],"parameters":{"text":"=Extract the job description in a textual format\n\nHere's the content: {{ $json.result.content[0].text }}","options":{},"attributes":{"attributes":[{"name":"job_description","description":"Job Description"}]}},"retryOnFail":true,"typeVersion":1},{"id":"4636d7e9-8d13-4f57-95f9-936f6d8bbf1d","name":"AI Job Match","type":"@n8n/n8n-nodes-langchain.chainLlm","position":[1552,-10],"parameters":{"text":"=Hi, you are a helpful job matcher, you analyze the given resume and job description and providing a job matching skills and score in a JSON format.\n\nHere's the Resume:\n{{ $('Set the Input fields').item.json.resume }}\n\nHere's the Job Desc:\n\n{{ $json.output.job_description }}","promptType":"define","hasOutputParser":true},"retryOnFail":true,"typeVersion":1.6},{"id":"51b5d9dd-b0c8-4aaf-b789-f96e94519b94","name":"Structured Output Parser","type":"@n8n/n8n-nodes-langchain.outputParserStructured","position":[1720,200],"parameters":{"jsonSchemaExample":"{\n  \"job_match_analysis\": {\n    \"resume_summary\": \"Senior Python Developer with 9+ years of experience.\",\n    \"job_description_summary\": \"Seeking a developer with expertise in Sagemaker, Python, and LLM. The role involves client interaction, requirements understanding, design review, architecture validation, and team leadership.\",\n    \"skill_match\": [\n      {\n        \"skill\": \"python\",\n        \"resume\": \"Strong match - explicitly mentioned as core skill.\",\n        \"job_description\": \"Strong match - listed as a primary skill.\",\n        \"score\": 100\n      },\n      {\n        \"skill\": \"sagemaker\",\n        \"resume\": \"No match - not mentioned in the resume.\",\n        \"job_description\": \"Strong match - listed as a primary skill.\",\n        \"score\": 0\n      },\n      {\n        \"skill\": \"llm\",\n        \"resume\": \"No match - not mentioned in the resume.\",\n        \"job_description\": \"Strong match - listed as a primary skill.\",\n        \"score\": 0\n      },\n      {\n        \"skill\": \"leadership\",\n        \"resume\": \"Implicit match - Senior role implies leadership experience.\",\n        \"job_description\": \"Explicit match - requires leading and guiding teams.\",\n        \"score\": 75\n      },\n      {\n        \"skill\": \"client_interaction\",\n        \"resume\": \"No explicit mention, inferred from senior role.\",\n        \"job_description\": \"Explicit match - requires interfacing with clients.\",\n        \"score\": 50\n      }\n    ],\n    \"overall_match_score\": 45,\n    \"rationale\": \"The candidate's core skill (Python) is a strong match. The resume implies leadership skills, aligning with the job's team leadership requirements. However, the absence of Sagemaker and LLM experience significantly lowers the overall score. The candidate needs to demonstrate experience in these areas for a higher match.\",\n    \"recommendations\": [\n      \"Highlight any experience (even if limited) with Sagemaker or LLMs in the resume.\",\n      \"Quantify Python experience with specific projects and technologies used.\",\n      \"Emphasize any client-facing experience or responsibilities in previous roles.\",\n      \"Showcase leadership experience with specific examples (e.g., mentoring junior developers, leading project teams).\"\n    ]\n  }\n}\n"},"typeVersion":1.2},{"id":"1dcb1ca7-e4e9-4775-9eb8-94c9e1f89e64","name":"Create a binary data for AI Job Match","type":"n8n-nodes-base.function","position":[1928,-60],"parameters":{"functionCode":"items[0].binary = {\n  data: {\n    data: new Buffer(JSON.stringify(items[0].json, null, 2)).toString('base64')\n  }\n};\nreturn items;"},"typeVersion":1},{"id":"da19ddc2-5e0f-4a4a-b524-1086b59c511f","name":"Webhook Notification for AI Job Match","type":"n8n-nodes-base.httpRequest","position":[1928,215],"parameters":{"url":"https://webhook.site/7b5380a0-0544-48dc-be43-0116cb2d52c2","options":{},"sendBody":true,"contentType":"multipart-form-data","bodyParameters":{"parameters":[{"name":"job_match_response","value":"={{ $json.output.job_match_analysis.toJsonString() }}"}]}},"typeVersion":4.2},{"id":"0561839e-9ca9-4c18-9a9e-98b9a1f796fc","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[640,-320],"parameters":{"width":440,"height":120,"content":"## Disclaimer\nThis template is only available on n8n self-hosted as it's making use of the community node for MCP Client."},"typeVersion":1},{"id":"d68fd51a-d74f-4236-89e1-6144f9e80943","name":"Sticky Note4","type":"n8n-nodes-base.stickyNote","position":[-300,-140],"parameters":{"color":5,"width":440,"height":220,"content":"## LLM Usages\n\nOpenAI 4o mini LLM is being utilized for the structured data extraction handling."},"typeVersion":1},{"id":"29342cc1-10dd-490c-b274-fd5a82dbae1e","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[640,-160],"parameters":{"color":3,"width":1660,"height":620,"content":"## Bright Data MCP Job Extract via Job Listings\nExtract job information via BrightData MCP and then perform the AI Job matching by utilizing the OpenAI GPT 4o mini LLM"},"typeVersion":1},{"id":"25d7b451-0f5e-4694-a821-ea7fe93b7d6f","name":"Sticky Note5","type":"n8n-nodes-base.stickyNote","position":[-740,-700],"parameters":{"color":7,"width":400,"height":400,"content":"## Logo\n\n\n![logo](https://images.seeklogo.com/logo-png/43/1/brightdata-logo-png_seeklogo-439974.png)\n"},"typeVersion":1},{"id":"02e69f64-f7b4-4a0d-828c-3fcea324268e","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[-740,-240],"parameters":{"width":400,"height":320,"content":"## Note\n\nDeals with the LinkedIn profile data extraction by utilizing the Bright Data MCP and OpenAI GPT 4o LLM.\n\n**Please make sure to set the input fields node with the LinkedIn profile URL with the resume, location, keywords etc.\n\nPlease make sure to update the Webhook Notification URL of your interest**"},"typeVersion":1},{"id":"cb84eebb-4215-4bb3-91f6-bf7897a8ddf6","name":"OpenAI Chat Model for Job Desc Extract","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[1264,210],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o-mini"},"options":{}},"credentials":{"openAiApi":{"id":"vPKynKbDzJ5ZU4cU","name":"OpenAi account"}},"typeVersion":1.2},{"id":"4d14c3a1-5402-4f27-beda-dba41c1aa912","name":"OpenAI Chat Model for AI Job Match","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[1560,200],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o-mini"},"options":{}},"credentials":{"openAiApi":{"id":"vPKynKbDzJ5ZU4cU","name":"OpenAi account"}},"typeVersion":1.2},{"id":"2aec37e7-a67b-47b1-b3b2-7ea7e114bfff","name":"Write the AI job matched response to disk","type":"n8n-nodes-base.readWriteFile","position":[2148,-60],"parameters":{"options":{},"fileName":"=d:\\Job-Match-{{$now.toSeconds()}}.json","operation":"write"},"typeVersion":1},{"id":"af980102-85d0-4f90-842f-196605f6bcd6","name":"Paginated Job Data Extractor","type":"@n8n/n8n-nodes-langchain.informationExtractor","position":[140,115],"parameters":{"text":"=Extract all the job links from the provided content. \n\nHere's the content:  {{ $json.result.content[0].text }}","options":{},"schemaType":"manual","inputSchema":"{\n\t\"type\": \"array\",\n\t\"properties\": {\n\t\t\"link\": {\n\t\t\t\"type\": \"string\"\n\t\t}\n\t}\n}"},"retryOnFail":true,"typeVersion":1},{"id":"cb8e32c9-c1ac-4441-a42a-42e6b0d78970","name":"OpenAI Chat Model for Paginated Job Extract","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[228,335],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o-mini"},"options":{}},"credentials":{"openAiApi":{"id":"vPKynKbDzJ5ZU4cU","name":"OpenAi account"}},"typeVersion":1.2}],"active":false,"pinData":{},"settings":{"executionOrder":"v1"},"versionId":"b366450e-b10e-412e-b442-a0827ca430bb","connections":{"Split Out":{"main":[[{"node":"Loop Over Items","type":"main","index":0}]]},"AI Job Match":{"main":[[{"node":"Create a binary data for AI Job Match","type":"main","index":0},{"node":"Webhook Notification for AI Job Match","type":"main","index":0}]]},"Loop Over Items":{"main":[[],[{"node":"Bright Data MCP Client For Jobs Extraction within a Loop","type":"main","index":0}]]},"Set the Input fields":{"main":[[{"node":"Bright Data MCP Client For Jobs Extraction","type":"main","index":0}]]},"Structured Output Parser":{"ai_outputParser":[[{"node":"AI Job Match","type":"ai_outputParser","index":0}]]},"Paginated Job Data Extractor":{"main":[[{"node":"Split Out","type":"main","index":0}]]},"Job Desc Information Extractor":{"main":[[{"node":"AI Job Match","type":"main","index":0}]]},"List all tools for Bright Data":{"main":[[{"node":"Set the Input fields","type":"main","index":0}]]},"When clicking ‘Test workflow’":{"main":[[{"node":"List all tools for Bright Data","type":"main","index":0}]]},"OpenAI Chat Model for AI Job Match":{"ai_languageModel":[[{"node":"AI Job Match","type":"ai_languageModel","index":0}]]},"Create a binary data for AI Job Match":{"main":[[{"node":"Write the AI job matched response to disk","type":"main","index":0}]]},"Webhook Notification for AI Job Match":{"main":[[{"node":"Loop Over Items","type":"main","index":0}]]},"OpenAI Chat Model for Job Desc Extract":{"ai_languageModel":[[{"node":"Job Desc Information Extractor","type":"ai_languageModel","index":0}]]},"Write the AI job matched response to disk":{"main":[[]]},"Bright Data MCP Client For Jobs Extraction":{"main":[[{"node":"Paginated Job Data Extractor","type":"main","index":0}]]},"OpenAI Chat Model for Paginated Job Extract":{"ai_languageModel":[[{"node":"Paginated Job Data Extractor","type":"ai_languageModel","index":0}]]},"Bright Data MCP Client For Jobs Extraction within a Loop":{"main":[[{"node":"Job Desc Information Extractor","type":"main","index":0}]]}}}


name: TradingView Signal Extractor with Gmail, Google Sheets & Telegram Notifications
author_name: Dhrumil Patel
author_username: itechdp
categories: []
created_at: 2025-05-23T07:57:01.872Z
updated_at: 2025-05-23T07:57:01.872Z
url: https://n8n.io/workflows/4334
scraped_at: 2025-06-19 22:49:03
description:
  Stay ahead in your trading game with this powerful n8n automation workflow. Designed for real-time efficiency, this setup continuously scans your Gmail inbox for trading alerts from TradingView and ensures you never miss a signal.

  Every minute, this workflow will:

  📩 Check Gmail for new messages using a trigger.
  🔍 Identify emails coming specifically from TradingView.
  📊 Extract key trading signals like BUY or SELL along with the company name.
  🕒 Capture the exact date and time of the alert.
  📄 Log all extracted signals neatly into a Google Sheet for easy tracking and analysis.
  📲 Instantly notify you on Telegram with a custom message so you can act fast.

  Perfect for traders who want an automated assistant to handle alerts, record them for analysis, and provide timely updates — all without lifting a finger.

nodes_used:
  ["n8n-nodes-base.googleSheets","n8n-nodes-base.telegram","n8n-nodes-base.gmail","n8n-nodes-base.code"]

workflow_json:
  {"meta":{"instanceId":"761a3dddae2bb21eb8973ffca0ba97d5b4f499405873760164a536f547546882","templateCredsSetupCompleted":true},"nodes":[{"id":"a5f53559-6b91-45a9-8822-53439b9c306d","name":"Clean Email","type":"n8n-nodes-base.code","position":[-160,180],"parameters":{"jsCode":"// Make sure From exists and is a string\nconst rawFrom = $input.first().json.From;\n\nlet cleanEmail = \"\";\n\n// Proceed only if rawFrom is a valid string\nif (typeof rawFrom === \"string\" && rawFrom.trim() !== \"\") {\n  const match = rawFrom.match(/<(.+?)>/);\n  cleanEmail = match ? match[1] : rawFrom.trim();\n} else {\n  cleanEmail = \"[Missing From field]\";\n}\n\nreturn [\n  {\n    json: {\n      cleanEmail\n    }\n  }\n];\n"},"typeVersion":2},{"id":"e6a332b0-529d-489c-9d67-8d7d06bc8044","name":"Gmail","type":"n8n-nodes-base.gmail","position":[-160,-20],"webhookId":"0c25cbb3-b954-4c3a-aabc-9f4473b9f733","parameters":{"messageId":"={{ $json.id }}","operation":"markAsRead"},"credentials":{"gmailOAuth2":{"id":"6I8sq2IhPgySI6XX","name":"Gmail account 2 - infodpatel15"}},"typeVersion":2.1},{"id":"032629d7-d41b-4d8f-b545-e98df9cf796c","name":"Send Message","type":"n8n-nodes-base.telegram","position":[1380,180],"webhookId":"836270b1-beef-4520-b024-30b72af1582a","parameters":{"text":"=KITE 11: {{ $('Get Email').item.json.snippet }}","chatId":"1520681602","additionalFields":{}},"credentials":{"telegramApi":{"id":"bAaBU3SFXiLAdyvU","name":"Telegram account"}},"typeVersion":1.2},{"id":"f7e47b44-5ea8-43fa-9054-539e710d3a39","name":"Verify Mail","type":"n8n-nodes-base.if","position":[60,180],"parameters":{"options":{},"conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"7f6c2c11-6204-4f36-8e57-dcc9efc93433","operator":{"name":"filter.operator.equals","type":"string","operation":"equals"},"leftValue":"={{ $json.cleanEmail }}","rightValue":"=noreply@tradingview.com"}]}},"typeVersion":2.2},{"id":"66b91b39-49f7-44cc-8d9a-f4392c11ff77","name":"Extract Company Name","type":"n8n-nodes-base.code","position":[500,180],"parameters":{"jsCode":"// Get subject from previous node (e.g., IMAP Email node)\nconst subject = $input.first().json.Subject;\n\nconst stockSymbol = subject.split('for ')[1]?.trim() || '';\n\nreturn [\n  {\n    json: {\n      symbol: stockSymbol,\n      originalSubject: subject,\n    }\n  }\n];\n"},"typeVersion":2},{"id":"ffbbff24-1959-4254-b05c-4a6327edec95","name":"Google Sheets","type":"n8n-nodes-base.googleSheets","position":[1160,180],"parameters":{"columns":{"value":{"Date":"={{ $json.formattedDate }}","Stock":"={{ $('Extract Company Name').item.json.symbol }}"},"schema":[{"id":"Date","type":"string","display":true,"required":false,"displayName":"Date","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Stock","type":"string","display":true,"required":false,"displayName":"Stock","defaultMatch":false,"canBeUsedToMatch":true}],"mappingMode":"defineBelow","matchingColumns":[],"attemptToConvertTypes":false,"convertFieldsToString":false},"options":{},"operation":"append","sheetName":{"__rl":true,"mode":"list","value":"gid=0","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1PBvePZN2yvVg23hDIDB62e91ogTgbuNXVduZTai-bZc/edit#gid=0","cachedResultName":"Sheet1"},"documentId":{"__rl":true,"mode":"list","value":"1PBvePZN2yvVg23hDIDB62e91ogTgbuNXVduZTai-bZc","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1PBvePZN2yvVg23hDIDB62e91ogTgbuNXVduZTai-bZc/edit?usp=drivesdk","cachedResultName":"KITE FINAL 11"}},"credentials":{"googleSheetsOAuth2Api":{"id":"9NecV5qrcx7kjh5f","name":"Google Sheets account 2"}},"typeVersion":4.5},{"id":"dde99d76-79fe-4650-b7a2-948047b62a16","name":"Current Date & Time","type":"n8n-nodes-base.dateTime","position":[720,180],"parameters":{"options":{"timezone":"Asia/kolkata"}},"typeVersion":2},{"id":"7a60d22e-8027-423c-9927-aa2e0759744d","name":"Formatted Date & Time","type":"n8n-nodes-base.dateTime","position":[940,180],"parameters":{"date":"={{ $json.currentDate }}","format":"custom","options":{},"operation":"formatDate","customFormat":"DD"},"typeVersion":2},{"id":"288dec30-51c9-4206-a0d8-5bca9317ec57","name":"Get Email","type":"n8n-nodes-base.gmail","position":[300,180],"webhookId":"1fd0763d-5989-4fc4-aa5f-191eb8ee51bc","parameters":{"messageId":"={{ $('Email Received').item.json.id }}","operation":"get"},"credentials":{"gmailOAuth2":{"id":"6I8sq2IhPgySI6XX","name":"Gmail account 2 - infodpatel15"}},"typeVersion":2.1},{"id":"20ac9cda-60e1-4a52-a41d-e83485f2c76f","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[-400,-80],"parameters":{"color":7,"width":380,"height":400,"content":"## Read Emails"},"typeVersion":1},{"id":"9a8cae5e-9601-4500-bde6-8a84837fc378","name":"Email Received","type":"n8n-nodes-base.gmailTrigger","position":[-380,80],"parameters":{"filters":{},"pollTimes":{"item":[{"mode":"everyMinute"}]}},"credentials":{"gmailOAuth2":{"id":"6I8sq2IhPgySI6XX","name":"Gmail account 2 - infodpatel15"}},"typeVersion":1.2},{"id":"ff7bbb0d-29a1-458d-8437-089fb0bb4ef4","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[20,120],"parameters":{"color":7,"width":180,"height":200,"content":"## Identify Email"},"typeVersion":1},{"id":"70ed236c-3d55-48ec-884c-8bf707139f61","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[240,80],"parameters":{"color":7,"width":400,"height":260,"content":"## Get Email Data - Extract Buy or Sell Signal"},"typeVersion":1},{"id":"a86e1c5f-9059-4971-835c-3e39dc176a3e","name":"Sticky Note3","type":"n8n-nodes-base.stickyNote","position":[660,120],"parameters":{"color":7,"width":440,"height":220,"content":"## Get Current Date & Time"},"typeVersion":1},{"id":"84d9bbe3-ebe6-4edb-b02b-f37c3dfdabdf","name":"Sticky Note4","type":"n8n-nodes-base.stickyNote","position":[1120,120],"parameters":{"color":7,"width":420,"height":220,"content":"## Update Data On Sheet & Notify"},"typeVersion":1}],"pinData":{},"connections":{"Get Email":{"main":[[{"node":"Extract Company Name","type":"main","index":0}]]},"Clean Email":{"main":[[{"node":"Verify Mail","type":"main","index":0}]]},"Verify Mail":{"main":[[{"node":"Get Email","type":"main","index":0}]]},"Send Message":{"main":[[]]},"Google Sheets":{"main":[[{"node":"Send Message","type":"main","index":0}]]},"Email Received":{"main":[[{"node":"Gmail","type":"main","index":0},{"node":"Clean Email","type":"main","index":0}]]},"Current Date & Time":{"main":[[{"node":"Formatted Date & Time","type":"main","index":0}]]},"Extract Company Name":{"main":[[{"node":"Current Date & Time","type":"main","index":0}]]},"Formatted Date & Time":{"main":[[{"node":"Google Sheets","type":"main","index":0}]]}}}


name: Webhook-enabled AI PDF analyzer
author_name: n8n Team
author_username: n8n-team
categories: []
created_at: 2025-05-23T09:04:13.777Z
updated_at: 2025-05-23T09:04:13.777Z
url: https://n8n.io/workflows/4336
scraped_at: 2025-06-19 22:49:42
description:
  Who this template is for

  This template is for researchers, students, professionals, or content creators who need to quickly extract and summarize key insights from PDF documents using AI-powered analysis.

  Use case

  Converting lengthy PDF documents into structured, digestible summaries organized by topic with key insights. This is particularly useful for processing research papers, reports, whitepapers, or any document where you need to quickly understand the main topics and extract actionable insights without reading the entire document.

  How this workflow works

  Document Upload: Receives PDF files through a POST endpoint at /ai_pdf_summariser
  File Validation: Checks that the PDF is under 10MB and has fewer than 20 pages to meet API limits
  Content Extraction: Extracts text content from the PDF file
  AI Analysis: Uses OpenAI's GPT-4o-mini to analyze the document and break it down into distinct topics
  Insight Generation: For each topic, generates 3 key insights with titles and detailed explanations
  Format Response: Converts the structured data into markdown format for easy reading
  Return Results: Provides the formatted summary along with document metadata (file hash)

  Set up steps

  Configure OpenAI API: Set up your OpenAI credentials for the GPT-4o-mini model
  Deploy Webhook: The workflow automatically creates a POST endpoint at /ai_pdf_summariser
  Test Upload: Send a PDF file to the endpoint using a multipart/form-data request
  Adjust Limits: Modify the file size (10MB) and page count (20) validation limits if needed based on your requirements
  Customize Prompts: Update the system prompt in the Information Extractor node to change how topics and insights are generated

  The workflow includes comprehensive error handling for file validation failures (400 error) and processing errors (500 error), ensuring reliable operation even with problematic documents.

nodes_used:
  ["n8n-nodes-base.crypto","n8n-nodes-base.code","@n8n/n8n-nodes-langchain.lmChatOpenAi","@n8n/n8n-nodes-langchain.informationExtractor"]

workflow_json:
  {"meta":{"instanceId":"ff412ab2a6cd55af5dedbbab9b8e43f0f3a0cb16fb794fa8d3837f957b771ad2","templateCredsSetupCompleted":true},"nodes":[{"id":"505f25b4-eaa7-4d42-98d9-2154d7d4cc81","name":"File Ref","type":"n8n-nodes-base.noOp","position":[-1360,280],"parameters":{},"typeVersion":1},{"id":"59721669-a3a9-48ab-8cb0-29ea0af84f6d","name":"Success1","type":"n8n-nodes-base.respondToWebhook","onError":"continueRegularOutput","position":[620,-20],"parameters":{"options":{"responseCode":200,"responseHeaders":{"entries":[{"name":"Content-Type","value":"application/json"}]}},"respondWith":"json","responseBody":"={{\n{\n  \"error\": null,\n  \"meta\": {\n    \"hash\": $('Get File Hash').first().json.data,\n  },\n  \"result\": $json.response\n}\n}}"},"typeVersion":1.1},{"id":"16479572-c3a6-4127-9bf2-db7380bd734c","name":"Is Valid File?","type":"n8n-nodes-base.if","position":[-660,280],"parameters":{"options":{},"conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"a277fc5c-6873-49d5-b67b-39df0efc8a61","operator":{"type":"number","operation":"lte"},"leftValue":"={{ $('Get Filesize').item.json.filesize_in_bytes }}","rightValue":"={{ 10000000 }}"},{"id":"d908d5a9-3550-45ce-8645-19c08d3e5982","operator":{"type":"number","operation":"lte"},"leftValue":"={{ $json.numpages }}","rightValue":20}]}},"typeVersion":2.2},{"id":"d35868fb-2a0b-4f07-a942-216a8d226b46","name":"Get Filesize","type":"n8n-nodes-base.code","position":[-980,280],"parameters":{"mode":"runOnceForEachItem","jsCode":"function convertToBytes(size) {\n    const units = {\n        b: 1,\n        bytes: 1,\n        kb: 1024,\n        mb: 1024 * 1024,\n        gb: 1024 * 1024 * 1024,\n    };\n\n    // Extract the number and unit using regex\n    const regex = /([\\d.]+)\\s*(bytes|b|kb|mb|gb)/i;\n    const match = size.match(regex);\n\n    if (!match) {\n        throw new Error(`Invalid size format: \"${size}\"`);\n    }\n\n    const value = parseFloat(match[1]);\n    const unit = match[2].toLowerCase();\n\n    // Calculate the size in bytes\n    const factor = units[unit];\n    if (!factor) {\n        throw new Error(`Unsupported unit: \"${unit}\"`);\n    }\n\n    return Math.round(value * factor);\n}\n\nconst data = $('File Ref').first().binary.data;\n\nreturn {\n  json: { filesize_in_bytes: convertToBytes(data.fileSize) },\n  binary: { data }\n}"},"typeVersion":2},{"id":"87e6b82c-4099-4435-b47f-647ae0b97d39","name":"Extract from File","type":"n8n-nodes-base.extractFromFile","position":[-820,280],"parameters":{"options":{},"operation":"pdf"},"typeVersion":1},{"id":"e4f623cd-418b-49f1-bc1b-2e804a089617","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[-1040,140],"parameters":{"color":7,"width":720,"height":480,"content":"### 2. Validate PDF File\nWe need to add validation here to meet service limits of our LLM. Here, we need to get for filesize and number of pages. "},"typeVersion":1},{"id":"ece12347-4205-447a-85cd-298bfa7595e0","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[-280,-120],"parameters":{"color":7,"width":600,"height":480,"content":"### 3. Document Parsing with Gemini API \nGoogle Gemini is used to breakdown the PDF into topics and provide insights for each. The number of topics and insights are not set and can be variable."},"typeVersion":1},{"id":"c7197f2f-7ac9-4c97-bd58-859c1d0950f0","name":"Sticky Note4","type":"n8n-nodes-base.stickyNote","position":[340,-120],"parameters":{"color":7,"width":480,"height":280,"content":"### 5. Format Response\nFinally, we'll format the output to return the summary as markdown."},"typeVersion":1},{"id":"9ef4b032-de21-48bd-ad3a-fb1cf391fe77","name":"Information Extractor","type":"@n8n/n8n-nodes-langchain.informationExtractor","onError":"continueErrorOutput","position":[-180,40],"parameters":{"text":"=Document as follows:\n{{ $json.text }}","options":{"systemPromptTemplate":"You are a note-taking agent helping the user to summarise this PDF in note form. Breakdown the document into distinct topics and provide a 3 paragraph summary of each topic discussed in the document."},"schemaType":"manual","inputSchema":"{\n  \"type\": \"array\",\n  \"items\": {\n    \"type\": \"object\",\n     \"properties\": {\n       \"topic\": { \"type\": \"string\" },\n       \"insights\": {\n         \"type\": \"array\",\n         \"items\": {\n           \"type\": \"object\",\n           \"properties\": {\n             \"title\": { \"type\": \"string\" },\n             \"body\": { \"type\": \"string\" }\n           }\n         }\n       }\n     }\n  }\n}"},"typeVersion":1},{"id":"4d9f3117-972b-417b-9dee-4098bbd71102","name":"Format Response","type":"n8n-nodes-base.set","position":[440,-20],"parameters":{"options":{},"assignments":{"assignments":[{"id":"10335d9e-7e0a-4ee1-a275-71d2f75b6bba","name":"response","type":"string","value":"={{\n$json.output.map(item => {\nreturn\n`## ${item.topic}\n${item.insights.map(insight =>\n`- **${insight.title}**: ${insight.body}`\n).join('\\n')}\n`;\n}).join('\\n\\n');\n}}"}]}},"typeVersion":3.4},{"id":"db32ecb9-79d0-45ee-aced-05aca99c9f27","name":"400 Error","type":"n8n-nodes-base.respondToWebhook","position":[-480,440],"parameters":{"options":{"responseCode":400},"respondWith":"json","responseBody":"{\n  \"error\": \"Unable to parse document. Please ensure file is less than 10mb with maximum of 20 pages.\",\n  \"result\": []\n}"},"typeVersion":1.1},{"id":"61d6e5e7-dcd7-4cdc-82be-8fec58f26e5a","name":"500 Error","type":"n8n-nodes-base.respondToWebhook","position":[140,120],"parameters":{"options":{"responseCode":500},"respondWith":"json","responseBody":"{\n  \"error\": \"Unable to parse document. An unknown error occurred.\",\n  \"result\": []\n}"},"typeVersion":1.1},{"id":"732d7d7b-f7f5-4342-93b7-e8b49d381dfb","name":"Get File Hash","type":"n8n-nodes-base.crypto","disabled":true,"position":[-1180,280],"parameters":{"value":"={{ $('File Ref').first().binary }}"},"typeVersion":1},{"id":"e6221a49-d4d8-4aa5-bbd8-69b885ff7254","name":"POST /ai_pdf_summariser","type":"n8n-nodes-base.webhook","position":[-1520,280],"webhookId":"a452fbcb-c7c4-4c0b-b435-b1829d411e7a","parameters":{"path":"ai_pdf_summariser","options":{"ignoreBots":false},"httpMethod":"POST","responseMode":"responseNode"},"typeVersion":2},{"id":"3d605049-571f-45d2-b1ba-914f0c9d68f4","name":"Sticky Note9","type":"n8n-nodes-base.stickyNote","position":[-1680,140],"parameters":{"width":280,"height":100,"content":"### POST /ai_pdf_summariser\nCall this endpoint to upload a document for summarising."},"typeVersion":1},{"id":"d79d5cf3-2f7c-459c-9977-9e0a77ed8d7b","name":"OpenAI Chat Model1","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[-100,220],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o-mini"},"options":{}},"credentials":{"openAiApi":{"id":"pY9tCO8MgTcBYqdJ","name":"OpenAi account Tutorial from docs"}},"typeVersion":1.2}],"pinData":{},"connections":{"File Ref":{"main":[[{"node":"Get File Hash","type":"main","index":0}]]},"Get Filesize":{"main":[[{"node":"Extract from File","type":"main","index":0}]]},"Get File Hash":{"main":[[{"node":"Get Filesize","type":"main","index":0}]]},"Is Valid File?":{"main":[[{"node":"Information Extractor","type":"main","index":0}],[{"node":"400 Error","type":"main","index":0}]]},"Format Response":{"main":[[{"node":"Success1","type":"main","index":0}]]},"Extract from File":{"main":[[{"node":"Is Valid File?","type":"main","index":0}]]},"OpenAI Chat Model1":{"ai_languageModel":[[{"node":"Information Extractor","type":"ai_languageModel","index":0}]]},"Information Extractor":{"main":[[{"node":"Format Response","type":"main","index":0}],[{"node":"500 Error","type":"main","index":0}]]},"POST /ai_pdf_summariser":{"main":[[{"node":"File Ref","type":"main","index":0}]]}}}


name: Generate Qualified Leads from LinkedIn with Apify, GPT- 4, and Airtable
author_name: Javier Hita
author_username: javierhita
categories: []
created_at: 2025-05-23T09:34:15.179Z
updated_at: 2025-05-23T09:34:15.179Z
url: https://n8n.io/workflows/4340
scraped_at: 2025-06-19 22:49:36
description:
  Who is this for?

  This workflow is perfect for sales teams, business development professionals, recruitment agencies, and fractional CFO service providers who need to identify and qualify companies actively hiring. Whether you're prospecting for new clients, building a database of potential customers, or researching market opportunities, this automated solution saves hours of manual research while delivering high-quality, AI-analyzed leads.

  What problem is this workflow solving?

  Finding qualified prospects in the finance sector is time-consuming and often inefficient. Traditional methods involve:
  Manually browsing LinkedIn job postings for hours
  Difficulty distinguishing between genuine opportunities and recruitment spam
  Inconsistent lead categorization and qualification
  Risk of contacting the same companies multiple times
  Lack of structured data for sales team follow-up

  This workflow automates the entire lead generation process, from data collection to AI-powered qualification, ensuring you focus only on the most promising opportunities.

  What this workflow does

  This comprehensive lead generation system performs six key functions:

  Automated LinkedIn Job Scraping: Uses Apify's reliable LinkedIn Jobs Scraper to extract detailed job postings for finance positions, including company information, job descriptions, and contact details.

  Smart Data Processing: Removes duplicates, filters companies by size, and structures data for consistent analysis across all leads.

  Intelligent Lead Categorization: Compares new leads against your existing database to optimize processing and avoid duplicate work.

  AI-Powered Qualification: Leverages OpenAI's GPT-4 Mini to analyze each lead and determine:
     Company Category: Consumer companies, Fractional CFO services, Recruiting agencies, or Other
     Finance Role Validation: Confirms the position is genuinely finance-related
     Seniority Level: Entry, Mid, Senior, Director, or C-Level classification
     Job Summary: Concise description for quick sales team review

  Automated Database Management: Stores qualified leads in Airtable with comprehensive profiles, preventing duplicates while maintaining data integrity.

  Lead Scoring & Routing: Prioritizes leads based on processing status and qualification results for efficient sales team follow-up.

  Setup

  Prerequisites

  You'll need accounts for three services:

  Airtable** (Free tier supported) - For lead storage and management
  Apify** (14-day free trial available) - For LinkedIn job scraping
  OpenAI** (Pay-per-use) - For AI-powered lead analysis

  Step 1: Create Required Credentials

  Apify API Credential
  Sign up for an Apify account at apify.com
  Navigate to Settings → Integrations → API tokens
  Create a new API token
  In n8n, create a new Apify API credential with your token

  OpenAI API Credential
  Create an account at platform.openai.com
  Generate an API key in the API section
  In n8n, create a new OpenAI credential with your key

  Airtable Personal Access Token
  Go to airtable.com/create/tokens
  Create a personal access token with the following scopes:
     data.records:read
     data.records:write
     schema.bases:read
  In n8n, create a new Airtable Personal Access Token credential

  Step 2: Set Up Airtable Base

  Create a new Airtable base with the following structure:

  Table Name: Qualified Leads

  Required Fields:
  Company Name (Single line text)
  Job Title (Single line text) 
  Is Finance Job (Checkbox)
  Seniority Level (Single select: Entry, Mid, Senior, Director, C-Level)
  Company Category (Single select: Consumer, Recruiting, Fractional CFO, Other)
  Job Summary (Long text)
  Company LinkedIn (URL)
  Job Link (URL)
  Posted Date (Date)
  Location (Single line text)
  Industry (Single line text)
  Company Employees (Number)

  Step 3: Configure the Workflow

  Import the Workflow: Copy the JSON and import it into your n8n instance
  Update Credentials: Replace placeholder credential IDs with your actual credential IDs in:
     "Scrape LinkedIn Jobs" node (Apify credential)
     "OpenAI GPT-4 Mini" node (OpenAI credential) 
     "Save to Airtable" and "Get Existing Leads" nodes (Airtable credential)
  Configure Airtable Connection: Update the base ID and table ID in both Airtable nodes
  Set Search Parameters: In the "Edit Variables" node, configure:
     linkedinUrls: Your target LinkedIn job search URLs
     maxEmployees: Maximum company size filter (default: 200)
     batchSize: Processing batch size for API efficiency (default: 5)

  Step 4: Test the Workflow

  Start with a small test by setting count: 50 in the HTTP Request node
  Use a specific LinkedIn job search URL (e.g., "CFO jobs in New York")
  Execute the workflow manually and verify results in your Airtable base
  Review the AI categorization accuracy and adjust prompts if needed

  How to customize this workflow to your needs

  Targeting Different Roles
  Modify the LinkedIn search URLs in the "Edit Variables" node to target different positions:
  "https://www.linkedin.com/jobs/search/?keywords=Controller"
  "https://www.linkedin.com/jobs/search/?keywords=Finance%20Director"  
  "https://www.linkedin.com/jobs/search/?keywords=VP%20Finance"

  Adjusting Company Size Filters
  Change the maxEmployees parameter to focus on different company segments:
  Startups: 1-50 employees
  SMBs: 51-500 employees  
  Enterprise: 500+ employees

  Customizing AI Analysis
  Enhance the GPT-4 prompt in the "AI Lead Analyzer" node to include:
  Industry-specific criteria
  Geographic preferences
  Technology stack requirements
  Company growth stage indicators

  Integration Options
  Extend the workflow by adding:
  Slack notifications** for new qualified leads
  Email alerts** for high-priority prospects
  CRM integration** (Salesforce, HubSpot, Pipedrive)
  Lead enrichment** with additional data sources

  Scheduling Automation
  Set up the workflow to run automatically:
  Daily**: For active prospecting campaigns
  Weekly**: For ongoing market research
  Monthly**: For periodic database updates

  Performance & Cost Optimization

  API Efficiency**: The workflow processes leads in batches to optimize API usage
  Smart Deduplication**: Avoids re-processing existing leads to reduce costs
  Configurable Limits**: Adjust batch sizes and employee count filters based on your needs
  Expected Costs**: Approximately $0.05-$0.20 per 100 analysed leads (OpenAI costs)

  Troubleshooting

  Common Issues:
  Rate Limiting**: Increase delays between API calls if you encounter rate limits
  Data Quality**: Review LinkedIn search URLs for relevance to your target market
  AI Accuracy**: Adjust prompts if categorisation doesn't match your criteria
  Airtable Errors**: Verify field names match exactly between workflow and base structure

  Support Resources:
  Apify LinkedIn Scraper Documentation
  OpenAI API Documentation
  Airtable API Reference

  Transform your lead generation process with this powerful, AI-driven workflow that delivers qualified prospects ready for immediate outreach.

nodes_used:
  ["n8n-nodes-base.airtable","n8n-nodes-base.httpRequest","n8n-nodes-base.code","@n8n/n8n-nodes-langchain.agent","@n8n/n8n-nodes-langchain.lmChatOpenAi","@n8n/n8n-nodes-langchain.outputParserStructured"]

workflow_json:
  {"meta":{"instanceId":"enhanced_workflow_instance"},"name":"Generate Qualified Finance Leads from LinkedIn with Apify, GPT-4, and Airtable","tags":[],"nodes":[{"id":"398b747b-1340-43b7-9c9e-49cd948711b4","name":"Start","type":"n8n-nodes-base.manualTrigger","position":[80,520],"parameters":{},"typeVersion":1},{"id":"edit-variables-node","name":"Edit Variables","type":"n8n-nodes-base.set","position":[260,520],"parameters":{"options":{},"assignments":{"assignments":[{"id":"config_linkedin_urls","name":"linkedinUrls","type":"string","value":"https://www.linkedin.com/jobs/search/?keywords=CFO&location=United%20States"},{"id":"config_max_employees","name":"maxEmployees","type":"number","value":200},{"id":"config_batch_size","name":"batchSize","type":"number","value":5}]}},"typeVersion":3.4},{"id":"87b76690-123f-4bce-ba3f-4752b143276a","name":"Scrape LinkedIn Jobs","type":"n8n-nodes-base.httpRequest","position":[420,520],"parameters":{"url":"https://api.apify.com/v2/acts/curious_coder~linkedin-jobs-scraper/run-sync-get-dataset-items","method":"POST","options":{},"jsonBody":"{\n    \"count\": 750,\n    \"scrapeCompany\": true,\n    \"urls\": [\n        \"{{ $('Edit Variables').item.json.linkedinUrls }}\"\n    ]\n}","sendBody":true,"specifyBody":"json","authentication":"predefinedCredentialType","nodeCredentialType":"apifyApi"},"typeVersion":4.2},{"id":"1878c155-6e6d-4600-ae4c-defca1acc6a1","name":"Split Job Data","type":"n8n-nodes-base.splitOut","position":[600,520],"parameters":{"include":"selectedOtherFields","options":{},"fieldToSplitOut":"companyName","fieldsToInclude":"title, link, descriptionText, postedAt, companyLinkedinUrl, jobPosterName, seniorityLevel, industries, companyEmployeesCount, location, jobPosterProfileUrl"},"typeVersion":1},{"id":"2dc5487e-dec2-42c6-84fd-96bb8d4c3955","name":"Remove Duplicates","type":"n8n-nodes-base.removeDuplicates","position":[820,520],"parameters":{"compare":"selectedFields","options":{},"fieldsToCompare":"companyName"},"typeVersion":2},{"id":"b8fde371-32bc-473e-be51-9927a5c0d660","name":"Clean Data Format","type":"n8n-nodes-base.set","position":[1100,520],"parameters":{"options":{},"assignments":{"assignments":[{"id":"7e3c28ee-e9bc-4e13-9615-f6a339d53f40","name":"company_name","type":"string","value":"={{ $json.companyName }}"},{"id":"51697efd-3564-48e8-b7c6-442a819d37a7","name":"title","type":"string","value":"={{ $json.title }}"},{"id":"23ff3936-c963-485c-8576-7aae534f8758","name":"job_link","type":"string","value":"={{ $json.link }}"},{"id":"52ae4935-d361-43ae-aa76-ffc1d8e184ff","name":"description","type":"string","value":"={{ $json.descriptionText }}"},{"id":"e5f9077c-71a3-41dd-91b2-d7e187b56ba1","name":"posted_at","type":"string","value":"={{ $json.postedAt }}"},{"id":"39ef0ce0-718b-47b1-8138-0bf2246fba51","name":"company_link","type":"string","value":"={{ $json.companyLinkedinUrl }}"},{"id":"d4559f9b-e602-42f6-ba8d-05d0e4332a89","name":"job_poster","type":"string","value":"={{ $json.jobPosterName }}"},{"id":"24590a98-f2d3-437a-b656-8538ce961b43","name":"seniority_level","type":"string","value":"={{ $json.seniorityLevel }}"},{"id":"bc1eecff-0570-4c0f-ac5b-a5d7f5c53ec0","name":"industry","type":"string","value":"={{ $json.industries }}"},{"id":"e0070649-5261-482f-9c09-fa54689e7659","name":"company_employees","type":"number","value":"={{ $json.companyEmployeesCount }}"},{"id":"02c838e5-8977-47c0-bdd7-31bbe9166ed9","name":"location","type":"string","value":"={{ $json.location }}"},{"id":"0973a0ab-d251-4ef0-ba71-ad19d8cce744","name":"jobposter_profile","type":"string","value":"={{ $json.jobPosterProfileUrl }}"}]}},"typeVersion":3.4},{"id":"afda4d35-13d0-4cda-9cb9-4a2286b9b184","name":"Get Existing Leads","type":"n8n-nodes-base.airtable","position":[80,780],"parameters":{"base":{"__rl":true,"mode":"list","value":"YOUR_AIRTABLE_BASE_ID"},"table":{"__rl":true,"mode":"list","value":"YOUR_AIRTABLE_TABLE_ID"},"options":{"fields":["company_name","jobposter_profile","company_link","company_category","job_summary"]},"operation":"search"},"executeOnce":true,"typeVersion":2.1},{"id":"677427b0-7d4e-4d9d-b429-c30325737106","name":"Categorize Leads","type":"n8n-nodes-base.code","position":[360,780],"parameters":{"jsCode":"// Lead deduplication and categorization logic\nconst existingLeads = $('Get Existing Leads').all().map(i => i.json);\nconst newLeads = $('Clean Data Format').all().map(i => i.json);\n\nreturn newLeads.map(lead => {\n  const match = existingLeads.find(existing =>\n    existing.company_name?.toLowerCase().trim() === lead.company_name?.toLowerCase().trim()\n  );\n\n  const existingSummary = match?.job_summary ?? '';\n  const existingJobPoster = match?.jobposter_profile ?? '';\n\n  const isSummaryMissing = existingSummary.trim() === '';\n  const isJobPosterMissing = existingJobPoster.trim() === '';\n\n  let category;\n  let processingReason = '';\n\n  if (!match || isSummaryMissing) {\n    category = 1;\n    processingReason = !match ? 'New company lead' : 'Existing lead missing AI analysis';\n  } else if (isJobPosterMissing) {\n    category = 2;\n    processingReason = 'Lead ready for enrichment';\n  } else {\n    category = 3;\n    processingReason = 'Complete lead - already processed';\n  }\n\n  return {\n    ...lead,\n    category,\n    processingReason,\n    isExistingLead: !!match\n  };\n});"},"typeVersion":2},{"id":"9a6b3cde-c69a-44a4-8540-2487aeecfbb2","name":"Route Leads","type":"n8n-nodes-base.switch","position":[1080,780],"parameters":{"rules":{"values":[{"outputKey":"New Leads","conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"e02f6478-e7bf-428c-8350-1f463062743c","operator":{"type":"number","operation":"equals"},"leftValue":"={{ $json.category }}","rightValue":1}]},"renameOutput":true},{"outputKey":"Incomplete Leads","conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"02aae098-3b8b-46fa-9917-de8d5d9af1f5","operator":{"type":"number","operation":"equals"},"leftValue":"={{ $json.category }}","rightValue":2}]},"renameOutput":true},{"outputKey":"Existing Leads","conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"9fbed109-bbcf-455a-bcb4-ef084b2a92da","operator":{"type":"number","operation":"equals"},"leftValue":"={{ $json.category }}","rightValue":3}]},"renameOutput":true}]},"options":{}},"typeVersion":3.2},{"id":"e2e6007c-7516-4cc0-b9fb-95177b325ed6","name":"Filter by Company Size","type":"n8n-nodes-base.filter","position":[1560,440],"parameters":{"options":{},"conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"70a23b0e-95ea-4f8a-97d2-4e99286aee51","operator":{"type":"number","operation":"lt"},"leftValue":"={{ $json.company_employees }}","rightValue":"={{ $('Edit Variables').item.json.maxEmployees }}"}]}},"typeVersion":2.2},{"id":"2da665f1-7988-4d00-bf3f-27ac773bdbb1","name":"Process in Batches","type":"n8n-nodes-base.splitInBatches","position":[1980,440],"parameters":{"options":{},"batchSize":"={{ $('Edit Variables').item.json.batchSize }}"},"typeVersion":3},{"id":"7c5374bf-e25c-4230-bb8d-93003584912c","name":"AI Lead Analyzer","type":"@n8n/n8n-nodes-langchain.agent","position":[2340,460],"parameters":{"text":"=You are a professional lead qualification assistant specializing in finance and accounting roles.\n\nAnalyze this job posting:\nCompany: {{ $json.company_name }}\nJob Title: {{ $json.title }}\nDescription: {{ $json.description }}\nCompany Link: {{ $json.company_link }}\n\nCategorize according to:\n\n1. Company Category:\n   - \"Consumer\": Companies hiring for their own operations\n   - \"Fractional CFO\": Companies providing fractional CFO services\n   - \"Recruiting\": Recruitment agencies\n   - \"Other\": None of the above\n\n2. Finance Job: Is this truly a finance-related position?\n\n3. Seniority Level: Entry, Mid, Senior, Director, C-Level\n\n4. Summary: One-line role description\n\nReturn JSON format only.","options":{},"promptType":"define","hasOutputParser":true},"executeOnce":false,"typeVersion":1.9},{"id":"a97f82fd-539f-44a5-a377-a39dfc155ee6","name":"OpenAI GPT-4 Mini","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[2340,160],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o-mini"},"options":{}},"typeVersion":1.2},{"id":"752cc07b-2148-432f-bef5-f7bf84444d10","name":"Structure AI Output","type":"@n8n/n8n-nodes-langchain.outputParserStructured","position":[2500,160],"parameters":{"jsonSchemaExample":"{\n    \"company_name\": \"TechCorp Inc\",\n    \"company_link\": \"https://linkedin.com/company/techcorp\",\n    \"seniority_level\": \"C-Level\",\n    \"is_finance_job\": true,\n    \"company_category\": \"Consumer\",\n    \"recap\": \"CFO role for financial strategy\"\n}"},"typeVersion":1.2},{"id":"58e36890-5c35-4ee8-9908-f8bdf5691c2b","name":"Save to Airtable","type":"n8n-nodes-base.airtable","position":[2800,460],"parameters":{"base":{"__rl":true,"mode":"list","value":"YOUR_AIRTABLE_BASE_ID"},"table":{"__rl":true,"mode":"list","value":"YOUR_AIRTABLE_TABLE_ID"},"columns":{"value":{"job_summary":"={{ $json.output.recap }}","company_link":"={{ $('Process in Batches').item.json.company_link }}","company_name":"={{ $('Process in Batches').item.json.company_name }}","is_finance_job":"={{ $json.output.is_finance_job }}","seniority_level":"={{ $json.output.seniority_level }}","company_category":"={{ $json.output.company_category }}"},"mappingMode":"defineBelow","matchingColumns":["company_name"]},"options":{},"operation":"upsert"},"typeVersion":2.1},{"id":"d2b3b56f-a0ef-44c2-b73f-5acdb3a51391","name":"Workflow Complete","type":"n8n-nodes-base.noOp","position":[1540,1140],"parameters":{},"typeVersion":1,"alwaysOutputData":true},{"id":"91825cfc-5906-4257-9f43-4cab81b1f34e","name":"Workflow Overview","type":"n8n-nodes-base.stickyNote","position":[0,0],"parameters":{"color":4,"width":1300,"height":400,"content":"## 🎯 Qualified Finance Lead Generation\n\n**Generate high-quality finance leads from LinkedIn**\n\n### Required:\n✅ Airtable (Free tier OK)\n✅ Apify (14-day trial) \n✅ OpenAI (Pay-per-use)\n\n### What it does:\n1. Scrapes LinkedIn finance jobs\n2. Filters by company size\n3. AI analyzes & categorizes\n4. Saves qualified leads to Airtable"},"typeVersion":1},{"id":"358381b4-7086-45db-a75d-76dec377bb18","name":"Data Collection","type":"n8n-nodes-base.stickyNote","position":[0,400],"parameters":{"color":5,"width":1300,"height":400,"content":"## 📊 Data Collection\n\n**LinkedIn Job Scraping**\n- Apify scraper for reliable data\n- Configurable search parameters\n- Company & job information\n\n**Data Processing**\n- Remove duplicates\n- Filter by company size\n- Clean data format"},"typeVersion":1},{"id":"83bfb584-0856-4df8-8ad6-68870c9302bf","name":"Lead Intelligence","type":"n8n-nodes-base.stickyNote","position":[0,800],"parameters":{"color":3,"width":1300,"height":520,"content":"## 🔄 Lead Intelligence\n\n**Smart Categorization**\n- Category 1: New leads (process with AI)\n- Category 2: Incomplete leads\n- Category 3: Complete leads (skip)\n\n**Benefits**\n- Reduces API costs\n- Avoids re-processing\n- Optimizes workflow efficiency"},"typeVersion":1},{"id":"0129e4dc-e119-4db8-9c46-8bb0db273626","name":"AI Qualification","type":"n8n-nodes-base.stickyNote","position":[1300,0],"parameters":{"color":6,"width":1800,"height":600,"content":"## 🤖 AI-Powered Qualification\n\n**GPT-4 Mini Analysis**\n- Company categorization\n- Finance role validation  \n- Seniority assessment\n- Job summarization\n\n**Structured Output**\n- JSON schema validation\n- Consistent data format\n- Ready for CRM integration"},"typeVersion":1}],"active":false,"pinData":{},"settings":{"executionOrder":"v1"},"versionId":"enhanced-linkedin-lead-gen-v2","connections":{"Start":{"main":[[{"node":"Edit Variables","type":"main","index":0}]]},"Route Leads":{"main":[[{"node":"Filter by Company Size","type":"main","index":0}],[{"node":"Workflow Complete","type":"main","index":0}],[{"node":"Workflow Complete","type":"main","index":0}]]},"Edit Variables":{"main":[[{"node":"Scrape LinkedIn Jobs","type":"main","index":0}]]},"Split Job Data":{"main":[[{"node":"Remove Duplicates","type":"main","index":0}]]},"AI Lead Analyzer":{"main":[[{"node":"Save to Airtable","type":"main","index":0}]]},"Categorize Leads":{"main":[[{"node":"Route Leads","type":"main","index":0}]]},"Save to Airtable":{"main":[[{"node":"Process in Batches","type":"main","index":0}]]},"Clean Data Format":{"main":[[{"node":"Get Existing Leads","type":"main","index":0}]]},"OpenAI GPT-4 Mini":{"ai_languageModel":[[{"node":"AI Lead Analyzer","type":"ai_languageModel","index":0}]]},"Remove Duplicates":{"main":[[{"node":"Clean Data Format","type":"main","index":0}]]},"Get Existing Leads":{"main":[[{"node":"Categorize Leads","type":"main","index":0}]]},"Process in Batches":{"main":[[],[{"node":"AI Lead Analyzer","type":"main","index":0}]]},"Structure AI Output":{"ai_outputParser":[[{"node":"AI Lead Analyzer","type":"ai_outputParser","index":0}]]},"Scrape LinkedIn Jobs":{"main":[[{"node":"Split Job Data","type":"main","index":0}]]},"Filter by Company Size":{"main":[[{"node":"Process in Batches","type":"main","index":0}]]}}}


name: AI-Powered Multi-Social Media Post Automation: Google Trends & Perplexity AI
author_name: Gerald Denor
author_username: dominixai
categories: []
created_at: 2025-05-24T00:42:22.300Z
updated_at: 2025-05-24T00:42:22.300Z
url: https://n8n.io/workflows/4352
scraped_at: 2025-06-19 22:48:37
description:
  Overview
  This comprehensive n8n workflow automatically transforms trending Google search queries into engaging LinkedIn posts using AI. The system runs autonomously, discovering viral topics, researching content, and publishing professionally formatted posts to grow your social media presence.

  Workflow Description
  Automate your entire social media content pipeline - from trend discovery to publication. This workflow monitors Google Trends, selects high-potential topics, creates human-like content using advanced AI, and publishes across multiple social platforms with built-in tracking.

  Key Features
  Automated Trend Discovery**: Pulls trending topics from Google Trends API with customizable filters
  Intelligent Topic Selection**: AI chooses the most relevant trending topic for your niche
  Multi-AI Content Generation**: Combines Perplexity for research and OpenAI for content curation
  Human-Like Writing**: Advanced prompts eliminate AI detection markers
  LinkedIn Optimization**: Proper formatting with Unicode characters, emojis, and engagement hooks
  Multi-Platform Support**: Ready for LinkedIn, Twitter/X, and Facebook posting
  Automated Scheduling**: Configurable posting times (default: 6 AM & 6 PM daily)
  Performance Tracking**: Automatic logging to Google Sheets with timestamps and metrics
  Error Handling**: Built-in delays and retry mechanisms for API stability

  Technical Implementation

  Workflow Architecture
  Schedule Trigger: Automated execution at specified intervals
  Google Trends API: Fetches trending search queries with geographical filtering
  Data Processing: JavaScript code node filters high-volume keywords (30+ search volume)
  Topic Selection: OpenAI GPT-3.5 evaluates and selects optimal trending topic
  Content Research: Perplexity AI researches selected topic for current information
  Content Generation: Advanced prompt engineering creates LinkedIn-optimized posts
  Content Distribution: Multi-platform posting with platform-specific formatting
  Analytics Tracking: Google Sheets integration for performance monitoring

  Node Breakdown
  Schedule Trigger**: Configurable timing for automated execution
  HTTP Request (Google Trends)**: SerpAPI integration for trend data
  Set Node**: Structures trending data for processing
  Code Node**: JavaScript filtering for high-volume keywords
  OpenAI Node**: Intelligent topic selection based on relevance and trend strength
  HTTP Request (Perplexity)**: Advanced AI research with anti-detection prompts
  Wait Node**: Rate limiting and API respect
  Split Out**: Prepares content for multi-platform distribution
  LinkedIn Node**: Authenticated posting with community management
  Google Sheets Node**: Automated tracking and analytics
  Social Media Nodes**: Twitter/X, LinkedIn and Facebook ready for activation

  Use Cases
  Content Creators**: Maintain consistent posting schedules with trending content
  Marketing Agencies**: Scale content creation across multiple client accounts
  Business Development**: Build thought leadership with timely industry insights
  Personal Branding**: Establish authority by commenting on trending topics
  SEO Professionals**: Create content around high-search-volume keywords

  Configuration Requirements

  API Integrations
  SerpAPI**: Google Trends data access
  Perplexity AI**: Advanced content research capabilities
  OpenAI**: Content curation and topic selection
  LinkedIn Community Management API**: Professional posting access
  Google Sheets API**: Analytics and tracking

  Authentication Setup
  LinkedIn OAuth2 community management credentials
  Google Sheets OAuth2 integration
  HTTP header authentication for AI services

  Customization Options
  Industry Targeting**: Modify prompts for specific business verticals
  Posting Schedule**: Adjust timing based on audience activity
  Content Tone**: Customize voice and style through prompt engineering
  Platform Selection**: Enable/disable specific social media channels
  Trend Filtering**: Adjust search volume thresholds and geographic targeting
  Content Length**: Modify character limits for different platforms

  Advanced Features
  Anti-AI Detection**: Sophisticated prompts create human-like content
  Rate Limit Management**: Built-in delays prevent API throttling
  Error Recovery**: Robust error handling with retry mechanisms
  Content Deduplication**: Prevents posting duplicate content
  Engagement Optimization**: LinkedIn-specific formatting for maximum reach

  Performance Metrics
  Time Savings**: Eliminates 10+ hours of weekly content creation
  Consistency**: Maintains regular posting schedule without manual intervention
  Relevance**: Content always based on current trending topics
  Engagement**: Optimized formatting increases social media interaction
  Scalability**: Single workflow manages multiple platform posting

  Installation Notes
  Import JSON workflow file into n8n instance
  Configure all required API credentials
  Set up Google Sheets tracking document
  Test workflow execution with manual trigger
  Enable schedule trigger for automated operation

  Best Practices
  Monitor API usage to stay within rate limits
  Regularly update prompts based on content performance
  Review and adjust trending topic filters for your niche
  Maintain backup of workflow configuration
  Test content output before enabling automation

  Support & Updates
  Comprehensive setup documentation included
  Configuration troubleshooting guide provided
  Regular workflow updates for API changes
  Community support through n8n forums

  Tags
  social-media content-automation linkedin ai-generation google-trends perplexity openai marketing trend-analysis content-creation

  Compatibility
  n8n Version: 1.0+
  Node Requirements: Standard n8n installation
  External Dependencies: API access to listed services
  Hosting: Compatible with cloud and self-hosted n8n instances

nodes_used:
  ["n8n-nodes-base.googleSheets","n8n-nodes-base.httpRequest","n8n-nodes-base.facebookGraphApi","n8n-nodes-base.twitter","n8n-nodes-base.linkedIn","n8n-nodes-base.code","@n8n/n8n-nodes-langchain.openAi"]

workflow_json:
  {"id":"vJw8YoQhdA5CXGeB","meta":{"instanceId":"f2cf6301a998e16084609c8635767c7f2fe71603e7ba21b5457aa517ce5164cb","templateCredsSetupCompleted":true},"name":"Social_media_post _automation_from_google_trends_and _perplexity copy","tags":[],"nodes":[{"id":"39b1272c-3700-4ce6-9aea-46b3a647fc26","name":"X1","type":"n8n-nodes-base.twitter","position":[-1500,0],"parameters":{"additionalFields":{}},"credentials":{"twitterOAuth2Api":{"id":"tNwQsAkmjk3b0Dp6","name":"X account"}},"typeVersion":2},{"id":"4bab1fd3-1c21-4438-8cc1-e0d0fdde390e","name":"Facebook Graph API1","type":"n8n-nodes-base.facebookGraphApi","position":[-1500,-400],"parameters":{"options":{},"httpRequestMethod":"POST"},"typeVersion":1},{"id":"ffcd9aa8-daef-41dc-8ad3-b9a55a817b8b","name":"LinkedIn1","type":"n8n-nodes-base.linkedIn","position":[-1480,-200],"parameters":{"text":"={{ $json['choices[0].message.content'] }}","person":"[CONFIGURE_YOUR_LINKEDIN_PERSON_ID]","authentication":"communityManagement","additionalFields":{}},"credentials":{"linkedInCommunityManagementOAuth2Api":{"id":null,"name":"[CONFIGURE_YOUR_LINKEDIN_CREDENTIALS]"}},"typeVersion":1},{"id":"a2c2c5e5-e9b1-4744-9883-c63cda3306c9","name":"Google Sheets2","type":"n8n-nodes-base.googleSheets","position":[-1280,-200],"parameters":{"columns":{"value":{"Topic":"={{ $('Choosing Topic').item.json.message.content }}","Status":"Posted","AI Output":"={{ $json['choices[0].message.content'] }}","Date Posted":"={{ $('Schedule Trigger').item.json.timestamp }}"},"schema":[{"id":"Topic","type":"string","display":true,"removed":false,"required":false,"displayName":"Topic","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Status","type":"string","display":true,"required":false,"displayName":"Status","defaultMatch":false,"canBeUsedToMatch":true},{"id":"AI Output","type":"string","display":true,"required":false,"displayName":"AI Output","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Date Posted","type":"string","display":true,"required":false,"displayName":"Date Posted","defaultMatch":false,"canBeUsedToMatch":true}],"mappingMode":"defineBelow","matchingColumns":["Topic"],"attemptToConvertTypes":false,"convertFieldsToString":false},"options":{},"operation":"appendOrUpdate","sheetName":{"__rl":true,"mode":"list","value":"gid=0","cachedResultUrl":"[YOUR_GOOGLE_SHEETS_URL]","cachedResultName":"Sheet1"},"documentId":{"__rl":true,"mode":"list","value":"[YOUR_GOOGLE_SHEETS_DOCUMENT_ID]","cachedResultUrl":"[YOUR_GOOGLE_SHEETS_URL]","cachedResultName":"LinkedIn Automation"}},"credentials":{"googleSheetsOAuth2Api":{"id":null,"name":"[CONFIGURE_YOUR_GOOGLE_SHEETS_CREDENTIALS]"}},"typeVersion":4.5},{"id":"51d3733a-004c-4938-9575-d227588140b7","name":"Split Out","type":"n8n-nodes-base.splitOut","position":[-1720,-200],"parameters":{"options":{},"fieldToSplitOut":"choices[0].message.content"},"typeVersion":1},{"id":"cc9b1e41-aaeb-43fb-a283-e3faf397cc73","name":"Schedule Trigger","type":"n8n-nodes-base.scheduleTrigger","position":[-3420,-200],"parameters":{"rule":{"interval":[{"triggerAtHour":6},{"triggerAtHour":18}]}},"typeVersion":1.2},{"id":"01d0a3b7-66db-4032-b7d7-7a7b273920a7","name":"Research Topic- Perplexity","type":"n8n-nodes-base.httpRequest","position":[-2160,-200],"parameters":{"url":"https://api.perplexity.ai/chat/completions","method":"POST","options":{},"jsonBody":"={\n  \"model\": \"sonar-pro\",\n  \"messages\": [\n    {\n      \"role\": \"system\",\n      \"content\": \"Act as a skilled editor revising AI-generated text to sound authentically human. Follow these rules:\\n\\n1. Punctuation Adjustments\\n   - Replace em dashes, semicolons, or rephrase sentences where appropriate.\\n   - Avoid semicolons in casual contexts; use periods or conjunctions (e.g., 'and,' 'but').\\n   - Remove mid-sentence ellipses unless mimicking deliberate hesitation.\\n   - Limit parenthetical asides; integrate explanations into the main sentence.\\n   - Use colons sparingly.\\n\\n2. Language\\n   - Replace hedging phrases with direct statements.\\n   - Avoid stock transitions.\\n   - Vary repetitive terms.\\n   - Use contractions in informal contexts.\\n   - Replace overly formal words with simpler alternatives.\\n\\n3. Style\\n   - Prioritize concise, varied sentence lengths.\\n   - Allow minor imperfections.\\n   - Maintain the core message but adjust tone to match the audience.\"\n    },\n    {\n      \"role\": \"user\",\n      \"content\": \"You are a researcher and expert copywriter in a business development team of an AI Automation Agency. Generate exactly one LinkedIn post that adheres to LinkedIn's API formatting guidelines and is easy for humans to read. Follow these rules:\\n\\nStructure:\\n1. Hook: Start with a bold opening line using Unicode characters (e.g., \\\"𝐁𝐎𝐋𝐃 𝐒𝐓𝐀𝐓𝐄𝐌𝐄𝐍𝐓\\\").\\n2. Body: Use short paragraphs (1-3 sentences) separated by \\\\n\\\\n.\\n3. Use bullet points (•) for key features or highlights.\\n4. End with a clear call-to-action (e.g., \\\"Comment below with your thoughts!\\\").\\n\\nFormatting Requirements:\\n- Remove all numeric citation brackets like [2], [3], [4] from the text.\\n- Instead of citation brackets, if needed, add a brief phrase like \\\"according to Google I/O 2025\\\" or \\\"as reported by DeepMind\\\" naturally within the sentence.\\n- No Markdown or rich text formatting.\\n- Use Unicode characters or emojis for emphasis (e.g., ★, 🚀).\\n- Include up to 3 relevant hashtags at the end (e.g., #AI #Automation).\\n- For URLs or references, use placeholders like [Link] instead of raw URLs.\\n- If mentioning users or companies, use official LinkedIn URN format (e.g., \\\"urn:li:organization:123456\\\").\\n\\nContent Rules:\\n- Max 1,200 characters.\\n- Avoid promotional language.\\n- Include one statistical claim or industry insight.\\n- Add one personal anecdote or professional observation.\\n\\nReturn the post as plain text without additional commentary.\\n\\nInput: {{ $json.message.content }}\"\n    }\n  ]\n}\n","sendBody":true,"specifyBody":"json","authentication":"genericCredentialType","genericAuthType":"httpHeaderAuth"},"credentials":{"httpHeaderAuth":{"id":null,"name":"[CONFIGURE_YOUR_PERPLEXITY_API_KEY]"}},"typeVersion":4.2},{"id":"1b226459-7dc7-46c2-9b02-769cd213e927","name":"2 Most Trending","type":"n8n-nodes-base.set","position":[-2980,-200],"parameters":{"mode":"raw","options":{},"jsonOutput":"={\n  \"most-trending\": {\n\n    \"#1\": { \n\n      \"query\":\"{{ $json.related_queries.rising[0].query }}\",\n      \"score\":\"{{ $json.related_queries.rising[0].extracted_value }}\"\n\n    },\n\n\n    \"#2\": { \n\n      \"query\":\"{{ $json.related_queries.rising[1].query }}\",\n      \"score\":\"{{ $json.related_queries.rising[1].extracted_value }}\"\n\n    }\n  }\n}"},"typeVersion":3.4},{"id":"75ccf42a-7dc8-4cc8-9d5d-202ff4b2b795","name":"High search volume keywords","type":"n8n-nodes-base.code","position":[-2760,-200],"parameters":{"jsCode":"// Get the top array from your JSON\nconst topItems = $('Google Trends').first().json.related_queries.top;\n\n// Filter the items to only include those with extracted_value > 30\nconst filtered = topItems.filter(item => item.extracted_value > 30);\n\n// Map the filtered items to their query values and join them with commas\nconst resultString = filtered.map(item => item.query).join(', ');\n\n// Return the result in a new JSON property\nreturn [{ json: { result: resultString } }];\n"},"typeVersion":2},{"id":"c85503d1-76e7-4dd7-a2e3-69966f69e0cd","name":"Choosing Topic","type":"@n8n/n8n-nodes-langchain.openAi","position":[-2540,-200],"parameters":{"modelId":{"__rl":true,"mode":"list","value":"gpt-3.5-turbo","cachedResultName":"GPT-3.5-TURBO"},"options":{},"messages":{"values":[{"content":"=You are part of a team that creates world class blog posts. Your job is to choose the topic for each blog post. \n\nThe blog posts are posted on the website of a [COMPANY NAME + DESCRIPTION + PRODUCTS + TARGET MARKET]. The blog posts are mainly posted as part of an SEO campaign to get [YOUR_COMPANY] to rank high for its products and services.\n\nIn this instance, you are given a list of 2 keywords which have been trending the most on Google news search over the past few days. \n\nYour job is to pick one which you think would make for the most relevant blog post with the best SEO outcomes for the client. \n\nThe keywords have two attributes: \n\n1. query: This attribute determines the search query that users have been searching for which is trending. \n\n2. value: This attribute determines what percentage increase the keyword has seen compared to previous periods (i.e. the increase in search volume). \n\nYou must choose one out of the taking into consideration both the relevance of the keyword for [YOUR_COMPANY]'s SEO efforts and the comparative trendiness determined by the value attribute. \n\nOutput the keyword you decided to post a blog on and nothing else. Don't explain your reasoning. Just output the keyword. \n\nThis instance: \n\nKeyword 1:\n{{ $('2 Most Trending').item.json['most-trending']['#1'].toJsonString() }} \n\nKeyword2: \n{{ $('2 Most Trending').item.json['most-trending']['#2'].toJsonString() }} "}]}},"credentials":{"openAiApi":{"id":null,"name":"[CONFIGURE_YOUR_OPENAI_API_KEY]"}},"typeVersion":1.8},{"id":"37d7191c-878e-424e-90be-3fe2bdff625a","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[-3240,-280],"parameters":{"width":400,"height":240,"content":"## Find Trend\n\n"},"typeVersion":1},{"id":"9987f2ae-0ec1-48b5-81f5-44a2f5a705b7","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[-2820,-280],"parameters":{"width":200,"height":240,"content":"## High Volume Keywords\n\n"},"typeVersion":1},{"id":"f4a25815-10e6-409c-a89a-baa2efecb119","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[-2580,-280],"parameters":{"width":340,"height":240,"content":"## Choosing Blog Topic\n\n\n"},"typeVersion":1},{"id":"c9206a42-1471-4a87-99ad-25bd5d318fb4","name":"Sticky Note3","type":"n8n-nodes-base.stickyNote","position":[-2200,-280],"parameters":{"width":600,"height":240,"content":"## Research\n\n\n"},"typeVersion":1},{"id":"089fdbf7-f1a0-4cd5-9769-caf94b05a939","name":"Google Trends","type":"n8n-nodes-base.httpRequest","position":[-3200,-200],"parameters":{"url":"https://serpapi.com/search","options":{},"sendQuery":true,"queryParameters":{"parameters":[{"name":"q","value":"=ai agents"},{"name":"geo","value":"US"},{"name":"hl","value":"en"},{"name":"date","value":"={{ $now.minus({ days: 3 }).format('yyyy-MM-dd') }} {{ $now.format('yyyy-MM-dd') }}"},{"name":"data_type","value":"RELATED_QUERIES"},{"name":"engine","value":"google_trends"},{"name":"api_key","value":"[YOUR_SERPAPI_KEY]"}]}},"typeVersion":4.2},{"id":"13f0ea49-1dbe-4b33-9c73-ebe9d3099003","name":"Wait","type":"n8n-nodes-base.wait","position":[-1940,-200],"webhookId":"[GENERATED_WEBHOOK_ID]","parameters":{"amount":10},"typeVersion":1.1},{"id":"c582949e-858f-4aa7-984b-0bd94212009f","name":"Sticky Note4","type":"n8n-nodes-base.stickyNote","position":[-1560,-540],"parameters":{"height":800,"content":"## Multi Social Media Posting"},"typeVersion":1},{"id":"77f592f4-fc6c-4633-ba2e-e671b18d6a1b","name":"Sticky Note5","type":"n8n-nodes-base.stickyNote","position":[-1300,-280],"parameters":{"height":260,"content":"## Status update"},"typeVersion":1}],"active":false,"pinData":{},"settings":{"executionOrder":"v1"},"versionId":"9211dd42-49be-406b-94aa-297f48c13f3e","connections":{"Wait":{"main":[[{"node":"Split Out","type":"main","index":0}]]},"LinkedIn1":{"main":[[{"node":"Google Sheets2","type":"main","index":0}]]},"Split Out":{"main":[[{"node":"X1","type":"main","index":0},{"node":"Facebook Graph API1","type":"main","index":0},{"node":"LinkedIn1","type":"main","index":0}]]},"Google Trends":{"main":[[{"node":"2 Most Trending","type":"main","index":0}]]},"Choosing Topic":{"main":[[{"node":"Research Topic- Perplexity","type":"main","index":0}]]},"2 Most Trending":{"main":[[{"node":"High search volume keywords","type":"main","index":0}]]},"Schedule Trigger":{"main":[[{"node":"Google Trends","type":"main","index":0}]]},"Research Topic- Perplexity":{"main":[[{"node":"Wait","type":"main","index":0}]]},"High search volume keywords":{"main":[[{"node":"Choosing Topic","type":"main","index":0}]]}}}


name: AI-Powered Post-Sales Call Automated Proposal Generator
author_name: Gerald Denor
author_username: dominixai
categories: []
created_at: 2025-05-24T13:32:44.312Z
updated_at: 2025-05-24T13:32:44.312Z
url: https://n8n.io/workflows/4359
scraped_at: 2025-06-19 22:49:15
description:
  AI-Powered Proposal Generator - Sales Automation Workflow

  Overview

  This n8n workflow automates the entire proposal generation process using AI, transforming client requirements into professional, customized proposals delivered via email in seconds.

  Use Case
  Perfect for agencies, consultants, and sales teams who need to generate high-quality proposals quickly. Instead of spending hours writing proposals manually, this workflow captures client information through a web form and uses GPT-4 to generate contextually relevant, professional proposals.

  How It Works
  Form Trigger - Captures client information through a customizable web form
  OpenAI Integration - Processes form data and generates structured proposal content
  Google Drive - Creates a copy of your proposal template
  Google Slides - Populates the template with AI-generated content
  Gmail - Automatically sends the completed proposal to the client

  Key Features
  AI Content Generation**: Uses GPT-4 to create personalized proposal content
  Professional Templates**: Integrates with Google Slides for polished presentations
  Automated Delivery**: Sends proposals directly to clients via email
  Form Integration**: Captures all necessary client data through web forms
  Customizable Output**: Generates structured proposals with multiple sections

  Template Sections Generated
  Proposal title and description
  Problem summary analysis
  Three-part solution breakdown
  Project scope details
  Milestone timeline with dates
  Cost integration

  Requirements
  n8n instance** (cloud or self-hosted)
  OpenAI API key** for content generation
  Google Workspace account** for Slides and Gmail
  Basic n8n knowledge** for setup and customization

  Setup Complexity
  Intermediate - Requires API credentials setup and basic workflow customization

  Benefits
  Time Savings**: Reduces proposal creation from hours to minutes
  Consistency**: Ensures all proposals follow the same professional structure
  Personalization**: AI analyzes client needs for relevant content
  Automation**: Eliminates manual copy-paste and formatting work
  Scalability**: Handle multiple proposal requests simultaneously

  Customization Options
  Modify AI prompts for different industries or services
  Customize Google Slides template design
  Adjust form fields for specific information needs
  Personalize email templates and signatures
  Configure milestone templates for different project types

  Error Handling
  Includes basic error handling for API failures and form validation to ensure reliable operation.

  Security Notes
  All credentials have been removed from this template. Users must configure their own:
  OpenAI API credentials
  Google OAuth2 connections for Slides, Drive, and Gmail
  Form webhook configuration

  This workflow demonstrates practical AI integration in business processes and showcases n8n's capabilities for complex automation scenarios.

nodes_used:
  ["n8n-nodes-base.googleDrive","n8n-nodes-base.gmail","n8n-nodes-base.googleSlides","@n8n/n8n-nodes-langchain.openAi"]

workflow_json:
  {"meta":{"templateCredsSetupCompleted":false},"name":"AI Proposal Generator System","tags":[],"nodes":[{"id":"12f23b4f-a653-45ad-87b7-e60ba30e70cb","name":"Replace Text","type":"n8n-nodes-base.googleSlides","position":[1300,1100],"parameters":{"textUi":{"textValues":[{"text":"{{proposalTitle}}","replaceText":"={{ $('OpenAI').item.json.message.content.proposalTitle }}"},{"text":"{{descriptionName}}","replaceText":"={{ $('OpenAI').item.json.message.content.descriptionName }}"},{"text":"{{oneParagraphProblemSummary}}","replaceText":"={{ $('OpenAI').item.json.message.content.oneParagraphProblemSummary }}"},{"text":"{{solutionHeadingOne}}","replaceText":"={{ $('OpenAI').item.json.message.content.solutionHeadingOne }}"},{"text":"{{solutionHeadingTwo}}","replaceText":"={{ $('OpenAI').item.json.message.content.solutionHeadingTwo }}"},{"text":"{{solutionHeadingThree}}","replaceText":"={{ $('OpenAI').item.json.message.content.solutionHeadingThree }}"},{"text":"{{solutionDescriptionOne}}","replaceText":"={{ $('OpenAI').item.json.message.content.solutionDescriptionOne }}"},{"text":"{{solutionDescriptionTwo}}","replaceText":"={{ $('OpenAI').item.json.message.content.solutionDescriptionTwo }}"},{"text":"{{solutionDescriptionThree}}","replaceText":"={{ $('OpenAI').item.json.message.content.solutionDescriptionThree }}"},{"text":"{{shortScopeTitleOne}}","replaceText":"={{ $('OpenAI').item.json.message.content.shortScopeTitleOne }}"},{"text":"{{shortScopeTitleTwo}}","replaceText":"={{ $('OpenAI').item.json.message.content.shortScopeTitleTwo }}"},{"text":"{{shortScopeTitleThree}}","replaceText":"={{ $('OpenAI').item.json.message.content.shortScopeTitleThree }}"},{"text":"{{shortScopeDescriptionOne}}","replaceText":"={{ $('OpenAI').item.json.message.content.shortScopeDescriptionOne }}"},{"text":"{{shortScopeDescriptionTwo}}","replaceText":"={{ $('OpenAI').item.json.message.content.shortScopeDescriptionTwo }}"},{"text":"{{shortScopeDescriptionThree}}","replaceText":"={{ $('OpenAI').item.json.message.content.shortScopeDescriptionThree }}"},{"text":"{{milestoneOneDay}}","replaceText":"={{ $('OpenAI').item.json.message.content.milestoneOneDay }}"},{"text":"{{milestoneTwoDay}}","replaceText":"={{ $('OpenAI').item.json.message.content.milestoneTwoDay }}"},{"text":"{{milestoneThreeDay}}","replaceText":"={{ $('OpenAI').item.json.message.content.milestoneThreeDay }}"},{"text":"{{milestoneFourDay}}","replaceText":"={{ $('OpenAI').item.json.message.content.milestoneFourDay }}"},{"text":"{{milestoneDescriptionOne}}","replaceText":"={{ $('OpenAI').item.json.message.content.milestoneDescriptionOne }}"},{"text":"{{milestoneDescriptionTwo}}","replaceText":"={{ $('OpenAI').item.json.message.content.milestoneDescriptionTwo }}"},{"text":"{{milestoneDescriptionThree}}","replaceText":"={{ $('OpenAI').item.json.message.content.milestoneDescriptionThree }}"},{"text":"{{milestoneDescriptionFour}}","replaceText":"={{ $('OpenAI').item.json.message.content.milestoneDescriptionFour }}"},{"text":"{{cost}}","replaceText":"={{ $('On form submission').item.json.Cost }}"}]},"options":{},"operation":"replaceText","presentationId":"={{ $json.id }}"},"typeVersion":2},{"id":"da8060cf-ac55-439f-ab44-a973d5e4ee18","name":"OpenAI","type":"@n8n/n8n-nodes-langchain.openAi","position":[700,1100],"parameters":{"modelId":{"__rl":true,"mode":"list","value":"gpt-4o","cachedResultName":"GPT-4O"},"options":{},"messages":{"values":[{"role":"system","content":"You are a helpful, intelligent writing assistant."},{"content":"Your task is to generate a proposal using input data from a form. This proposal should be highly customized, specific, and high-quality, considering we're going to be sending it immediately after you're done.\n\nContext: we are an automation/no-code agency that develops systems revolving around growth, revenue ops, etc.\n\nThe proposal template we're using has many fields. You must return these fields in one JSON object.\n\nUse this format:\n\n{\n  \"proposalTitle\": \"\",\n  \"descriptionName\": \"\",\n  \"oneParagraphProblemSummary\": \"\",\n  \"solutionHeadingOne\": \"\",\n  \"solutionDescriptionOne\": \"\",\n  \"solutionHeadingTwo\": \"\",\n  \"solutionDescriptionTwo\": \"\",\n  \"solutionHeadingThree\": \"\",\n  \"solutionDescriptionThree\":\"\",\n  \"shortScopeTitleOne\": \"\",\n  \"shortScopeTitleTwo\": \"\",\n  \"shortScopeTitleThree\": \"\",\n  \"shortScopeDescriptionOne\": \"\",\n  \"shortScopeDescriptionTwo\": \"\",\n  \"shortScopeDescriptionThree\": \"\",\n  \"milestoneOneDay\": \"\",\n  \"milestoneTwoDay\": \"\",\n  \"milestoneThreeDay\": \"\",\n  \"milestoneFourDay\": \"\",\n  \"milestoneDescriptionOne\": \"\",\n  \"milestoneDescriptionTwo\": \"\",\n  \"milestoneDescriptionThree\": \"\",\n  \"milestoneDescriptionFour\": \"\"\n}\n\nRules:\n1. Use a spartan, casual tone of voice.\n2. Be to-the-point but professional—assume you're writing to a sophisticated audience.\n3. Ensure that all fields are filled out. Do not miss a field or leave any variables empty.\n4. Keep things short. If a field contains the term \"Description\" it should be no more than fourteen words. For \"descriptionName\" do not use title case."},{"content":"{\n  \"companyName\":\"1SecondCopy\",\n  \"problem\": \"they can't generate leads. everything is referral based rn.\",\n  \"solution\": \"cold email lead gen system, client reactivation system, and best in class sales training for closing\",\n  \"scope\": \"1k/day cold email infra, 30k email leads, 4 weekly zoom sessions for sales training\",\n  \"currentDate\":\"Feb 4 2025\",\n  \"howSoon\": \"two months\",\n  \"depositCost\": \"$1,845\",\n}"},{"role":"assistant","content":"{\n  \"proposalTitle\": \"Lead Gen System for 1SecondCopy\n\",\n  \"descriptionName\": \"A simple, scalable lead generation system built to help grow your content efforts & connect you with the right people.\n\",\n  \"oneParagraphProblemSummary\": \"Right now, 1SecondCopy is struggling with an inability to generate qualified leads. The majority of your new clients are referral-based, which, while always nice to have, is not scalable nor is it reliable. Building an alternative strategy—one that allows you to take leads from cold -> close—is vital to the health and longevity of the company, and it's what we're going to help you with.\n\",\n  \"solutionHeadingOne\": \"Cold Outbound Lead Gen\",\n  \"solutionDescriptionOne\": \"We'll put in place a robust cold-email-based system for you using best practices.\",\n  \"solutionHeadingTwo\": \"Client Reactivation System\",\n  \"solutionDescriptionTwo\": \"We'll build a simple, but high-ROI reactivation system to let you extract value from pre-existing clients.\",\n  \"solutionHeadingThree\": \"Best-In-Class Sales Training\",\n  \"solutionDescriptionThree\": \"We'll train your team with world-class setting & closing mechanisms.\",\n  \"shortScopeTitleOne\": Cold email infrastructure that sends ~1K emails/day\",\n  \"shortScopeTitleTwo\": \"30K high-quality scraped email leads (included)\",\n  \"shortScopeTitleThree\": \"Four weekly one-hour sales training sessions over Zoom\",\n  \"shortScopeDescriptionOne\": \"12 domains, 36 mailboxes, DNS optimization, and warmups included.\",\n  \"shortScopeDescriptionTwo\": \"30,000 leads in your target market, delivered by CSV.\",\n  \"shortScopeDescriptionThree\": \"We'll take your sales team from 0->1.\",\n  \"milestoneOneDay\": \"February 8th, 2025\",\n  \"milestoneTwoDay\": \"February 28th, 2025\",\n  \"milestoneThreeDay\": \"March 10th, 2025\",\n  \"milestoneFourDay\":\"March 17th-April 1st, 2025\",\n  \"milestoneDescriptionOne\": \"Cold email system done & ready for warmup.\",\n  \"milestoneDescriptionTwo\": \"Cold email system fully warmed up & operational.\",\n  \"milestoneDescriptionThree\": \"10,000 outbound emails sent; analysis & training #1.\"\n  \"milestoneDescriptionFour\":\"One sales training per week alongside iteration & handoff.\"\n}"},{"content":"={\n  \"companyName\":\"{{ $json['Company Name'] }}\",\n  \"problem\": \"{{ $json.Problem }}\",\n  \"solution\": \"{{ $json.Solution}}\",\n  \"scope\": \"{{ $json.Scope }}\",\n  \"currentDate\":\"{{ $now.toLocaleString({ dateStyle: 'medium' }) }}\",\n  \"howSoon\": \"{{ $json['How soon?'] }}\",\n  \"depositCost\": \"{{ $json.Cost }}\",\n}"}]},"jsonOutput":true},"typeVersion":1.6},{"id":"7e52e4c7-49da-499a-a9ea-3e421611fb87","name":"Google Drive","type":"n8n-nodes-base.googleDrive","position":[1080,1100],"parameters":{"name":"={{ $json.message.content.proposalTitle }}","fileId":{"__rl":true,"mode":"id","value":"REPLACE_WITH_YOUR_GOOGLE_SLIDES_TEMPLATE_ID"},"options":{"copyRequiresWriterPermission":false},"operation":"copy"},"typeVersion":3},{"id":"5a0508ab-4eaa-49f0-96f9-a664a1e7a5eb","name":"Gmail","type":"n8n-nodes-base.gmail","position":[1520,1100],"webhookId":"WEBHOOK_ID_WILL_BE_GENERATED","parameters":{"sendTo":"={{ $('On form submission').item.json.Email }}","message":"=Hey {{ $('On form submission').item.json['First Name'] }},\n\nThanks for the great call earlier. I had a moment after our chat to put together a detailed proposal for you—please take a look at your earliest convenience and let me know your thoughts.\n\nYou'll find it here: https://docs.google.com/presentation/d/{{ $json.presentationId }}/edit\n\nIf you have any questions, just ask. I've also sent over an invoice for the project (just to keep things convenient) and we can get started anytime that's sorted.\n\nThanks,\n[YOUR NAME]","options":{"appendAttribution":false},"subject":"=Re: Proposal for  {{ $('On form submission').item.json['Company Name'] }}","emailType":"text"},"typeVersion":2.1},{"id":"5be2415f-96f1-4e05-b589-bc4992c2a231","name":"On form submission","type":"n8n-nodes-base.formTrigger","position":[480,1100],"webhookId":"WEBHOOK_ID_WILL_BE_GENERATED","parameters":{"options":{"appendAttribution":false},"formTitle":"Sales Call Logging Form","formFields":{"values":[{"fieldLabel":"First Name","requiredField":true},{"fieldLabel":"Last Name","requiredField":true},{"fieldLabel":"Company Name","requiredField":true},{"fieldType":"email","fieldLabel":"Email"},{"fieldLabel":"Website","requiredField":true},{"fieldType":"textarea","fieldLabel":"Problem","requiredField":true},{"fieldType":"textarea","fieldLabel":"Solution","requiredField":true},{"fieldType":"textarea","fieldLabel":"Scope","requiredField":true},{"fieldLabel":"Cost","requiredField":true},{"fieldLabel":"How soon?","requiredField":true}]},"formDescription":"This form logs a sales call & automatically generates a proposal."},"typeVersion":2.2},{"id":"4ae579fb-779d-4312-a163-d438507b8918","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[440,980],"parameters":{"width":1220,"height":280,"content":"## Google Slides AI Proposal Generator\n**This flow generates proposals using AI and the free Google Slides solution**."},"typeVersion":1}],"active":false,"pinData":{"On form submission":[{"json":{"Cost":"$2,500","Email":"john@example.com","Scope":"Setup and 1 month training","Problem":"Low sales due to lead generation problems","Website":"www.example.com","Solution":"AI automation system for lead generation","formMode":"test","How soon?":"Within 2 weeks","Last Name":"Doe","First Name":"John","submittedAt":"2025-05-13T09:10:33.001+01:00","Company Name":"Example Corp"}}]},"settings":{"timezone":"UTC","callerPolicy":"workflowsFromSameOwner","executionOrder":"v1"},"connections":{"OpenAI":{"main":[[{"node":"Google Drive","type":"main","index":0}]]},"Google Drive":{"main":[[{"node":"Replace Text","type":"main","index":0}]]},"Replace Text":{"main":[[{"node":"Gmail","type":"main","index":0}]]},"On form submission":{"main":[[{"node":"OpenAI","type":"main","index":0}]]}}}


name: 🤖💬 Conversational AI Chatbot with Google Gemini for Text & Image | Telegram
author_name: Alan Bajaña Granizo
author_username: thecrawlerzero
categories: []
created_at: 2025-05-24T20:40:13.992Z
updated_at: 2025-05-24T20:40:13.992Z
url: https://n8n.io/workflows/4365
scraped_at: 2025-06-19 22:48:47
description:
  🤖💬 Conversational AI Chatbot with Google Gemini for Text & Image | Telegram

  Overview 📋  
  Flexible and scalable chatbot template, designed mainly for Spanish conversations but capable of handling English and other languages. Integrates Google Gemini API for text and image generation, and Telegram for messaging. Supports multiple output types with potential for video, audio, and more.

  How It Works

  Modular Architecture & Extensibility ⚙️  
  Separate modules for data extraction, intent analysis, and adaptive response generation.  
  Easily extendable with additional tools, databases, or APIs.  

  Context & Memory Handling 🧠  
  Session-based volatile memory maintains conversation coherence.  
  Allows updates or modifications to previous images based on new requests (e.g., add a hat to a dog 🐶).  

  Intent Detection & Classification 🔍  
  Google Gemini accurately classifies user intent.  
  Two-step validation ensures context-aware, precise replies.

  Content Generation & Output ✍️🖼️  
  Generates text and images based on intent and context.  
  Designed for Telegram but adaptable to other platforms and media types (audio, video).

  Key Benefits ✅  
  Scalable, customizable, and production-ready architecture.  
  Supports multiple content formats: text, images, audio, and video.  
  Dynamic context and memory management for smooth, coherent conversations.  
  Native integration with Google Gemini and Telegram ensures reliable and seamless operation.  
  Suitable for diverse use cases and easy to extend with new tools or platforms.

  Use Cases 💼  
  Customer support virtual assistants.  
  On-demand multimedia content creation.  
  Marketing and user engagement bots.  
  AI conversational prototypes and pilots.

  Requirements 👨‍💻  
  n8n instance (self-hosted or cloud)  
  Google Gemini API credentials  
  Telegram bot setup (optional but recommended)

  Active member of the Polytechnic Artificial Intelligence Club (CIAP) at ESPOL.

nodes_used:
  ["n8n-nodes-base.httpRequest","n8n-nodes-base.telegram","n8n-nodes-base.code","@n8n/n8n-nodes-langchain.agent","@n8n/n8n-nodes-langchain.chainLlm","@n8n/n8n-nodes-langchain.memoryBufferWindow","@n8n/n8n-nodes-langchain.outputParserStructured","@n8n/n8n-nodes-langchain.memoryManager","@n8n/n8n-nodes-langchain.lmChatGoogleGemini"]

workflow_json:
  {"nodes":[{"id":"3017950d-52a5-4f51-a64d-7f223c01743e","name":"chatPrompt","type":"n8n-nodes-base.set","position":[0,-880],"parameters":{"options":{},"assignments":{"assignments":[{"id":"b3ce66e0-2b6f-4714-a672-59ef6e43ced9","name":"prompt","type":"string","value":"=1. Rules\n- Communicate formally, clearly, and respectfully at all times.\n- Be concise and precise, avoiding unnecessary details.\n- Maintain a positive, professional tone as a reliable and knowledgeable assistant.\n- Respect user boundaries and refrain from engaging in prohibited or inappropriate topics.\n- Keep the conversation engaging by encouraging user participation, but when requesting clarification or additional information, ask only one focused question at a time to avoid overwhelming the user. Avoid abrupt endings to the dialogue.\n- Follow user instructions precisely.\n- Do not include any additional text or explanations unless explicitly requested.\n\n2. Response instructions\n- Analyze the message and conversation history to maintain context and continuity.\n- If repetition is requested, return the message exactly as provided. Otherwise, respond clearly and appropriately based on intent and context.\n- If the message is vague, suggest an interpretation and ask for clarification while keeping the conversation active."}]}},"typeVersion":3.4},{"id":"975f1ebd-9af9-4bc5-8cec-6c3be3d3a63d","name":"otherPrompt","type":"n8n-nodes-base.set","position":[0,-720],"parameters":{"options":{},"assignments":{"assignments":[{"id":"d78c64d5-3c9e-4ffd-875e-973eb3c4d20a","name":"prompt","type":"string","value":"=1. Rules\n- Communicate formally, clearly, and respectfully at all times.\n- Be concise and precise, avoiding unnecessary details.\n- Maintain a positive, professional tone as a reliable and knowledgeable assistant.\n- Respect user boundaries and refrain from engaging in prohibited or inappropriate topics.\n- Keep the conversation engaging by encouraging user participation, but when requesting clarification or additional information, ask only one focused question at a time to avoid overwhelming the user. Avoid abrupt endings to the dialogue.\n- Follow user instructions precisely.\n- Do not include any additional text or explanations unless explicitly requested.\n\n2. General Instructions\n- If a message is unclear or lacks details, respond with your best understanding as a suggestion, and politely ask the user to confirm or provide more details if it is not what they meant.\n- If the request is inappropriate or irrelevant, respond politely and clearly refuse, maintaining respect and professionalism, and invite a valid request.\n- Always follow the established rules to maintain professionalism and accuracy."}]}},"typeVersion":3.4},{"id":"f297c8ce-7c7c-4011-9c36-e4993dbfd926","name":"generatePrompt","type":"n8n-nodes-base.set","position":[0,-1040],"parameters":{"options":{},"assignments":{"assignments":[{"id":"70c93816-7110-48e3-a105-568dd766bdf4","name":"prompt","type":"string","value":"=1.  General instructions\nCreate a prompt that generates only one response with no comments and no line breaks. Based on the input provided, generate a detailed visual description of the request in a clear and coherent manner. Avoid using quotation marks, apostrophes, or any other punctuation marks.\n\n2. Visual specifications\n- Composition: maintain a balanced and harmonious layout where all elements (images, shapes, and text) work together seamlessly. Ensure that no part of the image feels overcrowded, and the design directs the viewer’s attention naturally. Use a minimalistic approach, avoiding excessive detail or distractions.\n\n- Color palette: choose a color scheme that complements the overall theme and enhances the mood. The colors should be visually pleasing and work together harmoniously. Use no more than 3-4 main colors to maintain simplicity and coherence, ensuring they do not overpower the design.\n\n- Visual clarity: the image should be crisp and clear, with all elements legible and easy to interpret. Avoid blurry or pixelated visuals. Maintain sharp contrasts between key elements for emphasis and visual clarity.\n\n- Image size and resolution: the image should be sized to fit standard display requirements (e.g., social media, web posts). Ensure the resolution is high enough for clarity on both desktop and mobile devices. The image must maintain visual quality without losing sharpness or details when viewed on different screens.\n\n- Aesthetic appeal: aim for a design that is not only functional but also visually appealing. The overall style should be modern, clean, and aesthetically pleasing, with a consistent look that aligns with the intended mood or message. Ensure the design is pleasing to the eye, evoking the intended response from the viewer.\n\n- Visual balance: ensure the elements in the image are well-spaced, with no part feeling too heavy or too light. Create a natural flow of focus, guiding the viewer’s eye through the composition without distraction."}]}},"typeVersion":3.4},{"id":"51eb4b31-0099-4886-9dfd-dc9c02107562","name":"buildPrompt","type":"n8n-nodes-base.set","position":[140,-880],"parameters":{"options":{},"assignments":{"assignments":[{"id":"f435e1c3-6ff9-4e68-852c-0a39a5903ebe","name":"prompt","type":"string","value":"={{ $json.prompt }}"}]},"includeOtherFields":true},"typeVersion":3.4},{"id":"d9a263b3-9078-47e9-8146-abf62100af21","name":"ChatCore","type":"@n8n/n8n-nodes-langchain.agent","position":[280,-880],"parameters":{"text":"=Input from user: {{ $('sessionData').item.json.Mensaje }}\n\n{{ $json.prompt }}\n\nRespond only with the exact text requested, strictly following the instructions above. ","options":{"systemMessage":"=You are a professional enterprise chatbot designed to assist users with clear, respectful, and accurate communication. You provide informative text responses and generate images only upon explicit user requests. Utilize available conversation history to maintain context and coherence. Adhere strictly to company rules to ensure appropriate and secure interactions.\n\nYou can chat with me to get answers and create custom images based on your instructions.\n\nPrioritize the most recent relevant message if multiple prior references exist. Always respond in Spanish when providing text-based chat replies. For image generation requests, respond in English. Keep responses as short as possible without compromising clarity or natural interaction. Do not force interaction with the user beyond what is necessary to respond clearly."},"promptType":"define"},"typeVersion":1.9},{"id":"67e27375-a9f9-45d7-8ea9-aad5d18996de","name":"GeminiModel","type":"@n8n/n8n-nodes-langchain.lmChatGoogleGemini","position":[300,-720],"parameters":{"options":{},"modelName":"models/gemini-2.0-flash-001"},"credentials":{"googlePalmApi":{"id":"zuXA1v8tUW8qt8Gz","name":"Google Gemini(PaLM) Api account"}},"typeVersion":1},{"id":"58ab707f-00e3-4b9f-b598-af89cebf99ce","name":"inputProcessor","type":"@n8n/n8n-nodes-langchain.chainLlm","position":[-460,-880],"parameters":{"text":"=1. Context\nYou are an intelligent assistant designed to analyze user requests accurately by considering both the current user input and prior conversation history (if available). Use this context to improve classification and response relevance. Only classify as \"generate\" if the request clearly meets all criteria. Never assume without certainty.\n\n2. General instructions\n- Use prior conversation history, if available, to interpret references, refinements, or corrections in the user’s message. \n- Apply updates directly when a previous request is being modified (e.g., changing part of a generated image).\n- Maintain context continuity unless the user explicitly shifts the topic.\n- When evaluating intention, prioritize the most recent relevant message to avoid using outdated context.\n- If the message is vague, nonsensical, or overly brief (e.g., a single word), do not classify it as \"generate\". Even if image requests occurred earlier. Only proceed if the current input clearly meets all criteria. Default to \"other\" unless the message includes clear direction.\n\n3. User Request: \"{{ $('sessionData').item.json.Mensaje }}\"\n\n4. Conversation history:\n{{ $json.messages}}\n\n5. Intentions\nClassify the user's intention as exactly one of the following:\n- \"generate\": user requests the direct creation of new visual content (e.g., images or art) to be delivered. This includes implicit requests for physical or tangible objects (e.g., \"give me a pet\"), but only if the message contains clear intent or is supported by prior context. Single-word or vague inputs without clear directive or context should not be treated as generate.\n- \"chat\": user engages in meaningful conversational interaction, including requests to generate textual prompts, explanations, or dialogue that have clear context and intent.\n- \"other\": request does not fit into the above categories, or involves content that is restricted, inappropriate, irrelevant, nonsensical, or lacks clear context or intent distinct from conversational engagement.\n\n6. Data types\nWhen analyzing the user’s message, determine whether a request for a physical or tangible object should be interpreted as a visual content request. In general, treat requests for tangible items as image generation unless the context explicitly suggests otherwise. For intangible content, respond with text unless the user clearly asks for an image.\n\nBased on the intention and content of the request, select exactly one data type to return:\n\n- \"text\": a textual response such as an answer, explanation, dialogue, or prompt text.\n- \"image\": a visual response explicitly or implicitly requested as image generation.\n\nAssign \"image\" as typeData only if the intention is \"generate\". In all other cases, including when the intention is \"other\", assign \"text\".\n\n7. Output format\nRespond only with a JSON object in this exact format, with no additional text or explanation: {\"intention\": \"value\", \"typeData\": \"value\"}","promptType":"define","hasOutputParser":true},"typeVersion":1.6,"alwaysOutputData":false},{"id":"0123eef4-eb57-485a-ad01-66dc47b332f8","name":"GeminiModel1","type":"@n8n/n8n-nodes-langchain.lmChatGoogleGemini","position":[-440,-740],"parameters":{"options":{},"modelName":"models/gemini-2.0-flash"},"credentials":{"googlePalmApi":{"id":"zuXA1v8tUW8qt8Gz","name":"Google Gemini(PaLM) Api account"}},"typeVersion":1},{"id":"8853d1da-5ab6-44cf-8054-7267392c9eae","name":"structuredOutput","type":"@n8n/n8n-nodes-langchain.outputParserStructured","position":[-300,-740],"parameters":{"jsonSchemaExample":"{\n\t\"typeData\": \"text\",\n\t\"intention\": \"generate\"\n}"},"typeVersion":1.2},{"id":"b679111d-c640-4f59-8046-c37fa7f977e9","name":"contentType","type":"n8n-nodes-base.switch","position":[580,-800],"parameters":{"rules":{"values":[{"outputKey":"=Imagen","conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"24ab5811-2b6d-4f2f-8620-8697dadc2d4d","operator":{"type":"string","operation":"contains"},"leftValue":"={{ $('intentHandler').item.json.output.typeData }}","rightValue":"image"}]},"renameOutput":true},{"outputKey":"Texto","conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"28759436-2f6a-4bb3-a9bf-924477241809","operator":{"type":"string","operation":"contains"},"leftValue":"={{ $('intentHandler').item.json.output.typeData }}","rightValue":"text"}]},"renameOutput":true}]},"options":{}},"typeVersion":3.2},{"id":"8abd3463-8ecc-4086-9057-e7494b8b2d9d","name":"textCleaner","type":"n8n-nodes-base.code","position":[820,-980],"parameters":{"jsCode":"let texto = $input.first().json.prompt.replace(/[\\n\\r\\t]/g, \" \")  // Reemplaza saltos de línea, retorno de carro y tabulaciones por espacio\n  .replace(/['\"\\\\]/g, \"\")      // Elimina comillas simples, dobles y barras invertidas\n  .replace(/\\s+/g, \" \")        // Reemplaza múltiples espacios por un solo espacio\n  .trim();                     // Elimina los espacios en blanco al inicio y al final\n\nreturn {\n  text: texto\n}"},"typeVersion":2},{"id":"a11a2afc-71c4-4b3f-81ec-fb8cacc1d9f2","name":"imageGeneration","type":"n8n-nodes-base.httpRequest","position":[940,-980],"parameters":{"url":"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash-exp-image-generation:generateContent","method":"POST","options":{},"jsonBody":"={\n  \"contents\": [\n    {\n      \"role\": \"user\",\n      \"parts\": [\n        {\n          \"text\": \"{{ $json.text }}\"\n        }\n      ]\n    }\n  ],\n  \"generationConfig\": {\n    \"responseModalities\": [\"Text\", \"Image\"]\n  }\n}","sendBody":true,"specifyBody":"json","authentication":"predefinedCredentialType","nodeCredentialType":"googlePalmApi"},"credentials":{"googlePalmApi":{"id":"zuXA1v8tUW8qt8Gz","name":"Google Gemini(PaLM) Api account"}},"typeVersion":4.2},{"id":"ccce85bc-79f7-43ed-b649-8b1533d774a5","name":"imageBuilder","type":"n8n-nodes-base.convertToFile","position":[1060,-980],"parameters":{"options":{"fileName":"generated_image.png"},"operation":"toBinary","sourceProperty":"candidates[0].content.parts[1].inlineData.data"},"typeVersion":1.1},{"id":"4dbbf4c4-4d78-42d3-bdbc-a35a584643ff","name":"sendImage","type":"n8n-nodes-base.telegram","position":[1180,-980],"webhookId":"511272cc-d9e3-4384-9407-e5d4296db621","parameters":{"chatId":"={{ $('sessionData').item.json.sessionId }}","operation":"sendPhoto","binaryData":true,"additionalFields":{"fileName":"=generated_image.png"}},"credentials":{"telegramApi":{"id":"w7tC1svlHpL7ogwy","name":"TheCrawlerZeroBot"}},"typeVersion":1},{"id":"8e525ff1-f403-4f7a-a281-36fb18824168","name":"sendTextMessage","type":"n8n-nodes-base.telegram","position":[1180,-780],"webhookId":"1d1eee00-2306-4ac1-870f-0988e305f0d0","parameters":{"text":"={{ $('ChatCore').item.json.output }}","chatId":"={{ $('sessionData').item.json.sessionId }}","additionalFields":{"parse_mode":"HTML","appendAttribution":false}},"credentials":{"telegramApi":{"id":"w7tC1svlHpL7ogwy","name":"TheCrawlerZeroBot"}},"typeVersion":1},{"id":"4e0fcbad-8b6b-4c39-80ac-6aed0f8cf0fd","name":"sessionData","type":"n8n-nodes-base.set","position":[-980,-880],"parameters":{"values":{"string":[{"name":"Mensaje","value":"={{ $('userInput').item.json.message.text }}"},{"name":"sessionId","value":"={{ $('userInput').item.json.message.chat.id }}"},{"name":"Lenguaje","value":"={{ $('userInput').item.json.message.from.language_code }}"},{"name":"Username","value":"={{ $('userInput').item.json.message.chat.username }}"}]},"options":{},"keepOnlySet":true},"typeVersion":2},{"id":"ea84ebc4-2932-4fd9-8771-b13a929b6ea5","name":"conversationStore","type":"@n8n/n8n-nodes-langchain.memoryManager","position":[-860,-880],"parameters":{"options":{"groupMessages":true}},"typeVersion":1.1},{"id":"03420024-1474-4b55-a98a-e80e0826ccc7","name":"memoryRetriever","type":"@n8n/n8n-nodes-langchain.memoryBufferWindow","position":[-820,-740],"parameters":{"sessionKey":"={{ $('sessionData').item.json.sessionId }}","sessionIdType":"customKey","contextWindowLength":2},"typeVersion":1.3},{"id":"28f6a639-1c50-4754-a66c-772cc3a05083","name":"latestContext","type":"n8n-nodes-base.code","position":[-580,-880],"parameters":{"jsCode":"const allItems = $input.all();\nconst lastItem = allItems[allItems.length - 1];\n\nif (lastItem && Array.isArray(lastItem.json.messages)) {\n  const messages = lastItem.json.messages;\n  const count = messages.length;\n\n  if (count === 0) return [{ json: { message: \"\" } }];\n\n  const extractFirstLine = (text) => {\n    if (!text) return \"\";\n    return text.split('\\n')[0].replace(/^Input from user:\\s*/, '');\n  };\n\n  const trimEndNewline = (text) => {\n    if (!text) return \"\";\n    return text.replace(/\\n+$/, '');\n  };\n\n  // Tomar los últimos dos o menos mensajes\n  const selectedMessages = (count === 1) ? [messages[0]] : messages.slice(-1);\n\n  // Construir el texto concatenado\n  const combinedMessage = selectedMessages.map((msg, idx) => {\n    return `Message ${idx + 1}:\\nhuman: ${extractFirstLine(msg.human)}\\nai: ${trimEndNewline(msg.ai)}`;\n  }).join('\\n\\n');\n\n  return [{ json: { messages: combinedMessage } }];\n}\n\nreturn [{ json: { messages: \"\" } }];"},"typeVersion":2},{"id":"14bae45a-aafa-407f-9761-62954acabbbd","name":"intentHandler","type":"n8n-nodes-base.switch","position":[-180,-880],"parameters":{"rules":{"values":[{"outputKey":"generate","conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"24ab5811-2b6d-4f2f-8620-8697dadc2d4d","operator":{"type":"string","operation":"contains"},"leftValue":"={{ $json.output.intention }}","rightValue":"generate"}]},"renameOutput":true},{"outputKey":"chat","conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"28759436-2f6a-4bb3-a9bf-924477241809","operator":{"type":"string","operation":"contains"},"leftValue":"={{ $json.output.intention }}","rightValue":"chat"}]},"renameOutput":true},{"outputKey":"other","conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"de4b6e87-950e-461c-869f-d27c73f8d763","operator":{"type":"string","operation":"contains"},"leftValue":"={{ $json.output.intention }}","rightValue":"other"}]},"renameOutput":true}]},"options":{}},"typeVersion":3.2},{"id":"2f3d4931-9549-449b-8ff8-e27bf7b69e1f","name":"userInput","type":"n8n-nodes-base.telegramTrigger","position":[-1100,-880],"webhookId":"ddbf3f08-3f4d-446d-9378-054225c91a06","parameters":{"updates":["message"],"additionalFields":{}},"credentials":{"telegramApi":{"id":"w7tC1svlHpL7ogwy","name":"TheCrawlerZeroBot"}},"typeVersion":1},{"id":"357a258b-32a7-47c4-bcf1-f32cec025cba","name":"conversationMemory","type":"@n8n/n8n-nodes-langchain.memoryBufferWindow","position":[420,-700],"parameters":{"sessionKey":"={{ $('sessionData').item.json.sessionId }}","sessionIdType":"customKey","contextWindowLength":10},"typeVersion":1.3},{"id":"f1dad098-8b9f-4160-91ab-1eb7185d51a2","name":"errorPreprocessor","type":"n8n-nodes-base.set","position":[700,-980],"parameters":{"options":{},"assignments":{"assignments":[{"id":"d11831d7-533b-4132-9849-612e093d6b32","name":"prompt","type":"string","value":"={{ $('ChatCore').item.json.output }} It is mandatory to add a description of the image you are going to make."}]}},"typeVersion":3.4},{"id":"804fcbd3-cbc1-41d9-bbeb-40469545012f","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[-860,-1240],"parameters":{"color":4,"width":380,"height":680,"content":"### 2. Memory and Conversational Context\n\nRetrieves the necessary context to properly infer intentions.\n\n- conversationStore: stores the entire conversation history.\n\n- memoryRetriever: extracts relevant information according to the current need.\n\n- latestContext: formats and prepares the context to be useful in response generation.\n"},"typeVersion":1},{"id":"4b4e8510-6b97-4b1d-afdb-916581aa539d","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[-1220,-1240],"parameters":{"color":5,"width":340,"height":680,"content":"### 1. Input and Session Management\n\nReceives messages from Telegram and manages the session to maintain context.\n\n- userInput: captures the user's message.\n\n- sessionData: saves and updates the session state.\n"},"typeVersion":1},{"id":"6b14b58f-2e17-4cfb-baf4-3318b3fd9533","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[-460,-1240],"parameters":{"color":6,"width":700,"height":680,"content":"### 3. Intent Processing and Prompt Generation\nAnalyzes the intention and selects appropriate prompts according to the user's intention.\n\n- inputProcessor: detects intention and type of content to send.\n\n- intentHandler: redirects the flow based on the intention.\n\n- generatePrompt, chatPrompt, otherPrompt, buildPrompt: select the prompts for the response."},"typeVersion":1},{"id":"fa4cfc3f-cdaf-4184-b183-ca31b1aa1d86","name":"Sticky Note3","type":"n8n-nodes-base.stickyNote","position":[260,-1240],"parameters":{"color":3,"width":300,"height":680,"content":"### 4. Core of Generation and Conversation Management\nGenerates responses using Google Gemini, integrating context for coherence.\n\n- ChatCore: orchestrates the generation and management of the conversation.\n\n- GeminiModel: creates the final response based on prompts.\n\n- conversationMemory: stores information to maintain coherence."},"typeVersion":1},{"id":"ce598ece-492b-4294-9aa4-ea0c6757edf2","name":"Sticky Note4","type":"n8n-nodes-base.stickyNote","position":[580,-1240],"parameters":{"color":7,"width":800,"height":680,"content":"### 5. Content Classification and User Delivery\n\nDetermines the type of content and manages its delivery via Telegram.\n\n- contentType: defines the output format (text, image, etc.).\n\n- errorPreprocessor, textCleaner: clean and validate the content.\n\n- imageGeneration, imageBuilder: create visual content when necessary.\n\n- sendImage, sendTextMessage: send the content to the user."},"typeVersion":1}],"connections":{"ChatCore":{"main":[[{"node":"contentType","type":"main","index":0}]]},"userInput":{"main":[[{"node":"sessionData","type":"main","index":0}]]},"chatPrompt":{"main":[[{"node":"buildPrompt","type":"main","index":0}]]},"GeminiModel":{"ai_languageModel":[[{"node":"ChatCore","type":"ai_languageModel","index":0}]]},"buildPrompt":{"main":[[{"node":"ChatCore","type":"main","index":0}]]},"contentType":{"main":[[{"node":"errorPreprocessor","type":"main","index":0}],[{"node":"sendTextMessage","type":"main","index":0}]]},"otherPrompt":{"main":[[{"node":"buildPrompt","type":"main","index":0}]]},"sessionData":{"main":[[{"node":"conversationStore","type":"main","index":0}]]},"textCleaner":{"main":[[{"node":"imageGeneration","type":"main","index":0}]]},"GeminiModel1":{"ai_languageModel":[[{"node":"inputProcessor","type":"ai_languageModel","index":0}]]},"imageBuilder":{"main":[[{"node":"sendImage","type":"main","index":0}]]},"intentHandler":{"main":[[{"node":"generatePrompt","type":"main","index":0}],[{"node":"chatPrompt","type":"main","index":0}],[{"node":"otherPrompt","type":"main","index":0}]]},"latestContext":{"main":[[{"node":"inputProcessor","type":"main","index":0}]]},"generatePrompt":{"main":[[{"node":"buildPrompt","type":"main","index":0}]]},"inputProcessor":{"main":[[{"node":"intentHandler","type":"main","index":0}]]},"imageGeneration":{"main":[[{"node":"imageBuilder","type":"main","index":0}]]},"memoryRetriever":{"ai_memory":[[{"node":"conversationStore","type":"ai_memory","index":0}]]},"sendTextMessage":{"main":[[]]},"structuredOutput":{"ai_outputParser":[[{"node":"inputProcessor","type":"ai_outputParser","index":0}]]},"conversationStore":{"main":[[{"node":"latestContext","type":"main","index":0}]]},"errorPreprocessor":{"main":[[{"node":"textCleaner","type":"main","index":0}]]},"conversationMemory":{"ai_memory":[[{"node":"ChatCore","type":"ai_memory","index":0}]]}}}


name: Automate Email & Calendar Management with Gmail, Google Calendar & GPT-4o AI
author_name: AOE Agent Lab
author_username: aoepeople
categories: []
created_at: 2025-05-24T22:05:58.327Z
updated_at: 2025-05-24T22:05:58.327Z
url: https://n8n.io/workflows/4366
scraped_at: 2025-06-19 22:48:44
description:
  Boost your productivity with this AI-powered email and calendar assistant:

  This AI-powered template has 2 workflows. It manages your Gmail inbox and Google Calendar, classifies emails with custom labels, and suggests replies and meeting times — all fully automated with OpenAI and n8n.


  Automatically analyze your Gmail inbox

  Suggest replies, priorities, and meeting times

  Checks your Google Calendar for conflicts and free slots

  Maintain conversation context using Thread History Vector Store

  The agent proactively acts using a Tools Agent architecture, with integrated memory and real-time tool invocation. It's perfect for busy professionals who want a personal assistant for communication and scheduling.

  Included features:

  ✅ Do actions on incoming mails 8like Labeling etc)
  ✅ Summarize and Assist fot the latest emails
  ✅ Draft replies and schedule meetings contextually
  ✅ Handle time zone conversion and MessageID referencing
  ✅ Context retention of last conversation history - using VectorStore

  📦 Requirements:

  Gmail + Google Calendar credentials via n8n credentials

  OpenAI API key

  n8n VectorStore nodes (or external integration like Pinecone, Qdrant, or Chroma)

nodes_used:
  ["n8n-nodes-base.gmail","n8n-nodes-base.code","@n8n/n8n-nodes-langchain.agent","@n8n/n8n-nodes-langchain.embeddingsOpenAi","@n8n/n8n-nodes-langchain.lmChatOpenAi","@n8n/n8n-nodes-langchain.memoryBufferWindow","@n8n/n8n-nodes-langchain.textSplitterTokenSplitter","@n8n/n8n-nodes-langchain.vectorStoreInMemory","@n8n/n8n-nodes-langchain.documentDefaultDataLoader","@n8n/n8n-nodes-langchain.textClassifier","@n8n/n8n-nodes-langchain.toolVectorStore"]

workflow_json:
  {"id":"leftLsw8mj6dIDBp","meta":{"instanceId":"88b34e051213082619adc89dcb3c4c6a3611f57a17080c0af86efd3b8840b94f","templateCredsSetupCompleted":true},"name":"[AOE]  Inbox & Calendar Management Agent","tags":[],"nodes":[{"id":"2b6b584a-db48-414e-9469-0134dff9ebce","name":"When chat message received","type":"@n8n/n8n-nodes-langchain.chatTrigger","position":[120,240],"webhookId":"2da65603-a805-4491-a175-8e89e5223916","parameters":{"options":{}},"typeVersion":1.1},{"id":"61207c74-2086-4ee1-8bdf-96056534e509","name":"OpenAI Chat Model","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[720,420],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o","cachedResultName":"gpt-4o"},"options":{}},"credentials":{"openAiApi":{"id":"XX","name":"OpenAi account (n8n project)"}},"typeVersion":1.2},{"id":"c6e43767-eb96-4557-88ac-f5a5ca9f00cc","name":"Window Buffer Memory","type":"@n8n/n8n-nodes-langchain.memoryBufferWindow","position":[880,420],"parameters":{"sessionKey":"={{ $('sessionId-master').item.json.sessionId }}","sessionIdType":"customKey","contextWindowLength":10},"typeVersion":1.3},{"id":"912b82ce-e8c1-45bd-9ddf-d6b269de94c3","name":"When Executed by Another Workflow","type":"n8n-nodes-base.executeWorkflowTrigger","position":[120,80],"parameters":{"workflowInputs":{"values":[{"name":"sessionId"},{"name":"chatInput"}]}},"typeVersion":1.1},{"id":"fdb327a9-dcce-41ee-b6e8-d84a3d6ef9b9","name":"sessionId-master","type":"n8n-nodes-base.noOp","position":[600,240],"parameters":{},"typeVersion":1},{"id":"2d3c1764-fc33-4142-ad56-da4eb3231090","name":"Get last emails","type":"n8n-nodes-base.gmailTool","position":[540,760],"webhookId":"337cc370-cea4-4c29-bf30-2437e5d7609e","parameters":{"limit":"={{ $fromAI(\"limit\", \"The maximal number of mails to receive.\", \"number\") }}","filters":{"q":"in:inbox"},"operation":"getAll","descriptionType":"manual","toolDescription":"Consume the Gmail API to get the last emails"},"credentials":{"gmailOAuth2":{"id":"XXXX","name":"Gmail account XXXX@gmail.com"}},"typeVersion":2.1},{"id":"b3f00e8e-4354-43fe-8ee2-b8a86a79a1ea","name":"Get calendar events","type":"n8n-nodes-base.googleCalendarTool","position":[1160,800],"parameters":{"limit":"={{ $fromAI('limit','the amount of event',\"number\") }}","options":{},"timeMax":"={{ $fromAI('end','end date in format \"2017-07-01T13:00:00+02:00\"') }}","timeMin":"={{ $fromAI('start','start date in format \"2017-07-01T13:00:00+02:00\"') }}","calendar":{"__rl":true,"mode":"list","value":"XXXX@gmail.com","cachedResultName":"XXXX@gmail.com"},"operation":"getAll","descriptionType":"manual","toolDescription":"Consume Google Calendar API to receive a list of calendar events between \"start\" and \"end\". Make sure to pass datetime."},"credentials":{"googleCalendarOAuth2Api":{"id":"YY","name":"Google Calendar account"}},"typeVersion":1.3},{"id":"acfd68ec-4c61-437c-a0e4-95d676d995e6","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[100,-860],"parameters":{"width":1500,"height":720,"content":"## Email Sorting Agent\n"},"typeVersion":1},{"id":"e9526541-84cd-4b98-a24e-9c7e5d8d3d0d","name":"When clicking ‘Test workflow’","type":"n8n-nodes-base.manualTrigger","position":[1840,-760],"parameters":{},"typeVersion":1},{"id":"22156318-e308-41a9-aa9e-df1fc40a85b5","name":"Gmail - get recent Threads","type":"n8n-nodes-base.gmail","position":[2140,-560],"webhookId":"5c988c0a-67f8-4d16-9525-518bf9049c90","parameters":{"filters":{},"resource":"thread"},"credentials":{"gmailOAuth2":{"id":"XXXX","name":"Gmail account XXXX@gmail.com"}},"typeVersion":2.1},{"id":"c26da13c-8d94-48fc-a62e-05c21340ca06","name":"Gmail1","type":"n8n-nodes-base.gmail","position":[2360,-560],"webhookId":"3da4a75a-ee55-483e-b5e0-24f34d4db217","parameters":{"options":{},"resource":"thread","threadId":"={{ $json.id }}","operation":"get"},"credentials":{"gmailOAuth2":{"id":"XXXX","name":"Gmail account XXXX@gmail.com"}},"typeVersion":2.1},{"id":"7d69096c-6a05-4ad3-9428-1cef0d76205c","name":"Embeddings OpenAI","type":"@n8n/n8n-nodes-langchain.embeddingsOpenAi","position":[2780,-240],"parameters":{"options":{}},"credentials":{"openAiApi":{"id":"XX","name":"OpenAi account (n8n project)"}},"typeVersion":1.2},{"id":"583787f7-b378-43f7-9737-189b2fd29855","name":"Default Data Loader","type":"@n8n/n8n-nodes-langchain.documentDefaultDataLoader","position":[3020,-380],"parameters":{"options":{"metadata":{"metadataValues":[{"name":"threadId","value":"={{ $json.id }}"}]}},"jsonData":"={{ $json.emailSummary }}","jsonMode":"expressionData"},"typeVersion":1},{"id":"d889a564-d810-430f-8470-eecac9717d7a","name":"Token Splitter","type":"@n8n/n8n-nodes-langchain.textSplitterTokenSplitter","position":[3040,-240],"parameters":{"chunkSize":2000},"typeVersion":1},{"id":"38842f34-bbd4-40d2-a636-3b42b51f3566","name":"Code - Summarize Email Thread as Text","type":"n8n-nodes-base.code","position":[2580,-560],"parameters":{"mode":"runOnceForEachItem","jsCode":"const result = {}\n\nfunction summarizeConversation(messages) {\n  return messages.map(msg => {\n    const date = new Date(Number(msg.internalDate)).toISOString();\n    return `\n\n📅 ${date}\n📨 From: ${msg.From}\n📥 To: ${msg.To}\n📌 Subject: ${msg.Subject}\n\n${msg.snippet}\n`.trim();\n  }).join(\"\\n\\n-----------------------\\n\\n\");\n}\n\n$json.emailSummary = summarizeConversation($json.messages);\n\nreturn $json;"},"typeVersion":2},{"id":"6dde2109-42ca-4cf9-885e-5d928949b9ad","name":"Embeddings OpenAI1","type":"@n8n/n8n-nodes-langchain.embeddingsOpenAi","position":[1800,960],"parameters":{"options":{}},"credentials":{"openAiApi":{"id":"XX","name":"OpenAi account (n8n project)"}},"typeVersion":1.2},{"id":"fd638fb0-db5f-43fc-816d-6c5462204982","name":"OpenAI Chat Model1","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[2080,760],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o-mini"},"options":{}},"credentials":{"openAiApi":{"id":"XX","name":"OpenAi account (n8n project)"}},"typeVersion":1.2},{"id":"18985af7-84c9-4c86-9e9f-a42f2b0bc216","name":"Delete an email","type":"n8n-nodes-base.gmailTool","position":[900,780],"webhookId":"0cfb9fbe-ec02-4ab3-87ac-ab949efdfe50","parameters":{"messageId":"={{ $fromAI('Message_ID', ``, 'string') }}","operation":"delete","descriptionType":"manual","toolDescription":"Call the Gmail API to delete an email. Always request the email message id before calling this tool."},"credentials":{"gmailOAuth2":{"id":"XXXX","name":"Gmail account XXXX@gmail.com"}},"typeVersion":2.1},{"id":"e59a937e-7392-4348-a7d3-1973c69f1d2f","name":"Create an Email Draft as response to a thread","type":"n8n-nodes-base.gmailTool","position":[580,920],"webhookId":"471a112a-9787-4fa1-b681-8b69395d631a","parameters":{"message":"={{ $fromAI('Message', `The Text that should be send in reply`, 'string') }}","options":{"sendTo":"={{ $fromAI('To_Email', `The email adress of the sender`, 'string') }}","threadId":"={{ $fromAI('thread-ID', `The ID of the thread. Need to be received from the Email Tool Response. Use the exact ID and better call the Get Email Tool again`, 'string') }}"},"subject":"={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('Subject', ``, 'string') }}","resource":"draft","descriptionType":"manual","toolDescription":"Call Gmail API to create a Draft message as Reply To an existing email or email thread. Pass the correct Thread-Id of the message. To get the Thread ID call the Get Email Tool before."},"credentials":{"gmailOAuth2":{"id":"XXXX","name":"Gmail account XXXX@gmail.com"}},"typeVersion":2.1},{"id":"7002b9d3-01b2-4dd0-8a33-258c17836330","name":"Create an New Email Draft","type":"n8n-nodes-base.gmailTool","position":[740,760],"webhookId":"0321c8e3-b0c1-44ff-9e8b-671db71e3f51","parameters":{"message":"={{ $fromAI('Message', `The Text that should be send in reply`, 'string') }}","options":{"sendTo":"={{ $fromAI('To_Email', `The email adress of the sender`, 'string') }}"},"subject":"={{ $fromAI('Subject', ``, 'string') }}","resource":"draft","descriptionType":"manual","toolDescription":"Call Gmail API to create a New outgoing Draft message."},"credentials":{"gmailOAuth2":{"id":"XXXX","name":"Gmail account XXXX@gmail.com"}},"typeVersion":2.1},{"id":"350497b8-4acb-49e2-ad26-e55cd51c30f3","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[500,660],"parameters":{"width":520,"height":460,"content":"## Email Access Tools"},"typeVersion":1},{"id":"56ba48de-1190-4fc2-bac0-1d2a3eac6cb6","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[1100,660],"parameters":{"color":6,"width":520,"height":460,"content":"## Calender Access Tools"},"typeVersion":1},{"id":"86aaa5cf-47e3-4a31-9116-2f09d98ed559","name":"Add an calender entry","type":"n8n-nodes-base.googleCalendarTool","position":[1360,800],"parameters":{"end":"={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('End', ``, 'string') }}","start":"={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('Start', ``, 'string') }}","calendar":{"__rl":true,"mode":"list","value":"XXXX@gmail.com","cachedResultName":"XXXX@gmail.com"},"descriptionType":"manual","toolDescription":"Consume Google Calendar API to add a new event or meeting to the calender","additionalFields":{"summary":"={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('Summary', ``, 'string') }}","description":"={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('Description', ``, 'string') }}"}},"credentials":{"googleCalendarOAuth2Api":{"id":"YY","name":"Google Calendar account"}},"typeVersion":1.3},{"id":"14bfc40d-0efb-4b00-a77b-917166a278a1","name":"Sticky Note3","type":"n8n-nodes-base.stickyNote","position":[1700,500],"parameters":{"color":5,"width":520,"height":620,"content":"## Knowlede about past email conversations"},"typeVersion":1},{"id":"83470865-9e68-4ee9-ba7d-5f6130a71b4d","name":"Gmail Trigger","type":"n8n-nodes-base.gmailTrigger","position":[240,-540],"parameters":{"filters":{},"pollTimes":{"item":[{"mode":"everyMinute"}]}},"credentials":{"gmailOAuth2":{"id":"XXXX","name":"Gmail account XXXX@gmail.com"}},"typeVersion":1.2},{"id":"00b10246-a5a3-4ea5-a570-e109821e6b8d","name":"OpenAI Chat Model2","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[560,-300],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4.1-mini","cachedResultName":"gpt-4.1-mini"},"options":{}},"credentials":{"openAiApi":{"id":"XX","name":"OpenAi account (n8n project)"}},"typeVersion":1.2},{"id":"7ed7143e-4e63-40cc-bfd2-82405057ef79","name":"Gmail label as kunde","type":"n8n-nodes-base.gmail","position":[1200,-640],"webhookId":"13291755-e6d5-435e-8601-b20b5ed7e866","parameters":{"labelIds":["Label_4725571417728382593"],"messageId":"={{ $json.id }}","operation":"addLabels"},"credentials":{"gmailOAuth2":{"id":"XXXX","name":"Gmail account XXXX@gmail.com"}},"typeVersion":2.1},{"id":"8d2ffc73-3fe3-48ed-a4b4-e4e9707435ff","name":"Sticky Note4","type":"n8n-nodes-base.stickyNote","position":[1740,-900],"parameters":{"color":4,"width":1680,"height":780,"content":"## Email Thread Knowledge adder"},"typeVersion":1},{"id":"1b6b3558-6bd5-49c6-85b5-d8661f204f26","name":"Get an email by MessageID","type":"n8n-nodes-base.gmailTool","position":[800,940],"webhookId":"2f916427-b445-4c08-841f-bd13b5f99c85","parameters":{"messageId":"={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('Message_ID', ``, 'string') }}","operation":"get","descriptionType":"manual","toolDescription":"Consume the Gmail API to receive an email by message-id"},"credentials":{"gmailOAuth2":{"id":"XXXX","name":"Gmail account XXXX@gmail.com"}},"typeVersion":2.1},{"id":"bbdfdfd9-f35d-4e02-aa31-6ad39ba27b4d","name":"Research context and infos in previous conversations","type":"@n8n/n8n-nodes-langchain.toolVectorStore","position":[1840,560],"parameters":{"description":"Can answer questions and do research in previous email conversations. Use this tool whenever you need more context about past conversations to an email. \nFor better retrieval and more context always pass the email-adresses to the query!\n"},"typeVersion":1.1},{"id":"f52a8a15-2a2c-4191-ad87-2a1a1a714896","name":"Gmail - Label as Colleges","type":"n8n-nodes-base.gmail","position":[1200,-800],"webhookId":"3e488d4d-5528-48c7-b363-1391368efd8e","parameters":{"labelIds":["Label_749967004333244217"],"messageId":"={{ $json.id }}","operation":"addLabels"},"credentials":{"gmailOAuth2":{"id":"XXXX","name":"Gmail account XXXX@gmail.com"}},"typeVersion":2.1},{"id":"72bf9803-02ce-48a9-bf6a-e64ab211ddf6","name":"EMail Agent","type":"@n8n/n8n-nodes-langchain.agent","position":[1060,240],"parameters":{"text":"={{ $json.chatInput }}","options":{"systemMessage":"=# AI Assistant Prompt – Inbox & Calendar\n\n## Role  \nYou are my personal AI assistant for email and calendar management.  \nI am Daniel Pötzinger, CTO of AOE.  \nYou support me in organizing my Gmail inbox, keeping track of important topics, handling emails, and managing appointments efficiently.  \nYou provide suggestions and analyses, and act autonomously when retrieving information using the available tools.\n\n---\n\n## Scope  \nYou analyze emails and calendar data, identify relevant information, prioritize, and assist in processing.  \nYou can access email content, draft responses, suggest calendar entries, and identify available time slots – based on the tools provided. Use the tools proactively.\n\n> Today is `{{ $now }}` in timezone +2.  \n> The user is in timezone +2.\n\n---\n\n## Command\n\n- Regularly provide an overview of current and prioritized emails.  \n- Detect requests, invitations, or to-dos in emails and suggest appropriate actions or scheduling.  \n- Propose meaningful draft replies suitable to the context.  \n- Monitor the calendar for upcoming appointments, conflicts, or free time slots.  \n- Suggest daily or weekly structures based on calendar availability.  \n- Support planning and coordination directly from the context of emails.  \n- When suggesting appointments, always check availability in the calendar.  \n- Note that calendar timestamps are in UTC and must be converted before evaluation and display.  \n- When handling emails and using the corresponding tools, remember the `MessageID` so it can be passed to other tools.  \n  Always show the `MessageID` to the user so it remains accessible in your conversation history.\n\n---\n\n## Format\n\n- Clear, structured presentation of suggestions (e.g., lists, tables, bullet points).  \n- Draft replies must always be **friendly and professional** – respectful, clear, without unnecessary phrasing.  \n- Calendar and time suggestions must be easy to read (e.g., “next Tuesday at 2:00 PM”).\n\n---\n\n## Constraints\n\n- Only send emails or create appointments after confirmation from the user.  \n- Always act in the spirit of **relief, clarity, and efficiency**.\n"},"promptType":"define"},"typeVersion":1.7},{"id":"76fa4e5c-110f-48b1-86f0-7fc7302b7f66","name":"Classify Emails","type":"@n8n/n8n-nodes-langchain.textClassifier","onError":"continueErrorOutput","position":[560,-680],"parameters":{"options":{"fallback":"other"},"inputText":"=Email Subject: {{ $json.Subject }}\n\nEMail From: {{ $json.From }}\n\n------\n##Email Snippet: \n{{ $json.snippet }}\n\n","categories":{"categories":[{"category":"Kollegen","description":"any email from colleagues with the sender @example.com"},{"category":"Kunden","description":"Every email with an existing contact in the CRM or that sounds like a customer.|Also mails that sound like a customer inquiry and mails that show a project reference."}]}},"typeVersion":1},{"id":"c6bb5664-fa45-4f80-af22-97786da79deb","name":"Write - Threads History Vector Store","type":"@n8n/n8n-nodes-langchain.vectorStoreInMemory","position":[2900,-560],"parameters":{"mode":"insert","clearStore":true},"typeVersion":1.1},{"id":"62cb4909-8dd1-4a5e-b0c8-cc8a6e708433","name":"Read- Threads History Vector Store","type":"@n8n/n8n-nodes-langchain.vectorStoreInMemory","position":[2820,-760],"parameters":{"mode":"load","topK":100,"prompt":"workshop"},"typeVersion":1.1},{"id":"e0e0b246-0091-4cef-97ea-18f1b48d9dd9","name":"Threads History Vector Store","type":"@n8n/n8n-nodes-langchain.vectorStoreInMemory","position":[1780,780],"parameters":{},"typeVersion":1.1},{"id":"c3cff5e3-24a0-4272-9e43-ea781784f64d","name":"Sticky Note7","type":"n8n-nodes-base.stickyNote","position":[-460,0],"parameters":{"color":3,"width":480,"height":440,"content":"## Main Inbox Assistance Agent\n\n### Before Using\n** Modify the classifier agent for your needs. Add the Labels in GMail before, if you want to assign labels.\n** Add proper credentials\n** Modify the Prompts (e.g. give more context about your role and company)\n\n### More on professional Agents:\n** From [AOE AI Lab](https://ai-radar.aoe.com/)"},"typeVersion":1},{"id":"ef343339-b6c5-4cde-bf74-89e6e254a337","name":"Determine the name of the day of the week","type":"n8n-nodes-base.dateTimeTool","position":[1240,960],"parameters":{"date":"={{ $fromAI('Date', ``, 'string') }}","format":"custom","options":{},"operation":"formatDate","customFormat":"EEEE dd MM ","descriptionType":"manual","outputFieldName":"=formattedDate","toolDescription":"Formats the date in the name of the day of the week. Always use this before you output weekdays."},"typeVersion":2}],"active":false,"pinData":{},"settings":{"executionOrder":"v1"},"versionId":"221a80b7-bc6f-4443-afe8-07806d453809","connections":{"Gmail1":{"main":[[{"node":"Code - Summarize Email Thread as Text","type":"main","index":0}]]},"EMail Agent":{"main":[[]]},"Gmail Trigger":{"main":[[{"node":"Classify Emails","type":"main","index":0},{"node":"Gmail - get recent Threads","type":"main","index":0}]]},"Token Splitter":{"ai_textSplitter":[[{"node":"Default Data Loader","type":"ai_textSplitter","index":0}]]},"Classify Emails":{"main":[[{"node":"Gmail - Label as Colleges","type":"main","index":0}],[{"node":"Gmail label as kunde","type":"main","index":0}]]},"Delete an email":{"ai_tool":[[{"node":"EMail Agent","type":"ai_tool","index":0}]]},"Get last emails":{"ai_tool":[[{"node":"EMail Agent","type":"ai_tool","index":0}]]},"sessionId-master":{"main":[[{"node":"EMail Agent","type":"main","index":0}]]},"Embeddings OpenAI":{"ai_embedding":[[{"node":"Read- Threads History Vector Store","type":"ai_embedding","index":0},{"node":"Write - Threads History Vector Store","type":"ai_embedding","index":0}]]},"OpenAI Chat Model":{"ai_languageModel":[[{"node":"EMail Agent","type":"ai_languageModel","index":0}]]},"Embeddings OpenAI1":{"ai_embedding":[[{"node":"Threads History Vector Store","type":"ai_embedding","index":0}]]},"OpenAI Chat Model1":{"ai_languageModel":[[{"node":"Research context and infos in previous conversations","type":"ai_languageModel","index":0}]]},"OpenAI Chat Model2":{"ai_languageModel":[[{"node":"Classify Emails","type":"ai_languageModel","index":0}]]},"Default Data Loader":{"ai_document":[[{"node":"Write - Threads History Vector Store","type":"ai_document","index":0}]]},"Get calendar events":{"ai_tool":[[{"node":"EMail Agent","type":"ai_tool","index":0}]]},"Window Buffer Memory":{"ai_memory":[[{"node":"EMail Agent","type":"ai_memory","index":0}]]},"Add an calender entry":{"ai_tool":[[{"node":"EMail Agent","type":"ai_tool","index":0}]]},"Create an New Email Draft":{"ai_tool":[[{"node":"EMail Agent","type":"ai_tool","index":0}]]},"Get an email by MessageID":{"ai_tool":[[{"node":"EMail Agent","type":"ai_tool","index":0}]]},"Gmail - get recent Threads":{"main":[[{"node":"Gmail1","type":"main","index":0}]]},"When chat message received":{"main":[[{"node":"sessionId-master","type":"main","index":0}]]},"Threads History Vector Store":{"ai_vectorStore":[[{"node":"Research context and infos in previous conversations","type":"ai_vectorStore","index":0}]]},"When Executed by Another Workflow":{"main":[[{"node":"sessionId-master","type":"main","index":0}]]},"When clicking ‘Test workflow’":{"main":[[{"node":"Gmail - get recent Threads","type":"main","index":0}]]},"Code - Summarize Email Thread as Text":{"main":[[{"node":"Write - Threads History Vector Store","type":"main","index":0}]]},"Determine the name of the day of the week":{"ai_tool":[[{"node":"EMail Agent","type":"ai_tool","index":0}]]},"Create an Email Draft as response to a thread":{"ai_tool":[[{"node":"EMail Agent","type":"ai_tool","index":0}]]},"Research context and infos in previous conversations":{"ai_tool":[[{"node":"EMail Agent","type":"ai_tool","index":0}]]}}}


name: AI Real Estate Agent: End-to-End Ops Automation (Web, Data, Voice)
author_name: Sam Yassine
author_username: samyassine
categories: []
created_at: 2025-05-25T01:59:42.452Z
updated_at: 2025-05-25T01:59:42.452Z
url: https://n8n.io/workflows/4368
scraped_at: 2025-06-19 22:49:12
description:
  This suite automates distinct aspects of real estate operations: incoming web lead qualification, scheduled/manual data research and content generation, and automated voice call outreach with lead qualification. It leverages AI (primarily OpenAI GPT-4o Mini via Langchain), data processing nodes, and integrations with external APIs and Google Workspace.

  Workflow 1: Incoming Web Lead Qualification & Scoring
  This workflow captures leads from a web source, validates their input, uses AI to classify intent and urgency, checks against a property database, scores the lead, and prepares a structured lead object.

  Tools & Services Used:

  AI Core & Processing: OpenAI (GPT-4o Mini via Langchain Agent and Chat Model nodes)
  Data Processing: n8n Set, If, Code nodes
  External API: HTTP Request node (for PropertyCheckAPI)
  Workflow Overview:
  Trigger:
  Incoming Web Lead Webhook (/incoming-lead): Captures new leads submitted via a web form.
  Lead Data Ingestion & Validation:
  Set & Rename Incoming Lead Fields: Standardizes input field names from the webhook.
  IF User Message Valid: Checks if the userMessage field is present and meets a minimum length.
  Clean User Message Text (Code): Pre-processes the user's message (e.g., removes extra spaces).
  AI-Powered Lead Analysis:
  AI Classify Lead Intent & Urgency (Langchain Agent): Analyzes the cleaned user message to determine the lead's primary intent (e.g., buying, selling, inquiry) and the urgency of their request.
  Powered by: LLM for Lead Intent/Urgency Classification (OpenAI Chat Model - GPT-4o Mini).
  Extract Intent & Urgency from AI Output (Set): Structures the AI's classification into distinct fields.
  Data Standardization & Enrichment:
  Standardize All Lead Data Fields (Code): Further standardizes all collected data points for consistency.
  Call Property Check API (HTTP Request): Sends lead/property details to an external API (https://api.example.com/property-check) to verify listing status or gather more information.
  Lead Scoring & Finalization:
  IF Property is Known Listing: Checks the API response to see if a matchFound was "true".
  Calculate Web Lead Score (Code): If a known listing (or based on other criteria), this node assigns a numerical or categorical score to the lead.
  Set Final Structured Web Lead Data (Set): Consolidates all original, processed, classified, and scored data into a final, comprehensive lead object.
  Workflow 2: Scheduled/Manual AI-Powered Data Research & Content Generation (Red Background)
  This workflow fetches data from external URLs, extracts information using AI, allows a sophisticated AI agent to perform research and generate analysis using various tools, and outputs results to Google Sheets, Google Docs, and potentially other AI processing steps.

  Tools & Services Used:
  Orchestration & Automation: n8n
  AI Core & Processing: OpenAI (GPT-4o Mini via Langchain Information Extractor, Langchain Agent, and direct OpenAI nodes)
  AI Tools: Langchain Calculator, Langchain SerpAPI
  Data Storage & Output: Google Sheets, Google Docs
  Data Input: HTTP Request node

  Workflow Overview:
  Triggers:
  Manual Trigger for Data Analysis Flow: Allows on-demand execution.
  Scheduled Trigger for Data Analysis Flow: Automates execution on a defined schedule.
  Data Ingestion & Initial Extraction:
  Fetch External Data for AI Analysis (HTTP Request): Retrieves content from a specified URL.
  AI Extract Information from Fetched Data (Langchain Information Extractor): Uses an AI model to extract structured data from the fetched content.
  Powered by: LLM for Data Information Extractor (OpenAI Chat Model - GPT-4o Mini).
  Advanced AI Analysis & Tasking:
  AI Agent for Research & Content Generation (Langchain Agent): Processes the extracted information to perform in-depth research, analysis, or content creation.
  Powered by: LLM for Research & Content AI Agent (OpenAI Chat Model - GPT-4o Mini).
  Utilizes Tools:
  Calculator Tool for AI Agent: For numerical calculations.
  SerpAPI Web Search Tool for AI Agent: For performing real-time web searches to gather additional context or verify information.
  Output & Dissemination:
  The AI Agent's output is routed to multiple destinations:
  Update Google Doc with AI Agent Analysis (Google Docs): Inserts the generated analysis/content into a Google Document.
  Split AI Agent Output Items (Split Out) -&gt; Log AI Analysis Data to Google Sheets (Google Sheets): If the agent produces multiple data items, they are split and logged individually into a Google Sheet.
  OpenAI: Generate Text from Agent (Output 1) & OpenAI: Generate Text from Agent (Output 2): These nodes likely take the agent's output for further specialized AI processing (e.g., summarization for different purposes, reformatting).
  Workflow 3: Automated Lead Outreach & Voice Call Qualification (Green Background)
  This workflow automates the initial contact with new leads via a voice call, uses AI to understand the lead's responses during the call, qualifies them, and logs the detailed interaction and a summary.
  Tools & Services Used:
  Orchestration & Automation: n8n
  AI Core & Processing: OpenAI (GPT-4o Mini via Langchain Agent and Chat Model nodes)
  Voice Services: ElevenLabs (Text-to-Speech via HTTP Request), Twilio (Place Call via HTTP Request)
  Data Storage & Output: Google Sheets
  Error Handling: n8n Execute Workflow Trigger
  Workflow Overview:
  Trigger:
  Webhook for Voice Call Lead (/new-lead): Captures new leads designated for an automated voice call.
  Call Preparation & Initiation:
  Set Initial Voice Call Lead Details: Extracts basic lead info (name, phone, property ref, email) from the webhook.
  Generate Voice Call Introduction Script (Function): Creates a personalized script for the call.
  ElevenLabs: Convert Intro Script to Voice (HTTP Request): Sends the script to ElevenLabs API to generate natural-sounding audio.
  Twilio: Initiate Voice Call to Lead (HTTP Request): Uses Twilio API to place the call and play the generated audio.
  AI-Powered Call Interaction Analysis:
  AI Agent: Extract Info from Voice Call (Langchain Agent): Processes the interaction from the call (e.g., a transcript of the lead's responses, or DTMF inputs if designed to capture them) to extract key qualification data like budget, timeline, and interest level.
  Powered by: LLM for Voice Call Info Extraction Agent (OpenAI Chat Model - GPT-4o Mini).
  Structure Extracted Voice Call Info (Function): Organizes the AI-extracted data into a structured JSON object.
  Lead Qualification & Data Logging:
  Set Lead Status Based on Call Interest: Updates the lead's status (e.g., "Interested" or "Not Interested") based on the AI's interpretation of the call.
  IF Lead Interested (from Voice Call): Branches the workflow based on lead status.
  If Interested:
  Assign Score to Interested Voice Lead (Function): Calculates a lead score based on budget, timeline, etc.
  Format Current Timestamp for Logging (DateTime): Generates a timestamp.
  Log Qualified Voice Lead to Google Sheets: Appends the detailed, qualified lead information to a 'Leads' Google Sheet.
  AI Agent: Generate Voice Call Lead Summary (Langchain Agent): Creates a concise summary of the entire lead interaction and qualification.
  Powered by: LLM for Voice Call Lead Summary Agent (OpenAI Chat Model - GPT-4o Mini).
  Log Voice Call Lead Summary to Google Sheets: Appends this summary to a separate 'LeadsSummary' Google Sheet.
  Error Handling (for Sheets Logging):
  IF Voice Lead Logging to Sheets Failed: Checks if the Google Sheets logging operation was unsuccessful.
  Error Trigger: Notify Admin of Sheets Failure (Execute Workflow Trigger): If logging fails, triggers a separate workflow to alert an administrator.

nodes_used:
  ["n8n-nodes-base.googleSheets","n8n-nodes-base.httpRequest","n8n-nodes-base.googleDocs","n8n-nodes-base.code","@n8n/n8n-nodes-langchain.agent","@n8n/n8n-nodes-langchain.lmChatOpenAi","@n8n/n8n-nodes-langchain.toolCalculator","@n8n/n8n-nodes-langchain.toolSerpApi","@n8n/n8n-nodes-langchain.openAi","@n8n/n8n-nodes-langchain.informationExtractor"]

workflow_json:
  {"id":"y5Oi5ph95vGJCuOu","meta":{"instanceId":"5beb610c1ddaf0be11e46fd8edaf0e265560c93f1638f8638d6a8a7adf44f57e","templateCredsSetupCompleted":true},"name":"AI Real Estate Agent: End-to-End Ops Automation (Web, Data, Voice)","tags":[],"nodes":[{"id":"846dfc0c-036f-4044-bb02-ca588518438e","name":"IncomingLeadWebhook","type":"n8n-nodes-base.webhook","position":[-80,-100],"webhookId":"1fafa296-7860-4c95-af04-d7362df1f447","parameters":{},"typeVersion":1},{"id":"ec23faac-8b49-4356-a9cb-794594705b8d","name":"RenameInputFields","type":"n8n-nodes-base.set","position":[120,-100],"parameters":{},"typeVersion":1},{"id":"ad8c4d0c-ee65-4cbd-a1bc-d4e4e9f02333","name":"ValidateMessageExists","type":"n8n-nodes-base.if","position":[320,-100],"parameters":{},"typeVersion":1},{"id":"f2633126-3eb0-4502-b39e-136a13096341","name":"CleanUserText","type":"n8n-nodes-base.code","position":[520,-100],"parameters":{},"typeVersion":1},{"id":"498baba4-1fdf-4356-adf8-cc68596f1a18","name":"ClassifyIntentUrgency","type":"@n8n/n8n-nodes-langchain.agent","position":[720,-100],"parameters":{},"typeVersion":1},{"id":"8f1194c9-8ca5-4f34-9881-1fa0a4848b0d","name":"ExtractClassification","type":"n8n-nodes-base.set","position":[1100,-100],"parameters":{},"typeVersion":1},{"id":"d7d6ef45-150c-493a-afc7-27b6b8396ca8","name":"StandardizeFields","type":"n8n-nodes-base.code","position":[1300,-100],"parameters":{},"typeVersion":1},{"id":"0c1327b0-2cd7-4b42-a376-659d27d04f6e","name":"PropertyCheckAPI","type":"n8n-nodes-base.httpRequest","position":[1480,-100],"parameters":{},"typeVersion":1},{"id":"ea619d5d-41af-42be-9d41-80173cafc453","name":"IsKnownListing","type":"n8n-nodes-base.if","position":[1660,-100],"parameters":{},"typeVersion":1},{"id":"d99d19f8-ab38-426a-bb1d-4647859090f6","name":"CalculateLeadScore","type":"n8n-nodes-base.code","position":[1860,-100],"parameters":{},"typeVersion":1},{"id":"072a1f65-f402-405b-a311-c3f3d1457fbd","name":"CreateStructuredLeadObject","type":"n8n-nodes-base.set","position":[2100,-100],"parameters":{},"typeVersion":1},{"id":"ed869dfa-a0e8-406e-84e4-e5f8d583b9f7","name":"OpenAI Chat Model","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[720,60],"parameters":{},"typeVersion":1.2},{"id":"93843c00-b69b-4587-8e26-c1e8f1491f87","name":"When clicking ‘Test workflow’","type":"n8n-nodes-base.manualTrigger","position":[-60,940],"parameters":{},"typeVersion":1},{"id":"833dfae1-d069-4829-9709-6b38b81a5e4b","name":"Schedule Trigger","type":"n8n-nodes-base.scheduleTrigger","position":[-80,1140],"parameters":{},"typeVersion":1.2},{"id":"deb43171-ef71-4793-a144-15b356261377","name":"HTTP Request","type":"n8n-nodes-base.httpRequest","position":[360,920],"parameters":{},"typeVersion":4.2},{"id":"91f6160f-319f-4073-963d-23331410b39f","name":"Information Extractor","type":"@n8n/n8n-nodes-langchain.informationExtractor","position":[600,800],"parameters":{},"typeVersion":1},{"id":"dc5baf99-7ba1-4e93-a72c-32a3d2f947d6","name":"Split Out","type":"n8n-nodes-base.splitOut","position":[1500,500],"parameters":{},"typeVersion":1},{"id":"1cdeaf35-c50d-4c16-b1af-38f8f0ba5924","name":"Real Estate Data","type":"n8n-nodes-base.googleSheets","position":[1800,500],"parameters":{},"typeVersion":4.5},{"id":"67d0a46b-f81f-4a73-bd39-5c400b1eeefd","name":"AI Agent","type":"@n8n/n8n-nodes-langchain.agent","position":[1020,800],"parameters":{},"typeVersion":1.9},{"id":"b4eb5076-9bd5-47bd-9c2e-2c8cd32ff16e","name":"OpenAI Chat Model1","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[980,1020],"parameters":{},"typeVersion":1.2},{"id":"dfd02f4a-0c46-41d5-bb7a-c4297139dc8f","name":"Calculator","type":"@n8n/n8n-nodes-langchain.toolCalculator","position":[1100,1020],"parameters":{},"typeVersion":1},{"id":"41bede03-022d-4aa2-8903-783c9cd16f7c","name":"SerpAPI","type":"@n8n/n8n-nodes-langchain.toolSerpApi","position":[1220,1020],"parameters":{},"typeVersion":1},{"id":"2ed11c87-5359-447a-85a7-e862f37fb975","name":"Google Docs","type":"n8n-nodes-base.googleDocs","position":[1500,700],"parameters":{},"typeVersion":2},{"id":"0cfdff1f-d5c5-4142-b160-b3660ebff7c7","name":"OpenAI","type":"@n8n/n8n-nodes-langchain.openAi","position":[1420,900],"parameters":{},"typeVersion":1.8},{"id":"a3a30179-81e9-466b-b371-a5f342609fd3","name":"OpenAI1","type":"@n8n/n8n-nodes-langchain.openAi","position":[1420,1100],"parameters":{},"typeVersion":1.8},{"id":"5da0995a-207c-4f84-96ec-018c9417c2fc","name":"OpenAI Chat Model2","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[700,1020],"parameters":{},"typeVersion":1.2},{"id":"0cac1985-8109-43f7-96f1-5753846c9fdf","name":"Set Lead Variables","type":"n8n-nodes-base.set","position":[20,2220],"parameters":{},"typeVersion":1},{"id":"23e34ce3-83d0-45e3-be3d-29c93f23e23a","name":"Generate Intro Message","type":"n8n-nodes-base.function","position":[220,2220],"parameters":{},"typeVersion":1},{"id":"615b812b-220b-4363-b817-2343e420feda","name":"ElevenLabs - Generate Voice","type":"n8n-nodes-base.httpRequest","position":[420,2220],"parameters":{},"typeVersion":1},{"id":"6f7ee3f4-d37d-4298-86f4-06dbb3e03dfa","name":"Twilio - Place Call","type":"n8n-nodes-base.httpRequest","position":[620,2220],"parameters":{},"typeVersion":1},{"id":"6a46df3e-71c8-435c-b0f6-fae78d085557","name":"AI Agent - Extract Lead Info","type":"@n8n/n8n-nodes-langchain.agent","position":[820,2220],"parameters":{},"typeVersion":1},{"id":"8d7a1054-75b8-491b-8684-09ee042ddb0c","name":"Store Extracted Values","type":"n8n-nodes-base.function","position":[1160,2220],"parameters":{},"typeVersion":1},{"id":"79836a16-27c8-455f-a50d-a7d165fe2a1d","name":"Normalize User Data","type":"n8n-nodes-base.set","position":[1360,2220],"parameters":{},"typeVersion":1},{"id":"adabf889-2acc-4dbd-9dd5-9afee6b5a99e","name":"IF Lead Interested","type":"n8n-nodes-base.if","position":[1520,2220],"parameters":{},"typeVersion":1},{"id":"63048171-dffb-4e55-8763-378d3910e654","name":"Assign Lead Score","type":"n8n-nodes-base.function","position":[1760,2220],"parameters":{},"typeVersion":1},{"id":"decc8704-953c-4d23-bceb-30cc17a5fbdf","name":"Format Timestamp","type":"n8n-nodes-base.dateTime","position":[1960,2220],"parameters":{},"typeVersion":1},{"id":"ebc6a20f-a395-4cf4-bccb-9f408a8d39d0","name":"Google Sheets - Log Lead","type":"n8n-nodes-base.googleSheets","position":[2180,2220],"parameters":{},"typeVersion":1},{"id":"869c74a0-a87d-4c1a-8f5f-2d853e8f0778","name":"AI Agent - Lead Summary","type":"@n8n/n8n-nodes-langchain.agent","position":[2420,2220],"parameters":{},"typeVersion":1},{"id":"2247fdc7-b4e7-45c8-80b8-0bc62fd0dfcb","name":"Google Sheets - Log Summary","type":"n8n-nodes-base.googleSheets","position":[2800,2220],"parameters":{},"typeVersion":1},{"id":"726ac587-3a4c-45d0-9076-b94fcd6ee91c","name":"Webhook - New Lead1","type":"n8n-nodes-base.webhook","position":[-180,2220],"webhookId":"55cbb141-ef66-46e5-92e8-6a02064ffded","parameters":{},"typeVersion":1},{"id":"d89bfcf8-7481-459d-9cdd-2ef949a51d89","name":"OpenAI Chat Model3","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[2380,2400],"parameters":{},"typeVersion":1.2},{"id":"b976b8a3-b239-428c-aea6-4399ada309ca","name":"OpenAI Chat Model4","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[840,2440],"parameters":{},"typeVersion":1.2},{"id":"da482b4f-0fae-4d0a-a401-e895579e5b4f","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[-420,-460],"parameters":{"content":""},"typeVersion":1},{"id":"8234251a-2bae-4bcf-baa0-a47ab8987a33","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[-420,480],"parameters":{"content":""},"typeVersion":1},{"id":"3b19e5af-fcfb-4af8-baa2-1e62e00a36b0","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[-420,1580],"parameters":{"content":""},"typeVersion":1}],"active":false,"pinData":{},"settings":{"executionOrder":"v1"},"versionId":"0819af6c-aac2-4b73-af95-5172057c05db","connections":{"SerpAPI":{"ai_tool":[[{"node":"AI Agent","type":"ai_tool","index":0}]]},"AI Agent":{"main":[[{"node":"Google Docs","type":"main","index":0},{"node":"Split Out","type":"main","index":0},{"node":"OpenAI","type":"main","index":0},{"node":"OpenAI1","type":"main","index":0}]]},"Split Out":{"main":[[{"node":"Real Estate Data","type":"main","index":0}]]},"Calculator":{"ai_tool":[[{"node":"AI Agent","type":"ai_tool","index":0}]]},"Google Docs":{"main":[[]]},"HTTP Request":{"main":[[{"node":"Information Extractor","type":"main","index":0}]]},"CleanUserText":{"main":[[{"node":"ClassifyIntentUrgency","type":"main","index":0}]]},"IsKnownListing":{"main":[[{"node":"CalculateLeadScore","type":"main","index":0}]]},"Format Timestamp":{"main":[[{"node":"Google Sheets - Log Lead","type":"main","index":0}]]},"PropertyCheckAPI":{"main":[[{"node":"IsKnownListing","type":"main","index":0}]]},"Schedule Trigger":{"main":[[{"node":"HTTP Request","type":"main","index":0}]]},"Assign Lead Score":{"main":[[{"node":"Format Timestamp","type":"main","index":0}]]},"OpenAI Chat Model":{"ai_languageModel":[[{"node":"ClassifyIntentUrgency","type":"ai_languageModel","index":0}]]},"RenameInputFields":{"main":[[{"node":"ValidateMessageExists","type":"main","index":0}]]},"StandardizeFields":{"main":[[{"node":"PropertyCheckAPI","type":"main","index":0}]]},"CalculateLeadScore":{"main":[[{"node":"CreateStructuredLeadObject","type":"main","index":0}]]},"IF Lead Interested":{"main":[[{"node":"Assign Lead Score","type":"main","index":0}]]},"OpenAI Chat Model1":{"ai_languageModel":[[{"node":"AI Agent","type":"ai_languageModel","index":0}]]},"OpenAI Chat Model2":{"ai_languageModel":[[{"node":"Information Extractor","type":"ai_languageModel","index":0}]]},"OpenAI Chat Model3":{"ai_languageModel":[[{"node":"AI Agent - Lead Summary","type":"ai_languageModel","index":0}]]},"OpenAI Chat Model4":{"ai_languageModel":[[{"node":"AI Agent - Extract Lead Info","type":"ai_languageModel","index":0}]]},"Set Lead Variables":{"main":[[{"node":"Generate Intro Message","type":"main","index":0}]]},"IncomingLeadWebhook":{"main":[[{"node":"RenameInputFields","type":"main","index":0}]]},"Normalize User Data":{"main":[[{"node":"IF Lead Interested","type":"main","index":0}]]},"Twilio - Place Call":{"main":[[{"node":"AI Agent - Extract Lead Info","type":"main","index":0}]]},"Webhook - New Lead1":{"main":[[{"node":"Set Lead Variables","type":"main","index":0}]]},"ClassifyIntentUrgency":{"main":[[{"node":"ExtractClassification","type":"main","index":0}]]},"ExtractClassification":{"main":[[{"node":"StandardizeFields","type":"main","index":0}]]},"Information Extractor":{"main":[[{"node":"AI Agent","type":"main","index":0}]]},"ValidateMessageExists":{"main":[[{"node":"CleanUserText","type":"main","index":0}]]},"Generate Intro Message":{"main":[[{"node":"ElevenLabs - Generate Voice","type":"main","index":0}]]},"Store Extracted Values":{"main":[[{"node":"Normalize User Data","type":"main","index":0}]]},"AI Agent - Lead Summary":{"main":[[{"node":"Google Sheets - Log Summary","type":"main","index":0}]]},"Google Sheets - Log Lead":{"main":[[{"node":"AI Agent - Lead Summary","type":"main","index":0}]]},"ElevenLabs - Generate Voice":{"main":[[{"node":"Twilio - Place Call","type":"main","index":0}]]},"AI Agent - Extract Lead Info":{"main":[[{"node":"Store Extracted Values","type":"main","index":0}]]},"When clicking ‘Test workflow’":{"main":[[{"node":"HTTP Request","type":"main","index":0}]]}}}


name: Auto Meeting Summarizer with Google Drive, OpenAI Whisper & GPT-4 to Sheets
author_name: Yaron Been
author_username: yaron-nofluff
nodes_used: ["n8n-nodes-base.googleSheets","n8n-nodes-base.googleDrive","@n8n/n8n-nodes-langchain.openAi"]
categories: []
created_at: 2025-05-25T05:37:57.429Z
updated_at: 2025-05-25T05:37:57.429Z
url: https://n8n.io/workflows/4370
scraped_at: 2025-06-19 22:49:57
description:
  🎤 Audio-to-Insights: Auto Meeting Summarizer

  Transform your meeting recordings into actionable insights automatically. This powerful n8n workflow monitors your Google Drive for new audio files, transcribes them using OpenAI's Whisper, generates intelligent summaries with ChatGPT, and logs everything in Google Sheets - all without lifting a finger.

  🔄 How It Works

  This workflow operates as a seamless 6-step automation pipeline:

  Step 1: Smart Detection
  The workflow continuously monitors a designated Google Drive folder (polls every minute) for newly uploaded audio files.

  Step 2: Secure Download
  When a new audio file is detected, the system automatically downloads it from Google Drive for processing.

  Step 3: AI Transcription
  OpenAI's Whisper technology converts your audio recording into accurate text transcription, supporting multiple audio formats.

  Step 4: Intelligent Summarization
  ChatGPT processes the transcript using a specialized prompt that extracts:
  Key discussion points and decisions
  Action items with assigned persons and deadlines
  Priority levels and follow-up tasks
  Clean, professional formatting

  Step 5: Timestamp Generation
  The system automatically adds the current date and formats it consistently for tracking purposes.

  Step 6: Automated Logging
  The final summary is appended to your Google Sheets document with the date, creating a searchable archive of all meeting insights.

  ⚙️ Setup Steps

  Prerequisites
  Before setting up the workflow, ensure you have:
  Active Google Drive account
  OpenAI API key with credits
  Google Sheets access
  n8n instance (cloud or self-hosted)

  Configuration Steps

  1. Credential Setup
  Google Drive OAuth2**: Required for folder monitoring and file downloads
  OpenAI API Key**: Needed for both transcription (Whisper) and summarization (ChatGPT)
  Google Sheets OAuth2**: Essential for writing summaries to your spreadsheet

  2. Google Drive Configuration
  Create a dedicated folder in Google Drive for meeting recordings
  Copy the folder ID from the URL (the long string after /folders/)
  Update the folderToWatch parameter in the workflow

  3. Google Sheets Preparation
  Create a new Google Sheet or use an existing one
  Ensure it has columns: Date and Meeting Summary
  Copy the spreadsheet ID from the URL
  Update the documentId parameter in the workflow

  4. Audio Requirements
  Supported Formats**: MP3, WAV, M4A, MP4
  Recommended Size**: Under 100MB for optimal processing
  Language**: Optimized for English (customizable for other languages)
  Quality**: Clear audio produces better transcriptions

  5. Workflow Activation
  Import the workflow JSON into your n8n instance
  Configure all credential connections
  Test with a sample audio file
  Activate the workflow trigger

  🚀 Use Cases

  Project Management
  Team Standup Summaries**: Convert daily standups into actionable task lists
  Sprint Retrospectives**: Extract improvement points and action items
  Stakeholder Updates**: Generate concise reports for leadership

  Sales & Customer Success
  Discovery Call Notes**: Capture prospect pain points and requirements
  Demo Follow-ups**: Track questions, objections, and next steps
  Customer Check-ins**: Monitor satisfaction and expansion opportunities

  Consulting & Professional Services
  Client Strategy Sessions**: Document recommendations and implementation plans
  Requirements Gathering**: Organize complex project specifications
  Progress Reviews**: Track deliverables and milestone achievements

  HR & Training
  Interview Debriefs**: Standardize candidate evaluation notes
  Training Sessions**: Create searchable knowledge bases
  Performance Reviews**: Document development plans and goals

  Research & Development
  Brainstorming Sessions**: Capture innovative ideas and concepts
  Technical Reviews**: Log decisions and architectural choices
  User Research**: Organize feedback and insights systematically

  💡 Advanced Customization Options

  Enhanced Summarization
  Modify the ChatGPT prompt to focus on specific elements:
  Add speaker identification for multi-person meetings
  Include sentiment analysis for customer calls
  Generate department-specific summaries (technical, sales, legal)
  Extract financial figures and metrics automatically

  Integration Expansions
  Slack Integration**: Auto-post summaries to relevant channels
  Email Notifications**: Send summaries to meeting participants
  CRM Updates**: Push action items directly to Salesforce/HubSpot
  Calendar Integration**: Schedule follow-up meetings based on action items

  Quality Improvements
  Audio Preprocessing**: Add noise reduction before transcription
  Multi-language Support**: Configure for international teams
  Custom Templates**: Create industry-specific summary formats
  Approval Workflows**: Add human review before final storage

  🛠️ Troubleshooting & Best Practices

  Common Issues
  Large File Processing**: Split recordings over 100MB into smaller segments
  Poor Audio Quality**: Use noise reduction tools before uploading
  API Rate Limits**: Implement delay nodes for high-volume usage
  Formatting Issues**: Adjust ChatGPT prompts for consistent output

  Optimization Tips
  Upload files in supported formats only
  Ensure stable internet connection for cloud processing
  Monitor OpenAI API usage and costs
  Regularly backup your Google Sheets data
  Test workflow changes with sample files first

  📊 Expected Outputs

  Sample Summary Format:
  Meeting Summary - March 15, 2024

  Key Discussion Points:
  Q1 budget review and allocation decisions
  New product launch timeline and milestones
  Team restructuring and role assignments

  Action Items:
  John: Finalize budget proposal by March 20th (High Priority)
  Sarah: Schedule product demo sessions for March 25th
  Team: Submit org chart feedback by March 18th

  Decisions Made:
  Approved additional marketing budget of $50K
  Delayed product launch to April 15th for quality assurance
  Promoted Lisa to Senior Developer role

  📞 Questions & Support

  For any questions, customizations, or technical support regarding this workflow:

  📧 Email Support
  Primary Contact**: Yaron@nofluff.online
  Response Time**: Within 24 hours on business days
  Best For**: Setup questions, customization requests, troubleshooting

  🎥 Learning Resources
  YouTube Channel**: https://www.youtube.com/@YaronBeen/videos
    Step-by-step setup tutorials
    Advanced customization guides  
    Workflow optimization tips

  🔗 Professional Network
  LinkedIn**: https://www.linkedin.com/in/yaronbeen/
    Connect for ongoing support
    Share your workflow success stories
    Get updates on new automation ideas

  💡 What to Include in Your Support Request
  Describe your specific use case
  Share any error messages or logs
  Mention your n8n version and setup type
  Include sample audio file characteristics (if relevant)

  Ready to transform your meeting chaos into organized insights? Download the workflow and start automating your meeting summaries today!

workflow_json:
  {"meta":{"instanceId":"5aaf4236c70e34e423fbdb2c7b754d19253a933bb1476d548f75848a01e473cf"},"nodes":[{"id":"ab3309d9-cb3e-4b13-bb43-a214722c50b4","name":"Looking for uploading file","type":"n8n-nodes-base.googleDriveTrigger","position":[1620,120],"parameters":{"event":"fileCreated","options":{},"pollTimes":{"item":[{"mode":"everyMinute"}]},"triggerOn":"specificFolder","folderToWatch":{"__rl":true,"mode":"list","value":"1Wjd0_fptBBBtLZySHt0qYPpZA_dBjyYi","cachedResultUrl":"https://drive.google.com/drive/folders/1Wjd0_fptBBBtLZySHt0qYPpZA_dBjyYi","cachedResultName":"meeting audio"}},"typeVersion":1},{"id":"6c7bed41-fcb2-46de-b764-f0df6bf15d72","name":"Download file","type":"n8n-nodes-base.googleDrive","position":[1920,120],"parameters":{"fileId":{"__rl":true,"mode":"id","value":"={{ $json.id }}"},"options":{},"operation":"download"},"typeVersion":3},{"id":"e44378ed-d689-4692-abe0-e9abc251dd40","name":"Transcribe the file","type":"@n8n/n8n-nodes-langchain.openAi","position":[2160,120],"parameters":{"options":{},"resource":"audio","operation":"transcribe"},"typeVersion":1.8},{"id":"b5cfacc7-59c6-47ad-8d4b-ce56f6c8b339","name":"Create summary","type":"@n8n/n8n-nodes-langchain.openAi","position":[2380,120],"parameters":{"modelId":{"__rl":true,"mode":"list","value":"gpt-4.1","cachedResultName":"GPT-4.1"},"options":{},"messages":{"values":[{"role":"system","content":"🧠 System Prompt: Meeting Summarizer & Action Item Extractor\n\nYou are an intelligent meeting assistant. Your job is to carefully listen to or read through the meeting transcript and:\n\nSummarize Key Discussion Points – Highlight the main topics discussed, decisions made, issues raised, and relevant insights. Keep it concise and organized.\n\nExtract Action Items – Identify specific tasks or follow-ups. For each action item, include:\n\nTask Description\n\nAssigned Person (if mentioned)\n\nDeadline (if mentioned)\n\nPriority (if indicated or can be inferred)\n\nUse clear formatting, such as bullet points and headings, to make the output easy to scan.\n\nTone: Professional, clear, and neutral.\nAvoid: Irrelevant chatter, filler content, or personal commentary.\nFocus on: Clarity, accuracy, and actionable information."},{"content":"={{ $json.text }}"}]}},"typeVersion":1.8},{"id":"da7cec5f-301d-456b-8ca6-f6b676579e2d","name":"Get date","type":"n8n-nodes-base.dateTime","position":[2760,120],"parameters":{"options":{},"outputFieldName":"Date"},"typeVersion":2},{"id":"b51f7dc9-2973-4f03-b160-90dc3ac0c0d2","name":"Format date","type":"n8n-nodes-base.dateTime","position":[3060,120],"parameters":{"date":"={{ $json.Date }}","options":{},"operation":"formatDate"},"typeVersion":2},{"id":"dc26f36b-7781-472f-86f4-6bd83270c95f","name":"Save the summary","type":"n8n-nodes-base.googleSheets","position":[3320,120],"parameters":{"columns":{"value":{"Date":"={{ $json.formattedDate }}","Meeting Summary":"={{ $('Create summary').item.json.message.content }}"},"schema":[{"id":"Date","type":"string","display":true,"removed":false,"required":false,"displayName":"Date","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Meeting Summary","type":"string","display":true,"required":false,"displayName":"Meeting Summary","defaultMatch":false,"canBeUsedToMatch":true}],"mappingMode":"defineBelow","matchingColumns":["Date"],"attemptToConvertTypes":false,"convertFieldsToString":false},"options":{},"operation":"append","sheetName":{"__rl":true,"mode":"list","value":"gid=0","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1JZnhAhr8x2UzzTQbT5l9PXguKkSM1NlznM8LX66-2Nc/edit#gid=0","cachedResultName":"Sheet1"},"documentId":{"__rl":true,"mode":"list","value":"1JZnhAhr8x2UzzTQbT5l9PXguKkSM1NlznM8LX66-2Nc","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1JZnhAhr8x2UzzTQbT5l9PXguKkSM1NlznM8LX66-2Nc/edit?usp=drivesdk","cachedResultName":"meeting"}},"typeVersion":4.5},{"id":"cf384106-5413-4a92-9bdb-cce26b2452d4","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[1560,0],"parameters":{"color":7,"width":500,"height":300,"content":"## Download the file \nThese two nodes are responsible for looking and downloading the uploaded file"},"typeVersion":1},{"id":"a060bdea-3526-41c7-b16e-7a98bb843c98","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[2120,0],"parameters":{"color":7,"width":560,"height":300,"content":"## Generate Summary \nThese two nodes are responsible for looking and downloading the uploaded file"},"typeVersion":1},{"id":"f65f26e5-03f5-4c49-bb41-69c3dd4ac6a8","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[2740,0],"parameters":{"color":7,"width":480,"height":300,"content":"## Get date\nThese two nodes are responsible for getting and formatting date"},"typeVersion":1},{"id":"71991313-d9c3-406f-a4d8-177a5d853dd8","name":"Sticky Note9","type":"n8n-nodes-base.stickyNote","position":[0,0],"parameters":{"color":4,"width":1300,"height":320,"content":"=======================================\n            WORKFLOW ASSISTANCE\n=======================================\nFor any questions or support, please contact:\n    Yaron@nofluff.online\n\nExplore more tips and tutorials here:\n   - YouTube: https://www.youtube.com/@YaronBeen/videos\n   - LinkedIn: https://www.linkedin.com/in/yaronbeen/\n=======================================\n"},"typeVersion":1},{"id":"54716f9a-097b-4e6e-82a0-5fcf9ff8e27b","name":"Sticky Note3","type":"n8n-nodes-base.stickyNote","position":[0,340],"parameters":{"color":4,"width":1289,"height":2098,"content":"### 🎤 Meeting Audio to Summary in Google Sheets\n\nAutomatically transcribe a meeting audio file, generate a concise summary using AI, and log it in Google Sheets. Perfect for:\n✅ Team syncs — stay aligned without rewatching recordings\n✅ Client calls — quick insight into discussions\n✅ Knowledge management — searchable summaries\n\n---\n\n### ⚙️ What's Used\n\n**n8n Nodes:**\nDrive Upload → Download File → Transcribe Recording → Create Summary → Get Date → Format Date → Append to Google Sheets\n\n**External Tools:**\n\n* **Google Drive** – Upload and host meeting recordings\n* **OpenAI / Whisper** – Audio transcription\n* **ChatGPT** – Summary generation\n* **Google Sheets** – Final summary storage\n\n---\n\n### 🔑 Setup – Credentials Needed\n\n* **Google Drive OAuth2** → To access and download files\n* **OpenAI API Key** → For transcription & summary\n* **Google Sheets OAuth2** → To append rows to the sheet\n\n---\n\n### 📝 Upload Flow\n\n**Trigger:** Upload audio file to a designated Google Drive folder\n\n**Input Format:**\n\n* **Audio Type:** MP3 / WAV / M4A\n* **File Size:** Recommended < 100MB\n* **Language:** English (default; can customize for others)\n\n---\n\n### 🚀 Workflow Steps\n\n1. **Detect File Upload:**\n   Monitor a specific Google Drive folder for new audio files\n2. **Download File:**\n   Fetch the uploaded audio file\n3. **Transcribe Audio:**\n   Use Whisper (OpenAI) to convert speech to text\n4. **Generate Summary:**\n   Pass transcript to GPT to summarize key points\n5. **Get & Format Date:**\n   Add timestamp to summary\n6. **Save Summary:**\n   Append date + summary into a Google Sheet\n\n**Sheet Example Columns:**\n`Date`, `Meeting Summary`\n\n---\n\n### 🧠 Use Cases\n\n* **Project Managers** → Share concise updates with stakeholders\n* **Sales Teams** → Summarize discovery or demo calls\n* **Consultants** → Keep track of discussions for reporting\n\n---\n\n### 💡 Pro Tips\n\n* Add speaker labels to transcript if using enhanced audio models\n* Customize the prompt to tailor summaries for specific departments (e.g., sales, product)\n* Schedule the workflow to run daily/weekly with new uploads\n\n---\n\n### 🛠️ Customize It\n\n* Use a form trigger if you want users to submit metadata with uploads\n* Add Slack integration to share summaries with the team\n* Store full transcripts alongside summaries for deeper context\n\n---\n\nThis setup gives your team an always-on assistant for meetings — listen once, never retype. Upload audio, get insight, move forward.\n"},"typeVersion":1}],"pinData":{},"connections":{"Get date":{"main":[[{"node":"Format date","type":"main","index":0}]]},"Format date":{"main":[[{"node":"Save the summary","type":"main","index":0}]]},"Download file":{"main":[[{"node":"Transcribe the file","type":"main","index":0}]]},"Create summary":{"main":[[{"node":"Get date","type":"main","index":0}]]},"Transcribe the file":{"main":[[{"node":"Create summary","type":"main","index":0}]]},"Looking for uploading file":{"main":[[{"node":"Download file","type":"main","index":0}]]}}}


name: Automate Blog Content Creation with OpenAI, Google Sheets & Email Approval Flow
author_name: Billy Christi
author_username: billy
categories: []
created_at: 2025-05-25T05:40:26.527Z
updated_at: 2025-05-25T05:40:26.527Z
url: https://n8n.io/workflows/4371
scraped_at: 2025-06-19 22:48:46
description:
  Who is this for?
  This workflow is perfect for:
  Digital marketers who need to scale SEO-optimized content production
  Bloggers and content creators who want to maintain consistent publishing schedules
  Small business owners who need regular blog content but lack writing resources

  What problem is this workflow solving?
  Creating high-quality, SEO-optimized blog content consistently is time-consuming and resource-intensive. This workflow solves that by:
  Automating the content generation process from topic to final draft
  Ensuring quality control through human-in-the-loop approval
  Managing topic queues and preventing duplicate content creation
  Streamlining the revision process based on human feedback
  Organizing and archiving all generated content for future reference

  What this workflow does
  From topics stored in Google Sheets, this workflow:
  Automatically retrieves pending topics from your Google Sheets tracking document
  Generates SEO-optimized blog posts (800-1200 words) using OpenAI GPT-4 with structured prompts
  Sends content for human approval via email with custom approval forms
  Handles revision requests by incorporating feedback while maintaining SEO best practices
  Updates topic status to prevent duplicate processing
  Add approved generated content in Google Sheets for easy access and management
  Routes workflow based on approval decisions (approve, revise, or cancel)

  Setup
  Copy the Google Sheet template here:
  👉 Automate Blog Content Creation – Google Sheet Template
  Connect Google Sheets with your topic tracking document (requires "Topic List" and "Generated Content" sheets)
  Add your OpenAI API key to the AI agent nodes for content generation
  Configure Gmail for the approval notification system
  Set up your topic list in Google Sheets with "Topic" and "Status" columns
  Customize the schedule trigger to run at your preferred intervals
  Update email recipient in the approval node to your email address
  Test with a sample topic marked as "Pending" in your Google Sheet

  How to customize this workflow to your needs
  Adjust content length**: modify the word count requirements in the AI agent prompts
  Change writing style**: customize the copywriter prompts for different tones (formal, casual, technical)
  Add multiple reviewers**: extend the approval system to include additional stakeholders
  Integrate with CMS**: add nodes to automatically publish approved content to WordPress, Webflow, or other platforms
  Include keyword research**: add Ahrefs or SEMrush nodes to incorporate keyword data
  Add image generation**: integrate DALL-E or Midjourney for automatic featured image creation
  Customize approval criteria**: modify the approval form to include specific feedback categories
  Add content scoring**: integrate readability checkers or SEO analysis tools before approval

nodes_used:
  ["n8n-nodes-base.googleSheets","n8n-nodes-base.gmail","@n8n/n8n-nodes-langchain.agent","@n8n/n8n-nodes-langchain.lmChatOpenAi","@n8n/n8n-nodes-langchain.memoryBufferWindow","@n8n/n8n-nodes-langchain.outputParserStructured"]

workflow_json:
  {"meta":{"instanceId":"d1786ab0d745a7498abf13a9c2cdabb1374c006e889b79eef64ce0386b8f8a41"},"nodes":[{"id":"4db95c1a-1825-4eba-ba3c-c8b01eb5cdd4","name":"Schedule Trigger","type":"n8n-nodes-base.scheduleTrigger","position":[-1600,320],"parameters":{"rule":{"interval":[{}]}},"typeVersion":1.2},{"id":"73d65915-e90f-4f03-acd5-d65505d02a2f","name":"Copywriter AI Agent","type":"@n8n/n8n-nodes-langchain.agent","position":[-940,240],"parameters":{"text":"=You are an expert-level SEO content strategist and copywriter with years of experience writing high-performing blog posts.\n\nYour task is to:\n\n1. Improve the provided topic title by generating a better, SEO-optimized blog post title that is more attractive and ranks well on search engines.\n\n2. Write a complete blog post based on the improved title. The post must:\n- Be between 800–1200 words\n- Use a clear, conversational, and engaging tone\n- Be SEO-friendly with natural keyword integration\n- Start with a hooking introduction that introduces the topic smoothly\n- Use headings and subheadings (H1 for the title, H2 for main sections, H3 for supporting points)\n- Use bullet points or numbered lists where helpful\n- Have a strong conclusion that summarizes the key points and includes a call-to-action or final insight\n- Ensure smooth flow and concise, informative paragraphs\n\n3. Output the result as a JSON object with this format:\n\n```json\n{\n  \"title\": \"Improved SEO-Optimized Title\",\n  \"content\": \"Full blog post content in markdown format\"\n}\n```\n\nHere is the topic you should improve and write about:\n{{ $json.Topic }}\n\nGenerate the improved title and the full blog post now.\n","options":{},"promptType":"define","hasOutputParser":true},"typeVersion":1.9},{"id":"8db55e14-f4b2-4ca0-b10e-a3a0d375b82d","name":"OpenAI Chat Model","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[-960,540],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o-mini"},"options":{}},"credentials":{"openAiApi":{"id":"MGwGMKEkdcjzlYCw","name":"OpenAi account"}},"typeVersion":1.2},{"id":"cd8a06ce-6643-4425-8a43-4becc78252e8","name":"Simple Memory","type":"@n8n/n8n-nodes-langchain.memoryBufferWindow","position":[-760,540],"parameters":{"sessionKey":"={{ $('Get Topic from Google Sheets').item.json.Topic }}","sessionIdType":"customKey","contextWindowLength":10},"typeVersion":1.3},{"id":"57985fcc-2be7-4c39-b342-ada88576712d","name":"Copywriter Revision Agent","type":"@n8n/n8n-nodes-langchain.agent","position":[-440,700],"parameters":{"text":"=You are an expert-level copywriter with strong SEO knowledge and a clear, engaging writing style. Your task is to revise an existing blog post based on the given topic and user feedback.\n\nHere are your responsibilities:\n- Carefully apply all of the user's feedback to improve the blog post.\n- Preserve the good parts of the original content, but rewrite or adjust areas based on the feedback.\n- Keep the tone friendly, professional, and easy to read.\n- Organize the blog post with clear headings and subheadings.\n- Use bullet points or numbered lists when it makes the content clearer.\n- Ensure a strong hook in the introduction and a solid conclusion with a call-to-action or takeaway.\n- Aim for a length between 800–1200 words unless the feedback suggests otherwise.\n\nHere is the topic title:\n{{ $('Get Topic from Google Sheets').item.json.Topic }}\n\nHere is the user's feedback:\n{{ $('Send Content for Approval').item.json.data['Content Feedback'] }}\n\nHere is the original content:\n{{ $('Copywriter AI Agent').item.json.output }}\n\nNow, rewrite the blog post using this input, fully incorporating the feedback.\n","options":{},"promptType":"define","hasOutputParser":true},"typeVersion":1.9},{"id":"16da1e46-0ccc-485b-94ef-b6742c78cfe7","name":"Set Data","type":"n8n-nodes-base.set","position":[-500,240],"parameters":{"options":{},"assignments":{"assignments":[{"id":"c4dbce1a-8b34-46b7-a740-b49339233e68","name":"Topic Title","type":"string","value":"={{ $json.output.title }}"},{"id":"4924b496-db60-4618-bab7-a9d5e689c8eb","name":"Content","type":"string","value":"={{ $json.output.content }}"}]}},"typeVersion":3.4},{"id":"c03ca6ef-ffa9-4226-b753-a7b065820985","name":"Structured Output Parser","type":"@n8n/n8n-nodes-langchain.outputParserStructured","position":[-660,720],"parameters":{"jsonSchemaExample":"{\n  \"title\": \"Improved SEO-Optimized Title\",\n  \"content\": \"Full blog post content in markdown format\"\n}"},"typeVersion":1.2},{"id":"03d23d6a-48f2-4af3-9a54-e2f51e280601","name":"Add Generated Content to Google Sheets","type":"n8n-nodes-base.googleSheets","position":[440,240],"parameters":{"columns":{"value":{"Title":"={{ $('Set Data').item.json['Topic Title'] }}","Content":"={{ $('Set Data').item.json.Content }}","Generation Date":"={{ $now }}"},"schema":[{"id":"Title","type":"string","display":true,"required":false,"displayName":"Title","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Content","type":"string","display":true,"required":false,"displayName":"Content","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Generation Date","type":"string","display":true,"removed":false,"required":false,"displayName":"Generation Date","defaultMatch":false,"canBeUsedToMatch":true}],"mappingMode":"defineBelow","matchingColumns":[],"attemptToConvertTypes":false,"convertFieldsToString":false},"options":{},"operation":"append","sheetName":{"__rl":true,"mode":"list","value":1579104486,"cachedResultUrl":"https://docs.google.com/spreadsheets/d/1CyELzPxCDHAXJVu-p2_QRiGRGYwjPtJpeGwWXvlWjLw/edit#gid=1579104486","cachedResultName":"Generated Content"},"documentId":{"__rl":true,"mode":"list","value":"1CyELzPxCDHAXJVu-p2_QRiGRGYwjPtJpeGwWXvlWjLw","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1CyELzPxCDHAXJVu-p2_QRiGRGYwjPtJpeGwWXvlWjLw/edit?usp=drivesdk","cachedResultName":"Content Topics"}},"credentials":{"googleSheetsOAuth2Api":{"id":"ypmzFxQFfAacuVVC","name":"Google Sheets account"}},"typeVersion":4.5},{"id":"89c0055e-4678-40bf-b291-62fb269d9250","name":"Update Topic Status on Google Sheets","type":"n8n-nodes-base.googleSheets","position":[100,240],"parameters":{"columns":{"value":{"Status":"Completed","row_number":"={{ $('Get Topic from Google Sheets').item.json.row_number }}"},"schema":[{"id":"Topic","type":"string","display":true,"removed":true,"required":false,"displayName":"Topic","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Status","type":"string","display":true,"required":false,"displayName":"Status","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Output","type":"string","display":true,"removed":true,"required":false,"displayName":"Output","defaultMatch":false,"canBeUsedToMatch":true},{"id":"row_number","type":"string","display":true,"removed":false,"readOnly":true,"required":false,"displayName":"row_number","defaultMatch":false,"canBeUsedToMatch":true}],"mappingMode":"defineBelow","matchingColumns":["row_number"],"attemptToConvertTypes":false,"convertFieldsToString":false},"options":{},"operation":"update","sheetName":{"__rl":true,"mode":"list","value":"gid=0","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1CyELzPxCDHAXJVu-p2_QRiGRGYwjPtJpeGwWXvlWjLw/edit#gid=0","cachedResultName":"Topic List"},"documentId":{"__rl":true,"mode":"list","value":"1CyELzPxCDHAXJVu-p2_QRiGRGYwjPtJpeGwWXvlWjLw","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1CyELzPxCDHAXJVu-p2_QRiGRGYwjPtJpeGwWXvlWjLw/edit?usp=drivesdk","cachedResultName":"Content Topics"}},"credentials":{"googleSheetsOAuth2Api":{"id":"ypmzFxQFfAacuVVC","name":"Google Sheets account"}},"typeVersion":4.5},{"id":"2b7802e1-3ebf-4083-b2eb-76c519629371","name":"Get Topic from Google Sheets","type":"n8n-nodes-base.googleSheets","position":[-1260,320],"parameters":{"options":{"returnFirstMatch":true},"filtersUI":{"values":[{"lookupValue":"Pending","lookupColumn":"Status"}]},"sheetName":{"__rl":true,"mode":"list","value":"gid=0","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1CyELzPxCDHAXJVu-p2_QRiGRGYwjPtJpeGwWXvlWjLw/edit#gid=0","cachedResultName":"Topic List"},"documentId":{"__rl":true,"mode":"list","value":"1CyELzPxCDHAXJVu-p2_QRiGRGYwjPtJpeGwWXvlWjLw","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1CyELzPxCDHAXJVu-p2_QRiGRGYwjPtJpeGwWXvlWjLw/edit?usp=drivesdk","cachedResultName":"Content Topics"}},"credentials":{"googleSheetsOAuth2Api":{"id":"ypmzFxQFfAacuVVC","name":"Google Sheets account"}},"typeVersion":4.5},{"id":"4496b333-3e63-4aaa-962a-cb6c3db04508","name":"Send Content for Approval","type":"n8n-nodes-base.gmail","position":[-340,240],"webhookId":"a23938a4-fc6c-4445-8dee-17e501e92e06","parameters":{"sendTo":"replace_with_your_email@yopmail.com","message":"=Generated Title:\n{{ $json['Topic Title'] }}\n\nGenerated Content:\n{{ $json.Content }}","options":{},"subject":"Approval Required for Blog Content","operation":"sendAndWait","formFields":{"values":[{"fieldType":"dropdown","fieldLabel":"Approve Content?","fieldOptions":{"values":[{"option":"Yes"},{"option":"No"},{"option":"Cancel"}]},"requiredField":true},{"fieldType":"textarea","fieldLabel":"Content Feedback"}]},"responseType":"customForm"},"credentials":{"gmailOAuth2":{"id":"sWl7FFMkEUYBj0zM","name":"Gmail account"}},"typeVersion":2.1},{"id":"83c5c065-6c7d-41c1-bae8-ce3b65f82b5b","name":"Approval Result","type":"n8n-nodes-base.switch","position":[-200,240],"parameters":{"rules":{"values":[{"outputKey":"Yes","conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"317039f4-754e-4cb0-a674-eb8d26c9ed27","operator":{"type":"string","operation":"equals"},"leftValue":"={{ $json.data['Approve Content?'] }}","rightValue":"Yes"}]},"renameOutput":true},{"outputKey":"No","conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"caace3ea-4ca0-40de-84fb-5a8fd809a0eb","operator":{"name":"filter.operator.equals","type":"string","operation":"equals"},"leftValue":"={{ $json.data['Approve Content?'] }}","rightValue":"No"}]},"renameOutput":true},{"outputKey":"Cancel","conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"f93e5649-6a21-49a9-9993-85f1323139b0","operator":{"name":"filter.operator.equals","type":"string","operation":"equals"},"leftValue":"={{ $json.data['Approve Content?'] }}","rightValue":"Cancel"}]},"renameOutput":true}]},"options":{}},"typeVersion":3.2},{"id":"557c483c-2f2f-46e8-8e43-a489efb48035","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[-1700,140],"parameters":{"color":4,"width":320,"height":360,"content":"🕒 WORKFLOW STARTER\nThis triggers the content generation process automatically.\n\nSetup Required:\n• Set your preferred trigger interval."},"typeVersion":1},{"id":"5a1130d9-c75a-4b8e-882d-e85b2c09a882","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[-1360,20],"parameters":{"color":4,"width":320,"height":480,"content":"📊 TOPIC RETRIEVAL\nFetches the first \"Pending\" topic from your topic list.\n\nSetup Required:\n• Connect your Google account\n• Update Sheet ID in node settings\n• Ensure \"Topic List\" sheet exists with columns:\n  - Topic (A), Status (B)\n\nOutput: Topic title + row number for tracking"},"typeVersion":1},{"id":"01aee1f1-9774-4c51-9f6d-5f120d141c9a","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[-1980,20],"parameters":{"color":4,"width":260,"height":480,"content":"## SETUP REQUIRED\n**Author:** [Billy Christi](https://n8n.io/creators/billy/)\n\n**Copy the Google Sheet template here**:\n👉 [Automate Blog Content Creation – Google Sheet Template](https://docs.google.com/spreadsheets/d/1ZZ2RoMYS1DZEhM7hEDUbSCAUlcZrZ15pnGRHuus3fVk/edit?usp=sharing)\n\nGoogle Sheets Structure:\nSheet 1: \"Topic List\"\n• Column A: Topic\n• Column B: Status (\"Pending\", \"Completed\")\n\nSheet 2: \"Generated Content\"\n• Column A: Title\n• Column B: Content\n• Column C: Generation Date\n\nRequired Credentials:\n• OpenAI API Key\n• Google Sheets Credential\n• Gmail Credential"},"typeVersion":1},{"id":"b1637cc0-d30e-4bb0-b772-2d5e2293ab92","name":"Sticky Note3","type":"n8n-nodes-base.stickyNote","position":[-1020,20],"parameters":{"color":4,"width":460,"height":800,"content":"🤖 CONTENT CREATION\nAI writes SEO-optimized blog posts (800-1200 words).\n\nSetup Required:\n• Add OpenAI API key in credentials\n• Uses structured prompts for consistency\n\nOutput: JSON with title + content ready for review"},"typeVersion":1},{"id":"ed3f4587-5f55-46b3-8fbb-43e003802044","name":"Sticky Note4","type":"n8n-nodes-base.stickyNote","position":[-520,20],"parameters":{"color":4,"width":440,"height":440,"content":"📧 HUMAN REVIEW\nThis step sends the generated content via email for approval.\n\n✅ Update the To Email Field in the Gmail node with your own email address.\n\n⚠️ Note: The workflow will pause here until a response is received."},"typeVersion":1},{"id":"70d17879-afa2-4751-9c67-41864723975b","name":"Sticky Note5","type":"n8n-nodes-base.stickyNote","position":[-520,480],"parameters":{"color":4,"width":440,"height":420,"content":"✏️ CONTENT REVISION\nAI improves content based on human feedback.\n\nTriggered when: Approval = \"No\"\nUses: Original topic + feedback + original content\nSame AI model as initial generation\n\nOutput: Revised content incorporating feedback"},"typeVersion":1},{"id":"a26b8d13-8fdb-4eb5-bd3c-844ccfa9f51d","name":"Sticky Note6","type":"n8n-nodes-base.stickyNote","position":[0,0],"parameters":{"color":4,"width":300,"height":480,"content":"✅ TOPIC STATUS UPDATE\nUpdates topic status to \"Completed\" in tracking sheet.\n\nPurpose:\n• Prevents duplicate processing\n• Tracks workflow progress\n• Uses row number from initial fetch\n\nColumn Updated: Status (B) → \"Completed\"\n"},"typeVersion":1},{"id":"fe915bd9-ab50-43ce-80e0-e67ffd8842fc","name":"Sticky Note7","type":"n8n-nodes-base.stickyNote","position":[340,0],"parameters":{"color":4,"width":300,"height":480,"content":"💾 ADD GENERATED CONTENT\nSaves approved content to \"Generated Content\" sheet.\n\nSetup Required:\n• Ensure \"Generated Content\" sheet exists\n• Columns: Title (A), Content (B), Date (C)\n\nPurpose: Permanent storage for published content\n"},"typeVersion":1},{"id":"bd465766-181f-4df9-a424-c79791759c1f","name":"Sticky Note8","type":"n8n-nodes-base.stickyNote","position":[-1980,520],"parameters":{"color":5,"width":420,"height":420,"content":"## 🚀 Automate Blog Content Creation with OpenAI, Google Sheets & Email Approval Workflow\n\nWhat This Template Does:\n- Automatically generates SEO-optimized blog posts\n- Uses AI (GPT-4) to write 800-1200 word articles\n- Includes human approval process for quality control\n- Manages topics via Google Sheets\n- Handles revisions based on feedback\n\nPerfect For:\n- Content marketers scaling blog production\n- Agencies managing multiple clients\n- Bloggers wanting consistent publishing\n- SEO professionals creating optimized content"},"typeVersion":1},{"id":"29bae5b4-f6e4-4fb5-a2aa-f8ae4c4ad165","name":"Sticky Note9","type":"n8n-nodes-base.stickyNote","position":[-1540,520],"parameters":{"color":5,"width":500,"height":420,"content":"## 📋 WORKFLOW PROCESS OVERVIEW\n\nStep 1: 📅 Schedule automatically starts process\nStep 2: 📊 Fetch pending topic from Google Sheets\nStep 3: 🤖 AI generates complete blog post\nStep 4: 📧 Send content to you for approval\nStep 5: ✅ You approve, request changes, or cancel\nStep 6: ✏️ AI revises content if changes requested\nStep 7: 💾 Save final content & mark topic complete\n"},"typeVersion":1}],"pinData":{},"connections":{"Set Data":{"main":[[{"node":"Send Content for Approval","type":"main","index":0}]]},"Simple Memory":{"ai_memory":[[{"node":"Copywriter AI Agent","type":"ai_memory","index":0},{"node":"Copywriter Revision Agent","type":"ai_memory","index":0}]]},"Approval Result":{"main":[[{"node":"Update Topic Status on Google Sheets","type":"main","index":0}],[{"node":"Copywriter Revision Agent","type":"main","index":0}],[{"node":"Update Topic Status on Google Sheets","type":"main","index":0}]]},"Schedule Trigger":{"main":[[{"node":"Get Topic from Google Sheets","type":"main","index":0}]]},"OpenAI Chat Model":{"ai_languageModel":[[{"node":"Copywriter AI Agent","type":"ai_languageModel","index":0},{"node":"Copywriter Revision Agent","type":"ai_languageModel","index":0}]]},"Copywriter AI Agent":{"main":[[{"node":"Set Data","type":"main","index":0}]]},"Structured Output Parser":{"ai_outputParser":[[{"node":"Copywriter AI Agent","type":"ai_outputParser","index":0},{"node":"Copywriter Revision Agent","type":"ai_outputParser","index":0}]]},"Copywriter Revision Agent":{"main":[[{"node":"Set Data","type":"main","index":0}]]},"Send Content for Approval":{"main":[[{"node":"Approval Result","type":"main","index":0}]]},"Get Topic from Google Sheets":{"main":[[{"node":"Copywriter AI Agent","type":"main","index":0}]]},"Update Topic Status on Google Sheets":{"main":[[{"node":"Add Generated Content to Google Sheets","type":"main","index":0}]]}}}


name: Automate Reddit Trend Analysis with GPT-4 and Slack/Gmail Distribution
author_name: Yaron Been
author_username: yaron-nofluff
categories: []
created_at: 2025-05-25T05:45:03.463Z
updated_at: 2025-05-25T05:45:03.463Z
url: https://n8n.io/workflows/4373
scraped_at: 2025-06-19 22:50:05
description:
  🤖 AI Reddit Scout Agent: Auto Post Analysis & Insights
  Stay ahead of trends and conversations with this intelligent n8n workflow that automatically monitors Reddit, analyzes discussions using AI, and delivers actionable insights to your team via Slack and Gmail. Perfect for market research, content inspiration, and competitive intelligence.
  🔄 How It Works
  This automated 4-step intelligence gathering system runs daily to keep you informed:
  Step 1: Scheduled Monitoring
  The workflow automatically triggers daily (default: 9 AM) to scan Reddit for fresh discussions and trending topics.
  Step 2: Smart Content Retrieval
  The Reddit API integration searches specified subreddits using customizable filters:

  Target subreddits (e.g., r/ChatGPT, r/technology, r/startups)
  Keyword matching for specific topics
  Post ranking criteria (hot, top, new)
  Engagement thresholds (upvotes, comments)

  Step 3: AI-Powered Analysis
  Each retrieved post is processed by GPT-4 through a specialized agent that:

  Extracts key discussion points and themes
  Classifies topics in 3-5 word categories
  Generates concise one-sentence summaries
  Identifies sentiment and engagement patterns
  Highlights actionable insights and trends

  Step 4: Multi-Channel Distribution
  Analyzed insights are automatically delivered to:

  Slack channels for immediate team visibility
  Gmail inboxes for stakeholders and decision-makers
  Formatted with links back to original Reddit discussions

  ⚙️ Setup Steps
  Prerequisites

  Reddit account (for API access)
  OpenAI API key with GPT-4 access
  Slack workspace with posting permissions
  Gmail account for email distribution
  n8n instance (cloud or self-hosted)

  Configuration Steps
  Credential Setup

  Reddit API: Configure Reddit node with API credentials
  OpenAI API Key: Required for AI analysis and summarization
  Slack OAuth2: Connect workspace for channel posting
  Gmail OAuth2: Enable email distribution functionality

  Reddit Configuration

  Subreddit Selection: Define target communities to monitor

  Professional: r/entrepreneur, r/marketing, r/sales
  Technology: r/artificial, r/MachineLearning, r/programming
  Industry-specific: r/fintech, r/biotech, r/startups


  Search Parameters: Set keywords and filters

  Keywords: "AI trends", "market analysis", "customer feedback"
  Time ranges: past day, week, or month
  Minimum engagement thresholds



  AI Analysis Customization
  Default analysis prompt can be tailored for:

  Market Research Focus: Extract business insights and opportunities
  Competitive Intelligence: Identify competitor mentions and sentiment
  Content Ideas: Find trending topics for content creation
  Customer Research: Analyze user pain points and feedback

  Distribution Setup

  Slack Integration: Choose channels for different content types

  #market-intelligence for business insights
  #content-ideas for creative inspiration
  #competitive-intel for competitor discussions


  Email Configuration: Set recipient lists and formatting preferences

  Schedule Optimization

  Frequency: Daily, weekly, or custom intervals
  Timing: Optimize for team availability and time zones
  Volume Control: Limit posts per execution to avoid overwhelm

  🚀 Use Cases
  Market Research & Intelligence

  Trend Identification: Spot emerging technologies and methodologies
  Customer Sentiment: Monitor brand mentions and user feedback
  Competitive Analysis: Track competitor discussions and reputation
  Industry Insights: Stay updated on regulatory changes and news

  Content Marketing

  Topic Discovery: Find trending subjects for blog posts and videos
  Audience Research: Understand community questions and pain points
  Content Validation: Test ideas before creating full content pieces
  Engagement Strategies: Learn what resonates with target audiences

  Product Development

  Feature Requests: Identify commonly requested functionality
  User Experience Feedback: Discover usability issues and improvements
  Market Validation: Gauge interest in new product concepts
  Beta Testing Insights: Monitor feedback on product releases

  Sales & Business Development

  Lead Generation: Find potential customers discussing relevant problems
  Objection Handling: Understand common concerns and hesitations
  Partnership Opportunities: Identify potential collaboration prospects
  Market Education: Understand knowledge gaps in your target market

  Investment & Strategy

  Startup Monitoring: Track emerging companies and funding news
  Technology Assessment: Evaluate new tools and platforms
  Risk Assessment: Monitor potential threats and challenges
  Opportunity Identification: Spot underserved markets and niches

  🔧 Advanced Customization Options
  Multi-Subreddit Orchestration
  Configure different analysis approaches:
  Technical Communities: Focus on innovation and implementation details
  Business Communities: Extract market opportunities and strategies  
  User Communities: Emphasize pain points and solution requests
  News Communities: Highlight breaking developments and reactions
  Sentiment & Engagement Scoring
  Enhance analysis with quantitative metrics:

  Sentiment Analysis: Positive, negative, neutral classification
  Engagement Prediction: Likelihood of viral content
  Influence Scoring: Identify high-authority contributors
  Trend Momentum: Track discussion growth over time

  Content Filtering & Prioritization
  Implement smart content curation:

  Quality Thresholds: Minimum upvotes, comments, or awards
  Relevance Scoring: AI-based topic matching and ranking
  Duplicate Detection: Avoid repetitive content in summaries
  Language Processing: Handle multiple languages and slang

  Extended Integration Options
  Connect additional platforms and tools:

  CRM Integration: Push leads to Salesforce, HubSpot, or Pipedrive
  Documentation Tools: Save insights to Notion, Obsidian, or Confluence
  Analytics Platforms: Feed data to Google Analytics or Mixpanel
  Social Media: Cross-post insights to Twitter, LinkedIn, or Facebook

  📊 Output Examples
  Sample Slack Message:
  🔍 Reddit Intelligence Report - r/ChatGPT

  📊 Top Discussion: "Why I stopped using ChatGPT for coding"
  📝 Topic: AI Tool Limitations & Alternatives
  📋 Summary: Users discussing ChatGPT's declining code quality and exploring alternatives like Claude and GitHub Copilot for development work.

  📈 Engagement: 847 upvotes, 234 comments
  💭 Sentiment: Mixed (concerns about accuracy, praise for alternatives)
  🔗 View Discussion: [Reddit Link]

  Key Insights:
  Growing demand for specialized coding AI tools
  Quality consistency remains a major user concern  
  Opportunity for developer-focused AI solutions

  Generated at 9:15 AM • Next scan: Tomorrow 9:00 AM
  Gmail Report Format:
  Subject: Daily Reddit Intelligence - AI & Technology Trends

  📡 REDDIT SCOUT REPORT
  Date: March 15, 2024

  🎯 TOP INSIGHTS TODAY:

  AI Development Tools (r/programming)
     Discussion: "Best AI coding assistants in 2024"
     Insight: Developers increasingly comparing specialized tools vs general AI
     Engagement: High (500+ upvotes)

  Startup Funding (r/entrepreneur)  
     Discussion: "Raised $2M seed round - lessons learned"
     Insight: Current funding landscape and investor priorities
     Engagement: Moderate (150+ upvotes)

  Customer Feedback (r/SaaS)
     Discussion: "Why our churn rate dropped 40%"
     Insight: Onboarding and support strategy impacts
     Engagement: High (300+ upvotes)

  🔗 View all discussions: [Links included]

  Powered by AI Reddit Scout Agent
  Next report: Tomorrow at 9:00 AM
  🛠️ Troubleshooting & Best Practices
  Common Issues & Solutions
  API Rate Limiting

  Implement exponential backoff delays
  Distribute requests across multiple time periods
  Cache results to minimize redundant calls
  Monitor Reddit API status and limits

  Content Quality Control

  Set minimum engagement thresholds
  Filter out low-quality or spam posts
  Implement keyword blacklists for irrelevant content
  Regular prompt tuning for better AI analysis

  Information Overwhelm

  Limit posts per subreddit per day
  Prioritize by engagement and relevance scores
  Create digest formats for high-volume periods
  Allow team members to customize their alerts

  Optimization Strategies
  Performance Enhancement

  Use parallel processing for multiple subreddits
  Implement caching for repeated analysis
  Optimize OpenAI prompt length and complexity
  Monitor and optimize workflow execution time

  Cost Management

  Balance AI analysis depth with API costs
  Use different models for different content types
  Implement smart filtering before AI analysis
  Track ROI through engagement metrics

  Team Adoption

  Start with pilot programs in specific departments
  Provide training on interpreting AI insights
  Create feedback loops for continuous improvement
  Establish clear action protocols for different insight types

  📈 Success Metrics
  Intelligence Quality Indicators

  Relevance Score: Percentage of insights that lead to action
  Timeliness: How quickly trends are identified vs competitors
  Accuracy: Validation of AI predictions against actual outcomes
  Engagement: Team interaction with distributed insights

  Business Impact Measurements

  Content Performance: Improvement in content engagement rates
  Market Timing: Success rate of trend-based decisions
  Competitive Advantage: Early identification of opportunities/threats
  Time Savings: Reduction in manual research and monitoring time

  📞 Questions & Support
  Need assistance with your AI Reddit Scout Agent setup or customization?
  📧 Technical Support

  Email: Yaron@nofluff.online
  Response Time: Within 24 hours on business days
  Expertise: Reddit API integration, AI prompt optimization, workflow scaling

  🎥 Learning Resources

  YouTube Channel: https://www.youtube.com/@YaronBeen/videos

  Complete setup and configuration guides
  Advanced filtering and analysis techniques
  Integration tutorials for popular business tools
  Troubleshooting common issues



  🤝 Professional Networking

  LinkedIn: https://www.linkedin.com/in/yaronbeen/

  Connect for ongoing automation support
  Share your intelligence gathering success stories
  Access to exclusive workflow templates and updates



  💬 Support Request Guidelines
  Include in your message:

  Target subreddits and use cases
  Current team size and distribution needs
  Specific industries or topics of interest
  Integration requirements with existing tools
  Any error messages or unexpected behaviors

nodes_used:
  ["n8n-nodes-base.slack","n8n-nodes-base.gmail","n8n-nodes-base.reddit","@n8n/n8n-nodes-langchain.agent","@n8n/n8n-nodes-langchain.lmChatOpenAi"]

workflow_json:
  {"meta":{"instanceId":"5aaf4236c70e34e423fbdb2c7b754d19253a933bb1476d548f75848a01e473cf","templateCredsSetupCompleted":true},"nodes":[{"id":"e5b2e77c-54df-46e4-a130-b30eed7934ab","name":"Fetch Reddit Posts","type":"n8n-nodes-base.reddit","position":[2440,3580],"parameters":{"limit":5,"keyword":"why I stopped using it","operation":"search","subreddit":"Chatgpt","additionalFields":{}},"typeVersion":1},{"id":"696586e7-a66b-49a9-a3e7-d309bb441951","name":"Summarize Posts with AI","type":"@n8n/n8n-nodes-langchain.agent","position":[2780,3580],"parameters":{"text":"=Analyze the following Reddit post. Classify its main topic in 3-5 words, and write a 1-sentence summary.\n\nTitle: {{ $json[\"title\"] }}  \nContent: {{ $json.selftext }}\n","options":{},"promptType":"define"},"typeVersion":1.9},{"id":"c665d7bb-0c34-4d34-807c-4861c984277e","name":"Generate AI Insights","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[2740,3800],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o-mini"},"options":{}},"typeVersion":1.2},{"id":"57ba5821-49e1-4ede-9bb0-a7097f94a286","name":"Send Summary to Slack","type":"n8n-nodes-base.slack","position":[3340,3480],"webhookId":"e021423b-e10c-4044-96e4-46cfb82be060","parameters":{"text":"=Topic:\n{{ $('Fetch Reddit Posts').item.json.subreddit }}\n\nSummary:\n{{ $json.output }}\n\nView on Reddit:\n{{ $('Fetch Reddit Posts').item.json.media_metadata.cnn80k7excte1.p[0].u }}","select":"channel","channelId":{"__rl":true,"mode":"list","value":"C08TTV0CC3E","cachedResultName":"all-nathing"},"otherOptions":{}},"typeVersion":2.3},{"id":"b4a501fb-7f2d-4d72-ae38-c418e10b588e","name":"Send Summary to Gmail","type":"n8n-nodes-base.gmail","position":[3340,3720],"webhookId":"c118adb5-da2c-4108-ae40-a056e2d51f89","parameters":{"sendTo":"uu941401@gmail.com","message":"=Topic:\n{{ $('Fetch Reddit Posts').item.json.subreddit }}\n\nSummary:\n{{ $json.output }}\n\nView on Reddit:\n{{ $('Fetch Reddit Posts').item.json.media_metadata.cnn80k7excte1.p[0].u }}","options":{},"subject":"=New Reddit Post on  {{ $('Fetch Reddit Posts').item.json.subreddit }}"},"typeVersion":2.1},{"id":"0eb7d480-bf92-4794-af7c-320b1bee5687","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[2160,2760],"parameters":{"color":3,"width":440,"height":1000,"content":"## 🛫 Step 1: Get the Post\n\nThis is the **entry point** of the Reddit Insight workflow, responsible for fetching fresh Reddit content on a regular basis.\n\n### 🔁 **Trigger Daily Reddit Scan**\n\nThis **Schedule Trigger** node initiates the workflow automatically at a predefined time—typically once per day. It ensures that your automation always works with the most recent content from Reddit without any manual input.\n\n### 📥 **Fetch Reddit Posts**\n\nThis **Reddit node** is configured to search specific subreddits using filters like:\n\n* **Subreddit** (e.g., `technology`, `ai`)\n* **Search term** (e.g., `GPT-5`, `startup launch`)\n* **Time range** (`day`, `week`, etc.)\n* **Sort by** (`top`, `hot`, `new`)\n* **Limit** (e.g., 5 posts)\n\nIt pulls the top relevant posts based on these criteria and passes them along for AI analysis in the next step.\n\n> 🔍 This section ensures you're always working with timely, relevant Reddit discussions—perfect for trend monitoring or content summarization.\n\n---\n\nLet me know if you want to break this into a reusable subworkflow or add dynamic inputs via a UI form.\n"},"typeVersion":1},{"id":"c9b3000d-17df-4b32-b4d6-ca381b1f2aa7","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[2660,3120],"parameters":{"color":4,"width":440,"height":820,"content":"## 🧠 Step 2: Post Summarization\n\nThis section turns raw Reddit content into concise insights using AI.\n\n### 🤖 **Summarize Posts with AI**\n\nThe **AI Agent** receives posts and uses a connected chat model to analyze and summarize each one. It can extract key points, tone, and trends — making the content more actionable.\n\n### 🔗 **Generate AI Insights (OpenAI Chat Model)**\n\nThe summarization is powered by the **OpenAI Chat Model**, which processes each post using a tailored prompt.\n\n> 📌 This step helps convert Reddit noise into clear, valuable summaries for decision-making or sharing."},"typeVersion":1},{"id":"bdd58493-78ed-4dbc-ad6f-3fa136168a4e","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[3160,2980],"parameters":{"color":6,"width":440,"height":920,"content":"## 📤 Step 3: Send the Summary\n\nThis section distributes the AI-generated summary to communication channels.\n\n### 💬 **Send Summary to Slack**\n\nThe summarized content is sent to a **Slack channel** via a message post. Ideal for quick team updates directly in your workflow.\n\n### 📧 **Send Summary to Gmail**\n\nSimultaneously, the same summary is sent to a **Gmail inbox**, ensuring recipients outside Slack still get the insights.\n\n> 📌 This step ensures summaries are instantly shared with stakeholders via preferred communication tools."},"typeVersion":1},{"id":"4013e36b-6070-4120-a5cc-ae5824d3e1d9","name":"Sticky Note9","type":"n8n-nodes-base.stickyNote","position":[480,2760],"parameters":{"color":4,"width":1300,"height":320,"content":"=======================================\n            WORKFLOW ASSISTANCE\n=======================================\nFor any questions or support, please contact:\n    Yaron@nofluff.online\n\nExplore more tips and tutorials here:\n   - YouTube: https://www.youtube.com/@YaronBeen/videos\n   - LinkedIn: https://www.linkedin.com/in/yaronbeen/\n=======================================\n"},"typeVersion":1},{"id":"22cc5f85-cd65-4fb9-ab3d-70393e580d55","name":"Sticky Note3","type":"n8n-nodes-base.stickyNote","position":[480,3100],"parameters":{"color":4,"width":1289,"height":2378,"content":"Based on your example, here’s a detailed breakdown for your **Reddit to AI Summary for Slack & Gmail** workflow, using the same structure and clarity:\n\n---\n\n# 🔎 Reddit Insight Broadcaster\n\nAutomatically fetch top Reddit posts, generate insights using OpenAI, and broadcast summaries to Slack and Gmail. Perfect for:\n✅ Market Monitoring — get daily pulse on trends and user sentiment\n✅ Content Curation — surface engaging discussions for teams\n\n---\n\n## ⚙️ What's Used\n\n**n8n Nodes:**\nSchedule Trigger → Reddit → AI Agent → OpenAI Chat Model → Slack → Gmail\n\n**External Tools:**\n\n* **Reddit** – Public API via n8n's Reddit node\n* **OpenAI GPT** – For intelligent summarization or sentiment tagging\n* **Slack** – Post to selected channel\n* **Gmail** – Send summaries via email\n\n---\n\n## 🔑 Setup – Credentials Needed\n\n* **Reddit Access** – Use n8n Reddit node (API key or OAuth2 if rate-limited access is needed)\n* **OpenAI API Key** – Add in the OpenAI Chat node\n* **Slack OAuth2** – Connect your workspace\n* **Gmail OAuth2** – Connect your Google account\n\n---\n\n## 🚀 Workflow Steps\n\n1. **Trigger Every Morning**\n   Scheduler runs daily at a set time.\n\n2. **Search Reddit Posts**\n   Uses subreddit and keyword filters.\n\n3. **Analyze Content with AI**\n   The AI Agent passes each post to OpenAI to:\n\n   * Summarize discussion\n   * Extract insights\n   * Optionally classify sentiment\n\n4. **Broadcast Insights**\n\n   * Post to a designated Slack channel\n   * Send via Gmail to stakeholders\n\n---\n\n## 📥 Example Output (Slack/Gmail Message)\n\n```\n🔍 Top Reddit Discussion — r/technology\n\n**Title:** OpenAI releases new GPT model  \n**Summary:** Users are discussing the implications of GPT-5's capabilities. General sentiment is excitement mixed with concern over ethical use.  \n**Upvotes:** 1,200 | 💬 Comments: 350  \n🔗 [Read Post](https://reddit.com/r/technology/example)\n```\n\n---\n\n## 💡 Pro Tips\n\n* Change subreddit dynamically using variables or UI form\n* Use OpenAI to classify tone (positive/neutral/negative)\n* Add branching: e.g., only email posts with >500 upvotes\n* Extend to Notion or Google Sheets for archiving\n* Use emojis or markdown in Slack messages for better UX\n\n---\n\n## 🛠️ Customize It\n\n* **Add filters:** Only include posts with >X upvotes\n* **Score content:** Prioritize based on engagement + AI relevance\n* **Route by topic:** Post AI topics to `#ai`, startup topics to `#founders`\n* **Trigger on-demand:** Add webhook or form to control when it runs\n\n---\n\nThis workflow is a lightweight yet powerful Reddit monitoring tool—perfect for keeping your team updated, generating newsletter content, or tracking niche trends.\n📡 One bot. One summary. Fully automated."},"typeVersion":1},{"id":"3b1c680a-0c74-4a83-bf3f-163e9b5114e6","name":"Trigger Daily Reddit Scan","type":"n8n-nodes-base.scheduleTrigger","position":[2220,3580],"parameters":{"rule":{"interval":[{"triggerAtHour":9}]}},"typeVersion":1.2}],"pinData":{},"connections":{"Fetch Reddit Posts":{"main":[[{"node":"Summarize Posts with AI","type":"main","index":0}]]},"Generate AI Insights":{"ai_languageModel":[[{"node":"Summarize Posts with AI","type":"ai_languageModel","index":0}]]},"Summarize Posts with AI":{"main":[[{"node":"Send Summary to Slack","type":"main","index":0},{"node":"Send Summary to Gmail","type":"main","index":0}]]},"Trigger Daily Reddit Scan":{"main":[[{"node":"Fetch Reddit Posts","type":"main","index":0}]]}}}


name: Automatic News Summarization & Email Digest with GPT-4, NewsAPI and Gmail
author_name: Yaron Been
author_username: yaron-nofluff
categories: []
created_at: 2025-05-25T05:58:27.949Z
updated_at: 2025-05-25T05:58:27.949Z
url: https://n8n.io/workflows/4375
scraped_at: 2025-06-19 22:50:12
description:
  📰 AI News Digest Agent: Auto News Summarizer & Email Newsletter
  Create an intelligent news curation system that automatically fetches breaking headlines, generates AI-powered summaries, and delivers personalized news digests to your subscriber list. Perfect for newsletter creators, team leaders, and content curators who want to keep their audience informed without the manual effort of news monitoring and summarization.
  🔄 How It Works
  This streamlined 5-step automation delivers fresh news insights around the clock:
  Step 1: Automated News Collection
  The workflow runs on a configurable schedule (default: every 10 minutes) to fetch the latest headlines from NewsAPI, ensuring your content stays current with breaking developments.
  Step 2: Intelligent Content Curation
  The system pulls top headlines from reliable news sources, filtering by country, category, and relevance to deliver the most important stories of the day.
  Step 3: AI-Powered Summarization
  GPT-4 processes the collected headlines and creates:

  Concise 5-bullet point summaries
  Key insights and implications
  Easy-to-digest news overviews
  Professional formatting for email distribution

  Step 4: Subscriber Management
  The workflow accesses your Google Sheets subscriber list, retrieving names and email addresses for personalized delivery.
  Step 5: Automated Email Distribution
  Personalized news digests are automatically sent to each subscriber via Gmail, with custom greetings and professionally formatted content.
  ⚙️ Setup Steps
  Prerequisites

  NewsAPI account (free tier available)
  OpenAI API access for content summarization
  Google Sheets for subscriber management
  Gmail account for email distribution
  n8n instance (cloud or self-hosted)

  Required Google Sheets Structure
  Create a simple subscriber database:
  | Name          | Email                    |
  |---------------|--------------------------|
  | John Smith    | john@example.com         |
  | Sarah Johnson | sarah@company.com        |
  | Mike Chen     | mike.chen@startup.co     |
  Configuration Steps
  Credential Setup

  NewsAPI Key: Sign up at newsapi.org for free headline access
  OpenAI API Key: Required for AI-powered news summarization
  Google Sheets OAuth2: Access your subscriber spreadsheet
  Gmail OAuth2: Enable automated email sending

  News Source Configuration

  Country Selection: Choose target region (US, UK, CA, AU, etc.)
  Category Filters: Focus on specific topics (technology, business, health)
  Source Selection: Prefer certain news outlets or avoid others
  Language Settings: Configure for international audiences

  AI Summarization Customization
  Default prompt creates 5-bullet summaries, but can be tailored for:

  Industry Focus: Technology, finance, healthcare, politics
  Audience Type: General public, professionals, executives
  Content Depth: Brief overviews vs detailed analysis
  Tone & Style: Formal, conversational, or technical

  Email Template Personalization

  Subject Line Formatting: Include date, breaking news indicators
  Greeting Customization: Use subscriber names for personal touch
  Content Layout: Professional formatting with clear sections
  Branding Elements: Add your organization's signature or logo

  Delivery Schedule Optimization

  Frequency Settings: Every 10 minutes, hourly, or daily
  Time Zone Considerations: Optimize for subscriber locations
  Breaking News Alerts: Immediate delivery for urgent stories
  Digest Compilation: Collect multiple stories for periodic summaries

  🚀 Use Cases
  Newsletter Publishers

  Content Automation: Generate newsletter content without manual curation
  Consistent Publishing: Maintain regular delivery schedules automatically
  Audience Growth: Provide value that encourages subscriptions and shares
  Time Savings: Eliminate hours of daily news monitoring and writing

  Corporate Communications

  Employee Updates: Keep teams informed about industry developments
  Executive Briefings: Deliver curated news summaries to leadership
  Client Communications: Share relevant industry insights with customers
  Stakeholder Relations: Maintain informed investor and partner networks

  Educational Institutions

  Student Resources: Provide current events for academic discussions
  Faculty Updates: Keep educators informed about relevant developments
  Research Support: Deliver news related to specific academic fields
  Parent Communications: Share educational policy and school-related news

  Professional Services

  Client Value Addition: Provide industry-specific news as a service benefit
  Thought Leadership: Position your firm as an informed industry expert
  Business Development: Share insights that demonstrate market knowledge
  Team Knowledge Sharing: Keep entire organization current on industry trends

  Community Organizations

  Member Engagement: Keep community members informed and engaged
  Local News Focus: Customize for regional or local news coverage
  Event Planning: Stay informed about developments affecting your community
  Advocacy Support: Monitor news relevant to your organization's mission

  🔧 Advanced Customization Options
  Multi-Source News Aggregation
  Expand beyond NewsAPI with additional sources:
  RSS Feed Integration: Add specialized industry publications
  Social Media Monitoring: Include trending topics from Twitter/LinkedIn
  Government Sources: Official announcements and policy updates
  International Coverage: Global perspectives on major stories
  Intelligent Content Filtering
  Implement smart curation features:

  Sentiment Analysis: Filter positive, negative, or neutral news
  Relevance Scoring: Prioritize stories based on subscriber interests
  Duplicate Detection: Avoid sending repetitive story coverage
  Quality Assessment: Ensure content meets editorial standards

  Subscriber Segmentation
  Create targeted news experiences:

  Interest Categories: Technology, business, sports, entertainment
  Geographic Preferences: Local, national, or international focus
  Delivery Preferences: Frequency and format customization
  Engagement Tracking: Monitor opens, clicks, and subscriber behavior

  Enhanced Email Features
  Professional newsletter capabilities:

  HTML Templates: Rich formatting with images and links
  Call-to-Action Buttons: Drive engagement with your content or services
  Social Sharing: Enable easy sharing of newsletter content
  Analytics Integration: Track email performance and subscriber engagement

  📊 Content Generation Examples
  Sample Email Output:
  Subject: 📰 Your Daily News Digest - March 15, 2024

  Hi John,

  Please find today's top news headlines summarized below:

  📈 BUSINESS & TECHNOLOGY
  Federal Reserve signals potential rate cuts following inflation data
  Major tech companies announce AI partnership for healthcare applications  
  Renewable energy sector sees record investment levels in Q1 2024
  Cryptocurrency markets stabilize after regulatory clarity announcement
  Supply chain disruptions ease as global shipping routes normalize

  💡 These developments suggest growing economic optimism and continued technology sector innovation. The healthcare AI partnership particularly signals significant advances in medical technology accessibility.

  Stay informed and have a great day!

  Powered by AI News Digest Agent
  Unsubscribe | Update Preferences
  Breaking News Alert Format:
  Subject: 🚨 Breaking News Alert - Major Development

  Hi Sarah,

  BREAKING: [Headline]

  Key Details:
  [Critical point 1]
  [Critical point 2]  
  [Impact analysis]

  Full coverage in your next scheduled digest.

  AI News Digest Agent
  🛠️ Troubleshooting & Best Practices
  Common Issues & Solutions
  API Rate Limiting

  Monitor NewsAPI quota usage and upgrade plan if needed
  Implement intelligent caching to reduce redundant requests
  Stagger requests during high-traffic periods
  Set up alerts for approaching rate limits

  Email Delivery Challenges

  Monitor Gmail sending limits and implement delays if needed
  Use professional email authentication (SPF, DKIM)
  Maintain clean subscriber lists to avoid spam flags
  Implement unsubscribe functionality for compliance

  Content Quality Control

  Review AI summaries periodically for accuracy and bias
  Implement feedback loops for continuous prompt improvement
  Create editorial guidelines for consistent tone and style
  Monitor subscriber feedback and engagement metrics

  Optimization Strategies
  Performance Enhancement

  Use parallel processing for multiple news sources
  Implement intelligent caching for repeated content
  Optimize AI prompts for faster processing and better results
  Monitor workflow execution time and resource usage

  Subscriber Growth

  Create compelling value propositions for newsletter signups
  Implement referral systems for organic growth
  Share sample newsletters on social media and websites
  Collect feedback to continuously improve content quality

  Content Strategy

  A/B test different summary formats and lengths
  Analyze which news categories generate most engagement
  Experiment with sending times for optimal open rates
  Create themed newsletters for special events or topics

  📈 Success Metrics
  Engagement Indicators

  Open Rates: Percentage of subscribers reading newsletters
  Click-Through Rates: Engagement with linked news sources
  Subscriber Growth: New signups and retention rates
  Forward/Share Rates: Viral coefficient of your content

  Content Quality Measurements

  Relevance Scores: Subscriber feedback on content usefulness
  Timeliness: How quickly breaking news reaches subscribers
  Accuracy: Verification of AI-summarized content
  Completeness: Coverage of important stories in your focus areas

  📞 Questions & Support
  Need assistance with your AI News Digest Agent setup or optimization?
  📧 Technical Support

  Email: Yaron@nofluff.online
  Response Time: Within 24 hours on business days
  Specialization: NewsAPI integration, AI content optimization, email deliverability

  🎥 Educational Resources

  YouTube Channel: https://www.youtube.com/@YaronBeen/videos

  Complete setup and configuration tutorials
  Advanced customization techniques for different industries
  Email marketing best practices for automated newsletters
  Troubleshooting common integration issues
  Scaling strategies for growing subscriber lists



  🤝 Professional Community

  LinkedIn: https://www.linkedin.com/in/yaronbeen/

  Connect for ongoing newsletter automation support
  Share your news curation success stories
  Access exclusive templates and workflow variations
  Join discussions about content automation trends



  💬 Support Request Best Practices
  Include in your support message:

  Your target audience and newsletter focus
  Current subscriber count and growth goals
  Specific news categories or geographic regions of interest
  Any technical errors or integration challenges
  Current content creation workflow and pain points

nodes_used:
  ["n8n-nodes-base.googleSheets","n8n-nodes-base.httpRequest","n8n-nodes-base.gmail","@n8n/n8n-nodes-langchain.agent","@n8n/n8n-nodes-langchain.lmChatOpenAi"]

workflow_json:
  {"meta":{"instanceId":"5aaf4236c70e34e423fbdb2c7b754d19253a933bb1476d548f75848a01e473cf","templateCredsSetupCompleted":true},"nodes":[{"id":"c5091fb1-5bc5-44bc-b804-201d5ffe0672","name":"Schedule Trigger","type":"n8n-nodes-base.scheduleTrigger","position":[-2120,-40],"parameters":{"rule":{"interval":[{"field":"minutes","minutesInterval":10}]}},"typeVersion":1.2},{"id":"60424e56-7429-48c5-831c-056e9874b8a3","name":"AI Agent","type":"@n8n/n8n-nodes-langchain.agent","position":[-1560,-40],"parameters":{"text":"=You are act as news expert and collect all news headlines  in below and summarise in 5 bullets.\n\n\n {{ $json.articles[1].title }}","options":{},"promptType":"define"},"typeVersion":1.9},{"id":"2bd28b32-80f9-4a69-9b1a-0eee7ef3db42","name":"OpenAI Chat Model","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[-1560,140],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o-mini"},"options":{}},"typeVersion":1.2},{"id":"792376e9-3312-4862-94a0-e38de2e6dda5","name":"Pull News","type":"n8n-nodes-base.httpRequest","position":[-1840,-40],"parameters":{"url":"https://newsapi.org/v2/top-headlines","options":{},"sendQuery":true,"queryParameters":{"parameters":[{"name":"country","value":"us"},{"name":"apiKey","value":"NEWS_API_KEY"}]}},"typeVersion":4.2},{"id":"596c8d5d-3c03-435e-abab-e7b93de28471","name":"Send Mail","type":"n8n-nodes-base.gmail","position":[-980,-40],"webhookId":"e5c02fba-64bc-47f0-b752-2de2b8e6b03c","parameters":{"sendTo":"={{ $json.Email }}","message":"=Hi {{ $json.Name }},\nPlease find the top news headlines as below:\n\n{{ $('AI Agent').item.json.output }}","options":{},"subject":"News Headlines","emailType":"text"},"typeVersion":2.1},{"id":"125b6015-f220-4245-94eb-08d61ece41b3","name":"Email list","type":"n8n-nodes-base.googleSheets","position":[-1200,-40],"parameters":{"options":{},"sheetName":{"__rl":true,"mode":"list","value":"gid=0","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1L2dLObdw_aicD6fTd-ElHSBBJIj1aBmKT7FecMtbyyE/edit#gid=0","cachedResultName":"Sheet1"},"documentId":{"__rl":true,"mode":"list","value":"1L2dLObdw_aicD6fTd-ElHSBBJIj1aBmKT7FecMtbyyE","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1L2dLObdw_aicD6fTd-ElHSBBJIj1aBmKT7FecMtbyyE/edit?usp=drivesdk","cachedResultName":"Emails"}},"typeVersion":4.5},{"id":"b4146559-5d6c-4db3-aad5-12a73621aa90","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[-3020,-300],"parameters":{"width":740,"height":1280,"content":"📰 AI News Digest Agent: Auto News Summarizer & Emailer\nAutomatically fetch top news headlines, generate AI-powered summaries, and send personalized digests to your subscriber list. Perfect for:\n✅ Newsletter creators — deliver curated news content effortlessly\n✅ Teams & organizations — keep everyone informed with regular updates\n✅ Content curators — transform news into digestible insights\n\n⚙️ What's Used\nn8n Nodes:\nSchedule Trigger → News API → AI Agent → OpenAI Chat Model → Google Sheets → Gmail\nExternal Tools:\n\nNewsAPI – Fetch latest headlines from reliable sources\nOpenAI GPT-4 – Generate concise 5-bullet summaries\nGoogle Sheets – Manage subscriber email lists\nGmail – Send personalized news digests\n\n\n🔑 Setup – Credentials Needed\n\nNewsAPI Key → Free account at newsapi.org for headline access\nOpenAI API Key → For AI-powered news summarization\nGoogle Sheets OAuth2 → Access subscriber email lists\nGmail OAuth2 → Send automated newsletter emails\n\n\n📊 Google Sheets Structure Required\nCreate a simple subscriber spreadsheet:\n\nName (subscriber's name for personalization)\nEmail (recipient email addresses)\n\n\n🚀 Workflow Steps\n\nScheduled News Collection\nRuns every 10 minutes to fetch latest US headlines from NewsAPI\nAI-Powered Summarization\nGPT processes news headlines and creates concise 5-bullet summaries\nSubscriber List Access\nRetrieves email list from Google Sheets for distribution\nPersonalized Email Delivery\nSends customized news digests to each subscriber with their name\n\n\n💡 Pro Tips\n\nCustomize the country parameter (US, UK, CA, etc.) for regional news\nAdjust schedule frequency based on your audience preferences\nAdd category filters (technology, business, sports) for niche newsletters\nMonitor email delivery rates and subscriber engagement\nTest with small subscriber lists before scaling up\n\n\n🛠️ Customize It\n\nAdd multiple news sources for comprehensive coverage\nInclude trending topics and sentiment analysis\nConnect to Mailchimp or other email marketing platforms\nAdd unsubscribe functionality and list management\nCreate different digest formats (daily, weekly, breaking news)"},"typeVersion":1}],"pinData":{},"connections":{"AI Agent":{"main":[[{"node":"Email list","type":"main","index":0}]]},"Pull News":{"main":[[{"node":"AI Agent","type":"main","index":0}]]},"Email list":{"main":[[{"node":"Send Mail","type":"main","index":0}]]},"Schedule Trigger":{"main":[[{"node":"Pull News","type":"main","index":0}]]},"OpenAI Chat Model":{"ai_languageModel":[[{"node":"AI Agent","type":"ai_languageModel","index":0}]]}}}


name: Extract Invoice Data from Email to Google Sheets using GPT-4o AI Automation
author_name: Yaron Been
author_username: yaron-nofluff
categories: []
created_at: 2025-05-25T06:03:38.031Z
updated_at: 2025-05-25T06:03:38.031Z
url: https://n8n.io/workflows/4376
scraped_at: 2025-06-19 22:48:54
description:
  Transform your invoice processing from manual data entry into an intelligent automation system. This powerful n8n workflow monitors Gmail for invoice attachments, extracts data using AI-powered analysis, and creates organized Google Sheets with all relevant financial information automatically structured and ready for your accounting workflows.

  🔄 How It Works

  This sophisticated 8-step automation eliminates manual invoice processing:

  Step 1: Intelligent Email Monitoring
  The workflow continuously monitors your Gmail account for emails with specific labels, checking every minute for new invoice attachments that need processing.

  Step 2: Attachment Verification
  Smart filtering ensures only emails with PDF attachments are processed, preventing unnecessary workflow triggers from text-only emails.

  Step 3: Advanced PDF Extraction
  The system automatically downloads and converts PDF invoices into readable text, handling various invoice formats and layouts with high accuracy.

  Step 4: AI-Powered Data Analysis
  GPT-4 processes the extracted text using specialized prompts designed for financial document analysis, identifying and extracting:
  Company information and contact details
  Invoice numbers, dates, and payment terms
  Detailed line items with quantities and pricing
  Tax calculations including CGST, SGST, and VAT
  Billing and shipping addresses
  Payment methods and transaction references

  Step 5: Structured Data Formatting
  The AI output is automatically formatted into clean, consistent JSON structure with 25+ standardized fields for comprehensive invoice tracking.

  Step 6: Dynamic Spreadsheet Creation
  Each processed invoice generates a new Google Sheets document with timestamp naming and organized data layout, ready for accounting review.

  Step 7: Automated File Organization
  Processed spreadsheets are automatically moved to designated Google Drive folders, maintaining organized file structure for easy retrieval and audit trails.

  Step 8: Data Population
  All extracted invoice data is populated into the spreadsheet with proper formatting, formulas, and structure for immediate use in accounting workflows.

  ⚙️ Setup Steps

  Prerequisites
  Gmail account with invoice-receiving capability
  Google Workspace access for Sheets and Drive
  OpenAI API account for data extraction
  n8n instance (cloud or self-hosted)
  PDF invoices (text-based, not scanned images)

  Gmail Configuration Requirements

  Label Setup:
  Create specific Gmail labels for invoice processing:
  📧 Labels to Create:
  "Invoice-Processing" (main processing label)
  "Invoice-Vendors" (supplier invoices)
  "Invoice-Clients" (customer invoices)  
  "Invoice-Processed" (completed items)

  Email Filter Configuration:
  Set up automatic labeling rules:
  Emails from known vendors → Auto-apply "Invoice-Processing"
  Emails with "Invoice" in subject → Auto-apply "Invoice-Processing"  
  Attachments with PDF extension → Auto-apply "Invoice-Processing"

  Configuration Steps

  1. Credential Setup
  Gmail OAuth2**: Full email access including attachments
  OpenAI API Key**: GPT-4 access for intelligent data extraction
  Google Sheets OAuth2**: Spreadsheet creation and editing permissions
  Google Drive OAuth2**: File organization and folder management

  2. Google Drive Folder Structure
  Create organized folder hierarchy:
  📁 Invoice Management/
  ├── 📁 Incoming Invoices/
  ├── 📁 Processed Invoices/
  │   ├── 📁 2024/
  │   │   ├── 📁 Q1/
  │   │   ├── 📁 Q2/
  │   │   └── 📁 Q3/
  ├── 📁 Vendor Invoices/
  └── 📁 Client Invoices/

  3. AI Extraction Customization
  The default AI prompt extracts standard invoice fields but can be customized for:
  Regional Tax Systems**: GST (India), VAT (EU), Sales Tax (US)
  Industry-Specific Fields**: Purchase orders, project codes, cost centers
  Company Standards**: Custom fields, approval workflows, coding requirements
  Multi-Currency**: Exchange rates, currency conversion, international invoices

  4. Data Validation Rules
  Implement quality control measures:
  Required Field Validation**: Ensure critical data is always extracted
  Format Standardization**: Consistent date formats, number formatting
  Duplicate Detection**: Identify potentially duplicate invoices
  Accuracy Scoring**: Confidence levels for extracted data

  5. Workflow Activation
  Import the workflow JSON into your n8n instance
  Configure all credential connections and test each step
  Process test invoices to verify accuracy
  Activate Gmail trigger for continuous monitoring

  🚀 Use Cases

  Accounting Firms & Bookkeepers
  Client Service Automation**: Process invoices for multiple clients efficiently
  Data Entry Elimination**: Convert hours of manual work into automated processing
  Accuracy Improvement**: Reduce human errors in financial data transcription
  Scalable Operations**: Handle increased client volume without proportional staff increase

  Small & Medium Businesses
  Accounts Payable Automation**: Streamline vendor invoice processing
  Cash Flow Management**: Quick access to payment due dates and amounts
  Expense Tracking**: Organized categorization of business expenses
  Audit Preparation**: Maintain organized, searchable invoice records

  Corporate Finance Teams
  Procurement Processing**: Handle purchase orders and vendor invoices at scale
  Multi-Location Operations**: Centralize invoice processing across offices
  Compliance Management**: Ensure consistent data capture for regulatory requirements
  Integration Readiness**: Prepare data for ERP and accounting system import

  Freelancers & Consultants
  Client Invoice Tracking**: Organize incoming payments and project billing
  Expense Management**: Categorize business expenses for tax preparation
  Cash Flow Monitoring**: Track outstanding invoices and payment schedules
  Professional Organization**: Maintain clean financial records for business growth

  E-commerce & Retail
  Supplier Invoice Processing**: Manage inventory purchasing and cost tracking
  Multi-Vendor Operations**: Handle invoices from numerous suppliers efficiently
  Cost Analysis**: Track product costs and supplier performance
  Inventory Reconciliation**: Match invoice data with purchase orders and receipts

  🔧 Advanced Customization Options

  Multi-Format Invoice Handling
  Extend processing capabilities:
  PDF Text-Based: Standard invoice PDFs with selectable text
  Scanned Documents: Add OCR processing for image-based invoices
  Email Body Invoices: Extract data from invoice details in email content  
  Excel Attachments: Process invoices sent as spreadsheet files
  Multi-Page Documents: Handle complex invoices with multiple pages

  Intelligent Data Validation
  Implement quality assurance features:
  Cross-Reference Validation**: Compare extracted data against purchase orders
  Vendor Database Matching**: Verify company details against known vendor lists
  Tax Calculation Verification**: Validate tax amounts and rates for accuracy
  Currency Conversion**: Handle multi-currency invoices with real-time exchange rates

  Workflow Integration Extensions
  Connect to existing business systems:
  ERP Integration**: Direct data export to SAP, Oracle, or Microsoft Dynamics
  Accounting Software**: Push data to QuickBooks, Xero, or FreshBooks
  Approval Workflows**: Add review and approval steps before final processing
  Payment Processing**: Connect to banking systems for automated payment scheduling

  Advanced Analytics & Reporting
  Generate business insights:
  Vendor Performance Analysis**: Track pricing trends and payment terms
  Expense Category Reporting**: Automated expense categorization and analysis
  Cash Flow Forecasting**: Predict payment obligations based on due dates
  Audit Trail Management**: Maintain comprehensive processing logs for compliance

  📊 Extracted Data Structure

  Standard Invoice Fields (25+ Data Points)
  The AI extraction captures comprehensive invoice information:

  Header Information:
  Billed To (Customer/Company Name)
  Invoice Number (Unique Identifier)
  Date of Issue (Invoice Creation Date)
  Due Date (Payment Deadline)

  Line Item Details:
  Item Description (Product/Service Details)
  Quantity (Number of Items/Hours)
  Rate (Unit Price)
  Amount (Line Total)

  Tax and Financial Calculations:
  CGST/SGST Rates and Amounts (Indian GST System)
  VAT Calculations (European Tax System)
  Subtotal (Pre-tax Amount)
  Total Amount (Final Invoice Value)

  Company and Contact Information:
  Vendor Company Name
  Contact Phone/Mobile
  Email Address
  Website URL
  GST Registration Number
  PAN Number (Indian Tax ID)

  Address Information:
  Billing Address
  Shipping Address  
  Place of Supply
  Place of Delivery

  Payment Details:
  Transaction IDs
  Payment Mode (Check, Bank Transfer, Card)
  Terms and Conditions
  Special Instructions

  Sample Extracted Data:
  {
    "billed_to": "Tech Solutions Inc.",
    "invoice_number": "INV-2024-0156",
    "date_of_issue": "2024-03-15",
    "due_date": "2024-04-15",
    "item_0_description": "Web Development Services",
    "item_0_quantity": 40,
    "item_0_rate": 75.00,
    "item_0_amount": 3000.00,
    "tax_0_cgst_rate": 9,
    "tax_0_cgst_amount": 270.00,
    "tax_0_sgst_rate": 9,
    "tax_0_sgst_amount": 270.00,
    "subtotal": 3000.00,
    "total": 3540.00,
    "company_name": "Digital Services LLC",
    "company_email": "billing@digitalservices.com",
    "payment_transaction_ids": "TXN123456789",
    "mode_of_payment": "Bank Transfer"
  }

  🛠️ Troubleshooting & Best Practices

  Common Issues & Solutions

  PDF Extraction Challenges
  Scanned Documents**: Original workflow handles text-based PDFs only
  Complex Layouts**: Some invoice formats may require prompt refinement
  Multi-Page Invoices**: Large invoices might need pagination handling
  Password Protection**: Encrypted PDFs require manual processing

  AI Extraction Accuracy
  Field Recognition**: Some custom invoice formats may need prompt tuning
  Currency Handling**: Multi-currency invoices may require specific configuration
  Date Formats**: International date formats might need standardization
  Vendor Variations**: Different vendor invoice styles may affect accuracy

  Gmail Integration Limitations
  Label Management**: Ensure consistent labeling for proper processing
  Attachment Size**: Large PDFs may hit Gmail API limits
  Email Volume**: High-volume processing may require rate limiting
  Security Settings**: Corporate Gmail may have additional restrictions

  Optimization Strategies

  Processing Efficiency
  Batch Processing**: Group similar invoices for more efficient processing
  Template Recognition**: Create vendor-specific extraction templates
  Quality Scoring**: Implement confidence ratings for extracted data
  Error Handling**: Add fallback processes for failed extractions

  Data Quality Assurance
  Validation Rules**: Implement business logic for data verification
  Duplicate Detection**: Prevent duplicate invoice processing
  Manual Review Queues**: Flag uncertain extractions for human review
  Audit Logging**: Maintain detailed processing logs for troubleshooting

  Business Process Integration
  Approval Workflows**: Add management approval steps for high-value invoices
  Exception Handling**: Create special processes for unusual invoice types
  Reporting Automation**: Generate regular summaries of processed invoices
  Archive Management**: Implement retention policies for processed documents

  📈 Success Metrics

  Efficiency Improvements
  Processing Time**: Reduce manual data entry from hours to minutes
  Accuracy Rates**: Achieve 95%+ data extraction accuracy
  Volume Capacity**: Process 10-50x more invoices with same resources
  Error Reduction**: Eliminate manual transcription errors

  Business Impact Measurements
  Cost Savings**: Calculate labor cost reduction from automation
  Cash Flow Management**: Faster invoice processing enables better payment scheduling
  Compliance**: Improved audit trails and data consistency
  Scalability**: Ability to handle business growth without proportional staff increase

  📞 Questions & Support

  Need help implementing or optimizing your AI Invoice Processor Agent?

  📧 Expert Technical Support
  Email**: Yaron@nofluff.online
  Response Time**: Within 24 hours on business days
  Specialization**: Invoice processing automation, AI data extraction, accounting workflow integration

  🎥 Comprehensive Training Resources
  YouTube Channel**: https://www.youtube.com/@YaronBeen/videos
    Complete setup and configuration walkthroughs
    Advanced customization for different invoice types
    Integration tutorials for popular accounting software
    Troubleshooting common extraction and processing issues
    Best practices for financial document automation

  🤝 Professional Community & Updates
  LinkedIn**: https://www.linkedin.com/in/yaronbeen/
    Connect for ongoing automation consulting and support
    Share your invoice processing success stories and ROI results
    Access exclusive workflow templates and advanced configurations
    Join discussions about financial automation trends and innovations

  💬 Support Request Guidelines
  Include in your support message:
  Your current invoice processing volume and types
  Specific vendor formats or invoice layouts you handle
  Target accounting software or systems for integration
  Any technical errors or extraction accuracy issues
  Current manual processing workflow and pain points



  Ready to eliminate manual invoice processing forever? Deploy this AI Invoice Processor Agent and transform your accounting workflow from tedious data entry into intelligent, automated financial management!

nodes_used:
  ["n8n-nodes-base.googleSheets","n8n-nodes-base.googleDrive","n8n-nodes-base.code","@n8n/n8n-nodes-langchain.agent","@n8n/n8n-nodes-langchain.lmChatOpenAi"]

workflow_json:
  {"meta":{"instanceId":"5aaf4236c70e34e423fbdb2c7b754d19253a933bb1476d548f75848a01e473cf","templateCredsSetupCompleted":true},"nodes":[{"id":"70ca3a90-55c8-4e46-9278-6a8fd3d107cd","name":"Gmail Trigger","type":"n8n-nodes-base.gmailTrigger","position":[-1820,220],"parameters":{"simple":false,"filters":{"labelIds":["Label_1393502052621954450"]},"options":{"downloadAttachments":true},"pollTimes":{"item":[{"mode":"everyMinute"}]}},"typeVersion":1.2},{"id":"f7dcff0f-7e98-4042-a33e-2fc32d876908","name":"Create blank spreadsheet","type":"n8n-nodes-base.googleSheets","position":[-780,220],"parameters":{"title":"=invoice_{{ $now }}","options":{},"resource":"spreadsheet","sheetsUi":{"sheetValues":[{"title":"=invoice_details"}]}},"executeOnce":false,"typeVersion":4.5},{"id":"9769ad04-a41c-4d55-806a-042b7d00e131","name":"Move spreadsheet in invoice folder","type":"n8n-nodes-base.googleDrive","position":[-560,220],"parameters":{"fileId":{"__rl":true,"mode":"id","value":"={{ $json.spreadsheetId }}"},"driveId":{"__rl":true,"mode":"list","value":"My Drive","cachedResultUrl":"https://drive.google.com/drive/my-drive","cachedResultName":"My Drive"},"folderId":{"__rl":true,"mode":"list","value":"1JIdajTJvK6gj4bRjniBJvHEJbQ1pn3AM","cachedResultUrl":"https://drive.google.com/drive/folders/1JIdajTJvK6gj4bRjniBJvHEJbQ1pn3AM","cachedResultName":"invoices"},"operation":"move"},"typeVersion":3},{"id":"f9dbfe55-70b0-4abc-9745-9f4a65d5d1c2","name":"OpenAI Chat Model","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[-1180,480],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o-mini"},"options":{"responseFormat":"json_object"}},"credentials":{"openAiApi":{"id":"7dME1fmMlkFyzFjq","name":"OpenAi account 2"}},"typeVersion":1.2},{"id":"00c59142-6079-4e9c-9374-ad487e48f072","name":"Attachment Verification","type":"n8n-nodes-base.filter","position":[-1600,220],"parameters":{"options":{"ignoreCase":false},"conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"efd974d9-aa20-461a-86ae-6e0a16d1527d","operator":{"type":"object","operation":"exists","singleValue":true},"leftValue":"={{ $('Gmail Trigger').item.binary }}","rightValue":""}]}},"typeVersion":2.2},{"id":"8a29ac14-be2b-468a-97fa-540d28e80006","name":"Extract Invoice data","type":"n8n-nodes-base.extractFromFile","position":[-1380,220],"parameters":{"options":{},"operation":"pdf","binaryPropertyName":"={{ $('Attachment Verification').item.binary.keys() }}"},"typeVersion":1},{"id":"ae08cdc8-fcf9-4891-be86-b2dcf6f35278","name":"Preparing Final data","type":"n8n-nodes-base.code","position":[-340,220],"parameters":{"mode":"runOnceForEachItem","jsCode":"// Loop over input items and add a new field called 'myNewField' to the JSON of $input$json.output.first().json.outputeach one\n\nlet invoice_details = $('Invoice AI Agent').item.json.output\n\nreturn JSON.parse(invoice_details)"},"typeVersion":2},{"id":"7615a5b0-8761-43e2-82b0-32ac5c772f44","name":"Final Spreadsheet with Invoice data","type":"n8n-nodes-base.googleSheets","position":[-140,220],"parameters":{"columns":{"value":{},"schema":[{"id":"billed_to","type":"string","display":true,"removed":false,"required":false,"displayName":"billed_to","defaultMatch":false,"canBeUsedToMatch":true},{"id":"invoice_number","type":"string","display":true,"removed":false,"required":false,"displayName":"invoice_number","defaultMatch":false,"canBeUsedToMatch":true},{"id":"date_of_issue","type":"string","display":true,"removed":false,"required":false,"displayName":"date_of_issue","defaultMatch":false,"canBeUsedToMatch":true},{"id":"due_date","type":"string","display":true,"removed":false,"required":false,"displayName":"due_date","defaultMatch":false,"canBeUsedToMatch":true},{"id":"item_0_description","type":"string","display":true,"removed":false,"required":false,"displayName":"item_0_description","defaultMatch":false,"canBeUsedToMatch":true},{"id":"item_0_quantity","type":"string","display":true,"removed":false,"required":false,"displayName":"item_0_quantity","defaultMatch":false,"canBeUsedToMatch":true},{"id":"item_0_rate","type":"string","display":true,"removed":false,"required":false,"displayName":"item_0_rate","defaultMatch":false,"canBeUsedToMatch":true},{"id":"item_0_amount","type":"string","display":true,"removed":false,"required":false,"displayName":"item_0_amount","defaultMatch":false,"canBeUsedToMatch":true},{"id":"tax_0_cgst_rate","type":"string","display":true,"removed":false,"required":false,"displayName":"tax_0_cgst_rate","defaultMatch":false,"canBeUsedToMatch":true},{"id":"tax_0_cgst_amount","type":"string","display":true,"removed":false,"required":false,"displayName":"tax_0_cgst_amount","defaultMatch":false,"canBeUsedToMatch":true},{"id":"tax_0_sgst_rate","type":"string","display":true,"removed":false,"required":false,"displayName":"tax_0_sgst_rate","defaultMatch":false,"canBeUsedToMatch":true},{"id":"tax_0_sgst_amount","type":"string","display":true,"removed":false,"required":false,"displayName":"tax_0_sgst_amount","defaultMatch":false,"canBeUsedToMatch":true},{"id":"item_0_total_amount","type":"string","display":true,"removed":false,"required":false,"displayName":"item_0_total_amount","defaultMatch":false,"canBeUsedToMatch":true},{"id":"subtotal","type":"string","display":true,"removed":false,"required":false,"displayName":"subtotal","defaultMatch":false,"canBeUsedToMatch":true},{"id":"total","type":"string","display":true,"removed":false,"required":false,"displayName":"total","defaultMatch":false,"canBeUsedToMatch":true},{"id":"terms","type":"string","display":true,"removed":false,"required":false,"displayName":"terms","defaultMatch":false,"canBeUsedToMatch":true},{"id":"conditions_instructions","type":"string","display":true,"removed":false,"required":false,"displayName":"conditions_instructions","defaultMatch":false,"canBeUsedToMatch":true},{"id":"company_name","type":"string","display":true,"removed":false,"required":false,"displayName":"company_name","defaultMatch":false,"canBeUsedToMatch":true},{"id":"company_mobile","type":"string","display":true,"removed":false,"required":false,"displayName":"company_mobile","defaultMatch":false,"canBeUsedToMatch":true},{"id":"company_email","type":"string","display":true,"removed":false,"required":false,"displayName":"company_email","defaultMatch":false,"canBeUsedToMatch":true},{"id":"company_website","type":"string","display":true,"removed":false,"required":false,"displayName":"company_website","defaultMatch":false,"canBeUsedToMatch":true},{"id":"payment_transaction_ids","type":"string","display":true,"removed":false,"required":false,"displayName":"payment_transaction_ids","defaultMatch":false,"canBeUsedToMatch":true},{"id":"mode_of_payment","type":"string","display":true,"removed":false,"required":false,"displayName":"mode_of_payment","defaultMatch":false,"canBeUsedToMatch":true},{"id":"billing_address","type":"string","display":true,"removed":false,"required":false,"displayName":"billing_address","defaultMatch":false,"canBeUsedToMatch":true},{"id":"shipping_address","type":"string","display":true,"removed":false,"required":false,"displayName":"shipping_address","defaultMatch":false,"canBeUsedToMatch":true},{"id":"place_of_supply","type":"string","display":true,"removed":false,"required":false,"displayName":"place_of_supply","defaultMatch":false,"canBeUsedToMatch":true},{"id":"place_of_delivery","type":"string","display":true,"removed":false,"required":false,"displayName":"place_of_delivery","defaultMatch":false,"canBeUsedToMatch":true},{"id":"gst_registration_no","type":"string","display":true,"removed":false,"required":false,"displayName":"gst_registration_no","defaultMatch":false,"canBeUsedToMatch":true},{"id":"pan_no","type":"string","display":true,"removed":false,"required":false,"displayName":"pan_no","defaultMatch":false,"canBeUsedToMatch":true}],"mappingMode":"autoMapInputData","matchingColumns":[],"attemptToConvertTypes":false,"convertFieldsToString":false},"options":{},"operation":"append","sheetName":{"__rl":true,"mode":"name","value":"invoice_details"},"documentId":{"__rl":true,"mode":"id","value":"={{ $('Create blank spreadsheet').item.json.spreadsheetId }}"}},"typeVersion":4.5},{"id":"e68aa386-7150-4070-a5d7-1dcb963b620d","name":"Invoice AI Agent","type":"@n8n/n8n-nodes-langchain.agent","position":[-1160,220],"parameters":{"text":"={{ $json.text }}","options":{"systemMessage":"you are an financial advisor , who reads the array of data to identify certain elements of an Invoice, from the input data and provide a json response. use only following specified keys \nfor example:\n{\n\"billed_to\": \"John\",\n\"invoice_number\": \"569871234\",\n\"date_of_issue\": \"2025-05-21\",\n\"due_date\": \"2025-05-25\",\n\"item_0_description\": \"Computer CPU\",\n\"item_0_quantity\": 6,\n\"item_0_rate\": 15,\n\"item_0_amount\": 90,\n\"item_1_description\": \"Chair Wooden\",\n\"item_1_quantity\": 8,\n\"item_1_rate\": 10,\n\"item_1_amount\": 80,\n\"subtotal\": 170.00,\n\"discount\": 20.00,\n\"total\": 150.00,\n\"terms\": \"Sold items not be acceptable\",\n\"conditions_instructions\": \"xyaABC\",\n\"company_name\": \"Digital Electronics\",\n\"company_mobile\": \"987654321\",\n\"company_email\": \"ayz@gmail.com\",\n\"company_website\": \"www.abc.com\"\n}"},"promptType":"define","hasOutputParser":true},"typeVersion":1.9,"alwaysOutputData":false},{"id":"335a80c5-ad86-4379-b1a6-9a2ef7285f3c","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[-2860,100],"parameters":{"width":880,"height":1520,"content":"AI Invoice Processor Agent: Email to Structured Data\nAutomatically extract, analyze, and organize invoice data from Gmail attachments into structured Google Sheets. Perfect for:\n✅ Accountants & bookkeepers — eliminate manual data entry from invoices\n✅ Small businesses — streamline invoice processing and tracking\n✅ Finance teams — automate accounts payable workflows\n\n⚙️ What's Used\nn8n Nodes:\nGmail Trigger → File Extraction → AI Agent → OpenAI Chat Model → Google Sheets → Google Drive\nExternal Tools:\n\nGmail API – Monitor specific labeled emails with attachments\nPDF Extraction – Convert invoice PDFs to readable text\nOpenAI GPT-4 – Intelligent invoice data extraction and structuring\nGoogle Sheets – Create organized spreadsheets with invoice details\nGoogle Drive – Automatically organize files in invoice folders\n\n\n🔑 Setup – Credentials Needed\n\nGmail OAuth2 → Access emails and download attachments\nOpenAI API Key → For AI-powered invoice data extraction\nGoogle Sheets OAuth2 → Create and populate spreadsheets\nGoogle Drive OAuth2 → Organize files in designated folders\n\n\n📧 Gmail Setup Required\nCreate a Gmail label (e.g., \"Invoice Processing\") and apply it to emails containing invoice attachments. The workflow will monitor this label for new emails every minute.\n\n🚀 Workflow Steps\n\nEmail Monitoring\nContinuously watches Gmail for new emails with specific labels and attachments\nAttachment Verification\nFilters emails to ensure they contain PDF attachments before processing\nData Extraction\nConverts PDF invoices to text and extracts readable content\nAI-Powered Analysis\nGPT processes invoice text and extracts structured data including:\n\nCompany details and contact information\nInvoice numbers, dates, and due dates\nLine items with quantities, rates, and amounts\nTax calculations (CGST, SGST, VAT)\nPayment terms and billing addresses\n\n\nSpreadsheet Creation\nCreates timestamped Google Sheets with organized invoice data\nFile Organization\nMoves processed spreadsheets to designated Drive folders for easy access\n\n\n📊 Extracted Data Fields\nThe AI identifies and organizes 25+ invoice elements:\n\nHeader Info: Billed to, invoice number, dates\nLine Items: Description, quantity, rate, amount\nTax Details: CGST/SGST rates and amounts\nCompany Info: Name, contact details, GST numbers\nPayment Info: Transaction IDs, payment methods\nAddresses: Billing, shipping, delivery locations\n\n\n💡 Pro Tips\n\nUse clear Gmail labels for different invoice types (vendors, clients, etc.)\nEnsure invoice PDFs are text-based (not scanned images) for best results\nCreate separate Drive folders for different accounting periods\nReview AI extraction accuracy and refine prompts as needed\nSet up email filters to automatically apply labels to vendor emails\n\n\n🛠️ Customize It\n\nAdd invoice approval workflows with email notifications\nConnect to accounting software (QuickBooks, Xero, SAP)\nInclude OCR processing for scanned invoice images\nAdd duplicate invoice detection and alerts\nCreate automated payment reminders based on due dates"},"typeVersion":1}],"pinData":{},"connections":{"Gmail Trigger":{"main":[[{"node":"Attachment Verification","type":"main","index":0}]]},"Invoice AI Agent":{"main":[[{"node":"Create blank spreadsheet","type":"main","index":0}]]},"OpenAI Chat Model":{"ai_languageModel":[[{"node":"Invoice AI Agent","type":"ai_languageModel","index":0}]]},"Extract Invoice data":{"main":[[{"node":"Invoice AI Agent","type":"main","index":0}]]},"Preparing Final data":{"main":[[{"node":"Final Spreadsheet with Invoice data","type":"main","index":0}]]},"Attachment Verification":{"main":[[{"node":"Extract Invoice data","type":"main","index":0}]]},"Create blank spreadsheet":{"main":[[{"node":"Move spreadsheet in invoice folder","type":"main","index":0}]]},"Move spreadsheet in invoice folder":{"main":[[{"node":"Preparing Final data","type":"main","index":0}]]}}}


name: Generate & Edit Images with OpenAI GPT-Image-1 and Share via Telegram
author_name: Alexey from Mingles.ai
author_username: alexx
nodes_used: ["n8n-nodes-base.httpRequest","n8n-nodes-base.telegram","n8n-nodes-base.googleDrive"]
categories: []
created_at: 2025-05-26T08:42:12.797Z
updated_at: 2025-05-26T08:42:12.797Z
url: https://n8n.io/workflows/4391
scraped_at: 2025-06-19 22:50:36
description:
  AI Image Generator & Editor with GPT-4 Vision - Complete Workflow

  Template Description

  Transform text prompts into stunning images or edit existing visuals using OpenAI's latest GPT-4 Vision model through an intuitive web form interface.

  This comprehensive n8n automation provides three powerful image generation modes:

  🎨 Text-to-Image Generation
  Simply enter a descriptive prompt and generate high-quality images from scratch using OpenAI's gpt-image-1 model. Perfect for creating original artwork, concepts, or visual content.

  🖼️ Image-to-Image Editing 
  Upload an existing image file and transform it based on your text prompt. The AI analyzes your input image and applies modifications while maintaining the original structure and context.

  🔗 URL-Based Image Editing
  Provide a direct URL to any online image and edit it with AI. Great for quick modifications of web images or collaborative workflows.

  Key Features

  Smart Input Processing
  Flexible Form Interface**: User-friendly web form with authentication
  Multiple Input Methods**: File upload, URL input, or text-only generation
  Quality Control**: Selectable quality levels (low, medium, high)
  Format Support**: Accepts PNG, JPG, and JPEG formats

  Advanced AI Integration
  Latest GPT-4 Vision Model**: Uses gpt-image-1 for superior results
  Intelligent Switching**: Automatically detects input type and routes accordingly
  Context-Aware Editing**: Maintains image coherence during modifications
  Customizable Parameters**: Control size (1024x1024), quality, and generation settings

  Dual Storage Options
  Google Drive Integration**: Automatic upload with public sharing permissions
  ImgBB Hosting**: Alternative cloud storage for instant public URLs
  File Management**: Organized storage with timestamp-based naming

  Instant Telegram Delivery
  Real-time Notifications**: Results sent directly to your Telegram chat
  Rich Media Messages**: Includes generated image with prompt details
  Quick Access Links**: Direct links to view and download results
  Markdown Formatting**: Clean, professional message presentation

  Technical Workflow

  Form Submission → User submits prompt and optional image
  Smart Routing → System detects input type (text/file/URL)
  AI Processing → OpenAI generates or edits image based on mode
  Binary Conversion → Converts base64 response to downloadable file
  Cloud Upload → Stores in Google Drive or ImgBB with public access
  Telegram Delivery → Sends result with viewing links and metadata

  Perfect For

  Content Creators**: Generate unique visuals for social media and marketing
  Designers**: Quick concept development and image variations
  Developers**: Automated image processing for applications
  Teams**: Collaborative image editing and sharing workflows
  Personal Use**: Transform ideas into visual content effortlessly

  Setup Requirements

  OpenAI API Key**: Access to GPT-4 Vision model
  Google Drive API** (optional): For Google Drive storage
  ImgBB API Key** (optional): For alternative image hosting
  Telegram Bot**: For result delivery
  Basic Auth Credentials**: For form security

  What You Get

  ✅ Complete image generation and editing pipeline  
  ✅ Secure web form with authentication  
  ✅ Dual cloud storage options  
  ✅ Instant Telegram notifications  
  ✅ Professional result formatting  
  ✅ Flexible input methods  
  ✅ Quality control settings  
  ✅ Automated file management  

  Start creating AI-powered images in minutes with this production-ready template!

  Tags: #AI #ImageGeneration #OpenAI #GPT4 #ImageEditing #Telegram #GoogleDrive #Automation #ComputerVision #ContentCreation

workflow_json:
  {"meta":{"instanceId":"2fa7acc0cd134988fb8b40b8d8b56c9f29ee37789503fef505450e2733dc2bdf","templateCredsSetupCompleted":true},"nodes":[{"id":"0b66ad6f-d216-41f3-a6dc-61cf15a2044a","name":"Set Access Permissions","type":"n8n-nodes-base.googleDrive","position":[-2220,-1000],"parameters":{"fileId":{"__rl":true,"mode":"id","value":"={{ $json.id }}"},"options":{},"operation":"share","permissionsUi":{"permissionsValues":{"role":"reader","type":"anyone"}},"authentication":"serviceAccount"},"credentials":{"googleApi":{"id":"vM5RNejQ9XDoP6Ld","name":"Google Sheets n8n dev service account"}},"typeVersion":3},{"id":"724b14c0-6763-47f5-87a1-ed0dde7e8a9e","name":"Edit Image (OpenAI)","type":"n8n-nodes-base.httpRequest","position":[-3060,-1000],"parameters":{"url":"https://api.openai.com/v1/images/edits","method":"POST","options":{},"sendBody":true,"contentType":"multipart-form-data","authentication":"predefinedCredentialType","bodyParameters":{"parameters":[{"name":"image","parameterType":"formBinaryData","inputDataFieldName":"={{ $json[\"input image url\"].isEmpty()?\"input_image\":\"data\"}}"},{"name":"prompt","value":"={{ $json.Promt }}"},{"name":"model","value":"gpt-image-1"},{"name":"n","value":"1"},{"name":"size","value":"1024x1024"},{"name":"quality","value":"={{ $json.quality }}"}]},"nodeCredentialType":"openAiApi"},"credentials":{"openAiApi":{"id":"3ff0w5x5tfolokJ7","name":"OpenAi account mingles new dev user"}},"typeVersion":4.2},{"id":"071f9711-3b73-411d-9962-b540f0b418c7","name":"Convert json binary to File","type":"n8n-nodes-base.convertToFile","position":[-2740,-620],"parameters":{"options":{"fileName":"={{ $now.format('yyyy-MM-dd_HHmmss')+\".png\" }}","mimeType":"image/png"},"operation":"toBinary","sourceProperty":"data[0].b64_json"},"typeVersion":1.1},{"id":"e22377ef-1bbf-4288-a625-d07a97d5667d","name":"Convert json binary to File final","type":"n8n-nodes-base.convertToFile","position":[-2740,-1000],"parameters":{"options":{"fileName":"={{ $now.format('yyyy-MM-dd_HHmmss')+\".png\" }}","mimeType":"image/png"},"operation":"toBinary","sourceProperty":"data[0].b64_json"},"typeVersion":1.1},{"id":"5aabd61e-5407-4be7-b6c9-ab77c7cadad7","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[-3140,-780],"parameters":{"color":3,"width":280,"height":340,"content":"### 🎨 Image Generation (OpenAI)\nSends a POST request to the OpenAI `/v1/images/generations` endpoint.\n\n- Uses `gpt-image-1` model"},"typeVersion":1},{"id":"93be8801-7fb4-42d7-af2d-1047b8c60d6e","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[-2840,-1200],"parameters":{"color":5,"width":300,"height":760,"content":"### 🧾 Convert base64 to File\nConverts the `b64_json` field into a binary PNG file to use in the next step.\n\n📤 Output: Final binary image\n"},"typeVersion":1},{"id":"aeafd971-28ad-4c5c-8d26-0d81f82fac01","name":"Sticky Note3","type":"n8n-nodes-base.stickyNote","position":[-3140,-1200],"parameters":{"color":3,"width":280,"height":360,"content":"### ✏️ Image to image generation (OpenAI)\nSends the binary image to OpenAI’s `/v1/images/edits` endpoint with a descriptive prompt.\n\n- Model: `gpt-image-1`"},"typeVersion":1},{"id":"930bba79-34c4-40da-b22f-4f42b9894705","name":"On form submission","type":"n8n-nodes-base.formTrigger","position":[-3860,-840],"webhookId":"e3e1e092-d5fb-4e15-911e-3bc98e916c9f","parameters":{"options":{},"formTitle":"GPT image to image","formFields":{"values":[{"fieldLabel":"Promt","requiredField":true},{"fieldType":"dropdown","fieldLabel":"quality","fieldOptions":{"values":[{"option":"low"},{"option":"medium"},{"option":"high"}]},"requiredField":true},{"fieldType":"file","fieldLabel":"input image","multipleFiles":false,"acceptFileTypes":".png,.jpg,.jpeg"},{"fieldLabel":"input image url"}]},"responseMode":"lastNode","authentication":"basicAuth"},"credentials":{"httpBasicAuth":{"id":"EzEYGeSYuNmHnrQn","name":"reels maker auth"}},"typeVersion":2.2},{"id":"abb8a008-0dcb-427c-a00a-7c850790cf4f","name":"Upload Result Image to imgbb","type":"n8n-nodes-base.httpRequest","position":[-2220,-640],"parameters":{"url":"https://api.imgbb.com/1/upload","method":"POST","options":{"redirect":{"redirect":{}}},"sendBody":true,"contentType":"multipart-form-data","bodyParameters":{"parameters":[{"name":"image","parameterType":"formBinaryData","inputDataFieldName":"data"},{"name":"key","value":"={{ $json.IMGBB_API_KEY }}"}]}},"typeVersion":4.2},{"id":"ec0fc073-15f9-4cdf-a2f4-19de2c2b3261","name":"Upload Result Image to Google Drive","type":"n8n-nodes-base.googleDrive","position":[-2440,-1000],"parameters":{"name":"={{ $input.item.binary.data.fileName }}","driveId":{"__rl":true,"mode":"list","value":"My Drive","cachedResultUrl":"https://drive.google.com/drive/my-drive","cachedResultName":"My Drive"},"options":{},"folderId":{"__rl":true,"mode":"list","value":"root","cachedResultUrl":"https://drive.google.com/drive","cachedResultName":"/ (Root folder)"},"authentication":"serviceAccount"},"credentials":{"googleApi":{"id":"vM5RNejQ9XDoP6Ld","name":"Google Sheets n8n dev service account"}},"typeVersion":3},{"id":"7487229b-5e94-48d4-b84c-a5725e529e23","name":"File Link","type":"n8n-nodes-base.set","position":[-2020,-1000],"parameters":{"options":{},"assignments":{"assignments":[{"id":"df673a7d-7ff2-4c7e-835f-7c65e58c5ad4","name":"ViewLink","type":"string","value":"={{ $('Upload Result Image to Google Drive').item.json.webViewLink }}"},{"id":"c3447718-d652-45d7-9c6f-6a1d4f29a68d","name":"ContentLink","type":"string","value":"={{ $('Upload Result Image to Google Drive').item.json.webContentLink }}"}]}},"typeVersion":3.4},{"id":"f4f2a07d-4a5e-45d9-96d6-0f5eb1359d6f","name":"Get Input Image by URL","type":"n8n-nodes-base.httpRequest","position":[-3360,-840],"parameters":{"url":"={{ $json['input image url'] }}","options":{}},"typeVersion":4.2},{"id":"613aa7b5-8f63-490f-9026-de4971619e41","name":"SETUP API KEY","type":"n8n-nodes-base.set","position":[-2440,-640],"parameters":{"options":{},"assignments":{"assignments":[{"id":"f0df22ed-6c69-4204-8cfb-8dae51ea8fd4","name":"IMGBB_API_KEY","type":"string","value":"IMGBB_API_KEY"}]},"includeOtherFields":true},"typeVersion":3.4},{"id":"5e276d4c-05c0-4aa2-9f3c-88669c2d259a","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[-2500,-1200],"parameters":{"color":6,"width":640,"height":760,"content":"## Upload result file to Google Drive OR to [imgbb](https://api.imgbb.com/)"},"typeVersion":1},{"id":"38760191-c39a-4a62-a222-324e5cd83590","name":"Image Generation","type":"n8n-nodes-base.httpRequest","position":[-3060,-620],"parameters":{"url":"https://api.openai.com/v1/images/generations","method":"POST","options":{},"sendBody":true,"authentication":"predefinedCredentialType","bodyParameters":{"parameters":[{"name":"model","value":"gpt-image-1"},{"name":"prompt","value":"={{ $json.Promt }}"},{"name":"n","value":"={{Number(1)}}"},{"name":"size","value":"1024x1024"},{"name":"moderation","value":"low"},{"name":"background","value":"auto"},{"name":"quality","value":"={{ $json.quality }}"}]},"nodeCredentialType":"openAiApi"},"credentials":{"openAiApi":{"id":"3ff0w5x5tfolokJ7","name":"OpenAi account mingles new dev user"}},"typeVersion":4.2},{"id":"6abaccab-b49b-41ab-86cd-8bf562472f9d","name":"File Link1","type":"n8n-nodes-base.set","position":[-2000,-640],"parameters":{"options":{},"assignments":{"assignments":[{"id":"df673a7d-7ff2-4c7e-835f-7c65e58c5ad4","name":"ViewLink","type":"string","value":"={{ $json.data.url }}"},{"id":"c3447718-d652-45d7-9c6f-6a1d4f29a68d","name":"ContentLink","type":"string","value":"={{ $json.data.image.url }}"}]}},"typeVersion":3.4},{"id":"7443a6f2-3d0c-4fef-9dbe-56948ea8c17c","name":"Send to Telegram","type":"n8n-nodes-base.telegram","position":[-1740,-840],"webhookId":"150d64ce-d278-4459-b9b9-5d0dfb3afbd1","parameters":{"file":"={{ $json.ContentLink }}","chatId":"YOUR_CHAT_ID","operation":"sendPhoto","additionalFields":{"caption":"={{ $('On form submission').item.json.Promt }}\n{{ $('On form submission').item.json.quality }}\n\n[Result]({{ $json.ViewLink }})","parse_mode":"MarkdownV2"}},"credentials":{"telegramApi":{"id":"ar7qqwMS6eFB8SaY","name":"NyroSikAIbot"}},"typeVersion":1.2},{"id":"efe008a1-1dea-41f8-8778-1556cf0bbbea","name":"Switch Mode","type":"n8n-nodes-base.switch","position":[-3640,-840],"parameters":{"rules":{"values":[{"outputKey":"file","conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"6c2e2793-96f4-4d15-af76-926d1fdcee71","operator":{"type":"boolean","operation":"true","singleValue":true},"leftValue":"={{ $json['input image'] !== null && $json['input image url'].isNotEmpty() }}","rightValue":""}]},"renameOutput":true},{"outputKey":"file_url","conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"9d464a07-f5fe-48af-b524-6ca60479fda6","operator":{"type":"boolean","operation":"true","singleValue":true},"leftValue":"={{ $json['input image url'] !== null && $json['input image url'].isNotEmpty() }}","rightValue":""}]},"renameOutput":true}]},"options":{"fallbackOutput":"extra"}},"typeVersion":3.2}],"pinData":{},"connections":{"File Link":{"main":[[{"node":"Send to Telegram","type":"main","index":0}]]},"File Link1":{"main":[[{"node":"Send to Telegram","type":"main","index":0}]]},"Switch Mode":{"main":[[{"node":"Edit Image (OpenAI)","type":"main","index":0}],[{"node":"Get Input Image by URL","type":"main","index":0}],[{"node":"Image Generation","type":"main","index":0}]]},"SETUP API KEY":{"main":[[{"node":"Upload Result Image to imgbb","type":"main","index":0}]]},"Image Generation":{"main":[[{"node":"Convert json binary to File","type":"main","index":0}]]},"On form submission":{"main":[[{"node":"Switch Mode","type":"main","index":0}]]},"Edit Image (OpenAI)":{"main":[[{"node":"Convert json binary to File final","type":"main","index":0}]]},"Get Input Image by URL":{"main":[[{"node":"Edit Image (OpenAI)","type":"main","index":0}]]},"Set Access Permissions":{"main":[[{"node":"File Link","type":"main","index":0}]]},"Convert json binary to File":{"main":[[{"node":"SETUP API KEY","type":"main","index":0}]]},"Upload Result Image to imgbb":{"main":[[{"node":"File Link1","type":"main","index":0}]]},"Convert json binary to File final":{"main":[[{"node":"Upload Result Image to Google Drive","type":"main","index":0}]]},"Upload Result Image to Google Drive":{"main":[[{"node":"Set Access Permissions","type":"main","index":0}]]}}}


name: Smart Shopify Agent: AI-Powered Abandoned Cart Recovery
author_name: Yaron Been
author_username: yaron-nofluff
categories: []
created_at: 2025-05-26T11:59:22.062Z
updated_at: 2025-05-26T11:59:22.062Z
url: https://n8n.io/workflows/4396
scraped_at: 2025-06-19 22:50:36
description:
  🤖 AI Cart Recovery Agent: Smart Abandoned Checkout Assistant

  Transform abandoned carts into recovered sales with intelligent automation. This sophisticated n8n workflow monitors checkout abandonment, implements smart waiting periods, and sends AI-generated personalized recovery emails only when needed - maximizing conversions while respecting customer experience.

  🔄 How It Works

  This intelligent 7-step recovery system recovers lost sales automatically:

  Step 1: Initial Abandonment Detection
  The workflow fetches current abandoned checkout data from your e-commerce platform (Shopify, WooCommerce, etc.), identifying customers who added items but didn't complete their purchase.

  Step 2: Strategic Grace Period
  Instead of immediately sending recovery emails, the system waits 1 hour (customizable), giving customers natural time to complete their purchase without pressure or interruption.

  Step 3: Smart Re-verification
  After the waiting period, the workflow rechecks the abandonment status by fetching updated checkout data, ensuring accuracy before taking action.

  Step 4: Intelligent Decision Logic
  Advanced conditional logic compares initial and updated abandonment lists, determining if customers are still abandoned or have completed their purchase during the grace period.

  Step 5: AI-Powered Email Generation
  For customers still showing abandonment, GPT generates personalized recovery emails featuring:
  Customer's actual name for personal connection
  Specific products left in their cart
  Friendly, non-pushy messaging tone
  Optional discount incentives
  Compelling call-to-action to complete purchase

  Step 6: Automated Email Delivery
  Personalized recovery emails are sent directly to abandoned customers via Gmail or your preferred email service, maintaining professional branding and deliverability.

  Step 7: Comprehensive Activity Logging
  All recovery attempts are logged in Google Sheets for tracking, including customer details, email content, and campaign performance analytics.

  ⚙️ Setup Steps

  Prerequisites
  E-commerce platform with API access (Shopify, WooCommerce, BigCommerce)
  OpenAI API key for personalized email generation
  Gmail or SMTP email service for delivery
  Google Sheets for activity tracking and analytics
  n8n instance (cloud or self-hosted)

  E-commerce Platform Configuration

  Shopify Setup:
  API Endpoint: https://your-store.myshopify.com/admin/api/2023-10/checkouts.json
  Authentication: X-Shopify-Access-Token header
  Required Permissions: Read checkouts, Read customers
  Parameters: status=abandoned

  WooCommerce Setup:
  API Endpoint: https://your-site.com/wp-json/wc/v3/orders
  Authentication: Consumer Key/Secret or JWT
  Parameters: status=pending, status=failed
  Required Plugins: WooCommerce REST API

  Configuration Steps

  1. Credential Setup
  E-commerce API**: Store admin API access tokens or keys
  OpenAI API Key**: GPT-4 access for intelligent email generation
  Gmail OAuth2**: Professional email delivery service
  Google Sheets OAuth2**: Activity logging and performance tracking

  2. Abandonment Detection Configuration
  Monitoring Frequency**: Set workflow trigger schedule (hourly, daily)
  Grace Period Duration**: Customize wait time (default: 1 hour)
  Platform Integration**: Configure API endpoints for your specific platform
  Data Filtering**: Set criteria for what constitutes abandonment

  3. AI Email Customization
  Default email generation includes:
  Personalization Level**: Customer name, product specifics, cart value
  Tone Customization**: Friendly, urgent, helpful, or premium
  Discount Integration**: Optional percentage or fixed amount offers
  Brand Voice**: Maintain consistent company messaging and style

  4. Recovery Campaign Settings
  Email Timing**: Optimal sending times based on customer time zones
  Frequency Limits**: Prevent over-emailing with cooldown periods
  Segmentation Rules**: Different approaches for high-value vs standard carts
  Follow-up Sequences**: Multi-email recovery campaigns with escalating incentives

  5. Performance Tracking Setup
  Analytics Dashboard**: Google Sheets with recovery metrics and ROI
  Success Tracking**: Monitor completion rates and revenue recovered
  A/B Testing**: Compare different email approaches and timing
  Customer Journey**: Track from abandonment through recovery completion

  🚀 Use Cases

  E-commerce Retailers
  Fashion & Apparel**: Recover high-value clothing and accessory purchases
  Electronics**: Target abandoned tech purchases with technical support offers
  Home & Garden**: Remind customers about seasonal or home improvement items
  Beauty & Cosmetics**: Recover abandoned skincare and makeup purchases

  Subscription & SaaS Businesses
  Software Trials**: Convert abandoned trial signups into paid subscriptions
  Membership Sites**: Recover incomplete membership purchases
  Online Courses**: Re-engage learners who abandoned course purchases
  Digital Services**: Follow up on abandoned service bookings or consultations

  B2B E-commerce
  Office Supplies**: Recover bulk order abandonments with volume discounts
  Industrial Equipment**: Follow up on high-value equipment quote requests
  Professional Services**: Re-engage businesses that abandoned service bookings
  Software Licenses**: Recover enterprise software purchase abandonments

  Specialty Retailers
  Luxury Goods**: Provide white-glove service for high-value abandoned purchases
  Custom Products**: Follow up on personalized or custom order abandonments
  Seasonal Items**: Time-sensitive recovery for holiday or event-specific products
  Limited Edition**: Create urgency for exclusive or limited availability items

  Service-Based Businesses
  Travel & Hospitality**: Recover abandoned hotel, flight, or package bookings
  Event Tickets**: Re-engage customers who abandoned concert or event purchases
  Professional Services**: Follow up on abandoned consultation or service bookings
  Fitness & Wellness**: Recover abandoned membership or class package purchases

  🔧 Advanced Customization Options

  Multi-Platform Integration
  Extend beyond single platform monitoring:
  Shopify Plus: Advanced checkout analytics and customer segmentation
  WooCommerce: Custom post-purchase and abandonment tracking
  Magento: Enterprise-level cart recovery with customer journey mapping
  BigCommerce: API-driven recovery with advanced personalization
  Custom Platforms: Webhook-based abandonment detection and recovery

  Intelligent Email Sequencing
  Create sophisticated recovery campaigns:
  Progressive Incentives**: Escalating discounts over multiple touchpoints
  Behavioral Triggers**: Different emails based on cart value, customer history
  Seasonal Campaigns**: Holiday-specific recovery messaging and offers
  Win-Back Sequences**: Long-term customer re-engagement beyond immediate recovery

  Advanced Personalization
  Enhance AI-generated content with:
  Purchase History Analysis**: Reference previous purchases and preferences
  Browsing Behavior**: Include recently viewed items and categories
  Geographic Personalization**: Local offers, shipping options, or store locations
  Demographic Targeting**: Age, gender, or interest-based messaging customization

  Performance Optimization
  Implement advanced tracking and optimization:
  Revenue Attribution**: Track exact recovery amounts and ROI calculations
  Customer Lifetime Value**: Prioritize high-value customer recovery efforts
  Conversion Funnel Analysis**: Identify optimal timing and messaging strategies
  Predictive Analytics**: Use ML to predict recovery likelihood and optimize approaches

  📊 Recovery Email Examples

  Fashion Retailer Example:
  Subject: You left something stylish behind, Sarah!

  Hi Sarah,

  I noticed you were checking out those gorgeous items in your cart earlier - the Bohemian Summer Dress and Classic Leather Handbag have been waiting for you!

  I completely understand if you got busy or needed time to think it over. These pieces are still available and ready to ship to you today.

  Since you showed such great taste in selecting these items, I'd love to offer you 10% off your order to make the decision easier. Just use code WELCOME10 at checkout.

  Your cart includes:
  • Bohemian Summer Dress (Size M) - $89.99
  • Classic Leather Handbag (Brown) - $156.99

  Complete your purchase now and get free shipping to your door!

  [Complete My Purchase] 

  Best regards,
  The StyleHub Team

  P.S. These items are popular and inventory is limited - don't wait too long!

  Software/SaaS Example:
  Subject: Your ProductivityPro trial is waiting, Mike

  Hi Mike,

  You were just one step away from unlocking the full power of ProductivityPro for your team at TechStartup Inc.

  I noticed you explored our Premium Plan features - the advanced reporting and team collaboration tools that could streamline your workflow and boost productivity by up to 40%.

  Since you invested time exploring our platform, I'd like to offer you an exclusive 25% discount on your first year. This offer is valid for the next 48 hours.

  Your selected plan:
  • ProductivityPro Premium (5 users) - $99/month
  • With 25% discount: $74/month (Save $300/year!)

  Ready to transform your team's productivity?

  [Activate My Account]

  Questions? Reply to this email or schedule a quick 15-minute demo call.

  Best regards,
  David Chen
  Customer Success Manager, ProductivityPro

  High-Value B2B Example:
  Subject: Your equipment quote is ready for approval, Jennifer

  Hi Jennifer,

  Thank you for your interest in our Industrial Packaging System for ManuCorp's new facility expansion.

  I understand that equipment investments of this scale require careful consideration and stakeholder alignment. Your configured system includes:

  • Model X5000 Packaging Line - $45,000
  • Installation & Training Package - $8,000  
  • Extended 3-Year Warranty - $3,500
  Total Investment: $56,500

  Given the scope of your project, I'd like to extend our Q1 promotion pricing, which provides:
  15% discount on equipment ($6,750 savings)
  Free installation supervision ($2,000 value)
  Expedited 6-week delivery

  This brings your total to $48,750 - a savings of $7,750.

  I'm available for a brief call to address any technical questions or help facilitate internal approvals. 

  [Accept Quote & Proceed]

  Best regards,
  Robert Martinez
  Senior Sales Engineer
  Industrial Solutions Inc.
  Direct: (555) 123-4567

  🛠️ Troubleshooting & Best Practices

  Common Issues & Solutions

  API Rate Limiting
  Implement exponential backoff for API requests
  Stagger workflow execution times across different stores
  Monitor API usage and upgrade plans as needed
  Cache frequently accessed data to reduce API calls

  Email Deliverability Challenges
  Use authenticated SMTP services with proper SPF/DKIM setup
  Monitor sender reputation and email engagement metrics
  Implement opt-out mechanisms and respect unsubscribe requests
  Segment email lists and avoid over-emailing customers

  False Positive Recoveries
  Extend grace periods for complex checkout processes
  Implement more sophisticated abandonment detection logic
  Add customer behavior analysis before triggering recovery
  Create exception rules for technical checkout failures

  Optimization Strategies

  Recovery Timing Optimization
  A/B test different grace period durations (30 min, 1 hour, 3 hours)
  Analyze customer behavior patterns to optimize sending times
  Consider time zone differences for global customer bases
  Implement seasonal timing adjustments for holidays and events

  Content Personalization Enhancement
  Continuously refine AI prompts based on successful recoveries
  Implement dynamic discount strategies based on cart value
  Create customer segment-specific messaging approaches
  Add urgency elements for time-sensitive or limited inventory items

  Performance Measurement
  Track recovery rates, revenue impact, and customer satisfaction
  Implement cohort analysis for long-term customer value impact
  Monitor email engagement metrics and optimize accordingly
  Calculate true ROI including customer acquisition costs and lifetime value

  📈 Success Metrics

  Recovery Performance Indicators
  Recovery Rate**: Percentage of abandoned carts successfully recovered
  Revenue Recovery**: Total dollar amount recovered from abandoned purchases
  Email Engagement**: Open rates, click rates, and conversion rates
  Time to Recovery**: Average time from abandonment to completed purchase

  Business Impact Measurements
  ROI Calculation**: Revenue recovered vs workflow operational costs
  Customer Retention**: Impact on long-term customer relationships
  Average Order Value**: Effect on overall purchase values post-recovery
  Operational Efficiency**: Automation savings vs manual recovery efforts

  📞 Questions & Support

  Need help implementing your AI Cart Recovery Agent?

  📧 E-commerce Automation Expert Support
  Email**: Yaron@nofluff.online
  Response Time**: Within 24 hours on business days
  Specialization**: E-commerce automation, cart recovery optimization, AI email personalization

  🎥 Comprehensive Implementation Resources
  YouTube Channel**: https://www.youtube.com/@YaronBeen/videos
    Complete setup guides for major e-commerce platforms
    Advanced AI email personalization techniques
    Recovery campaign optimization strategies
    Integration tutorials for Shopify, WooCommerce, and custom platforms
    Performance tracking and analytics implementation

  🤝 E-commerce Automation Community
  LinkedIn**: https://www.linkedin.com/in/yaronbeen/
    Connect for ongoing e-commerce automation support and consulting
    Share your cart recovery success stories and ROI achievements
    Access exclusive templates for different industry verticals
    Join discussions about e-commerce automation trends and innovations

  💬 Support Request Guidelines
  Include in your support message:
  Your e-commerce platform and current cart abandonment rates
  Average order values and customer segments you serve
  Current recovery processes and conversion challenges
  Integration requirements with existing marketing tools
  Specific technical errors or workflow execution issues

nodes_used:
  ["n8n-nodes-base.googleSheets","n8n-nodes-base.httpRequest","n8n-nodes-base.gmail","@n8n/n8n-nodes-langchain.agent","@n8n/n8n-nodes-langchain.lmChatOpenAi"]

workflow_json:
  {"meta":{"instanceId":"5aaf4236c70e34e423fbdb2c7b754d19253a933bb1476d548f75848a01e473cf"},"nodes":[{"id":"ecbb99d3-d896-48cc-b6b1-72e178329a3c","name":"Generate Recovery Email","type":"@n8n/n8n-nodes-langchain.agent","position":[100,500],"parameters":{"text":"=Write a friendly and persuasive abandoned cart recovery email for a customer named {{ $json.checkouts[0].customer.first_name }} {{ $json.checkouts[0].customer.last_name }}. The cart contains: {{ $json.checkouts }}. Encourage them to complete their purchase with a subtle reminder and optionally a discount. do not include subject and don't add extra stuff\n","options":{},"promptType":"define"},"typeVersion":1.9},{"id":"0b156bce-50ec-4e56-9c67-be4b34791b3e","name":"Email Writer","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[40,700],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o-mini"},"options":{}},"typeVersion":1.2},{"id":"49b21bce-bece-40a3-b9c0-86e4adc3e167","name":"Log Email Activity","type":"n8n-nodes-base.googleSheets","position":[740,500],"parameters":{"columns":{"value":{"email":"={{ $('Get Initial Abandoned Checkout').item.json.checkouts[0].email }}","customer":"={{ $('Get Initial Abandoned Checkout').item.json.checkouts[0].customer.first_name }} {{ $('Get Initial Abandoned Checkout').item.json.checkouts[0].customer.last_name }}","GPT response":"={{ $('Generate Recovery Email').item.json.output }}"},"schema":[{"id":"customer","type":"string","display":true,"required":false,"displayName":"customer","defaultMatch":false,"canBeUsedToMatch":true},{"id":"email","type":"string","display":true,"required":false,"displayName":"email","defaultMatch":false,"canBeUsedToMatch":true},{"id":"GPT response","type":"string","display":true,"required":false,"displayName":"GPT response","defaultMatch":false,"canBeUsedToMatch":true}],"mappingMode":"defineBelow","matchingColumns":[],"attemptToConvertTypes":false,"convertFieldsToString":false},"options":{},"operation":"append","sheetName":{"__rl":true,"mode":"list","value":"gid=0","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1H83mXsl_gjgwOWrwNYak6ISihoWsgx-EFxSbPlvQx7M/edit#gid=0","cachedResultName":"Sheet1"},"documentId":{"__rl":true,"mode":"list","value":"1H83mXsl_gjgwOWrwNYak6ISihoWsgx-EFxSbPlvQx7M","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1H83mXsl_gjgwOWrwNYak6ISihoWsgx-EFxSbPlvQx7M/edit?usp=drivesdk","cachedResultName":"Shopify abandoned checkout"}},"typeVersion":4.5},{"id":"e55ea939-10fd-423b-99ef-90a89b0effc8","name":"Send Email to Customer","type":"n8n-nodes-base.gmail","position":[520,500],"webhookId":"fb71183d-2a4d-4eca-a73b-225d4cfa4d2d","parameters":{"sendTo":"={{ $('Get Initial Abandoned Checkout').item.json.checkouts[0].email }}","message":"={{ $json.output }}","options":{},"subject":"=You left something behind, {{ $('Get Initial Abandoned Checkout').item.json.checkouts[0].customer.first_name }}"},"typeVersion":2.1},{"id":"b5a6e9ac-6d54-4d6f-bf4d-ced260eecd00","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[-680,400],"parameters":{"color":3,"width":420,"height":520,"content":"🔍 Section 3: Conditional Decision\n5. Is Customer Still Abandoned?\nNode Type: Conditional (If Statement).\n\nLogic: Compares the initial abandoned list with the new one using Customer ID.\n\nOutcome:\n\n✅ Yes – customer is still in the abandoned list → proceed to email.\n\n❌ No – customer has completed checkout → do nothing."},"typeVersion":1},{"id":"5462049f-2c8d-4f94-9475-33b16cbf4074","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[0,0],"parameters":{"color":5,"width":920,"height":840,"content":"📧 Section 4: Recovery Email Flow\n6. Create Personalized Recovery Email\nNode Type: AI Content Generation (GPT-based).\n\nInput: Customer name, product(s) left in cart, etc.\n\nOutput: A personalized recovery email message.\n\nPurpose: Increases the chances of recovery through customized messaging.\n\n7. Send Recovery Email\nNode Type: Email Action (e.g., Gmail, SMTP).\n\nPurpose: Sends the generated email to the customer.\n\n8. Log Email Sent\nNode Type: Spreadsheet Append (Google Sheets, etc.).\n\nPurpose: Logs customer email, customer name and Response.\n\nHelps With: Tracking open rates, click-throughs, and future optimizations."},"typeVersion":1},{"id":"ef86a495-60f4-49c0-a5ca-bbc4b36724b8","name":"Sticky Note9","type":"n8n-nodes-base.stickyNote","position":[-3520,300],"parameters":{"color":4,"width":1300,"height":320,"content":"=======================================\n            WORKFLOW ASSISTANCE\n=======================================\nFor any questions or support, please contact:\n    Yaron@nofluff.online\n\nExplore more tips and tutorials here:\n   - YouTube: https://www.youtube.com/@YaronBeen/videos\n   - LinkedIn: https://www.linkedin.com/in/yaronbeen/\n=======================================\n"},"typeVersion":1},{"id":"0f722fcc-e05a-4b9d-9250-487a049779eb","name":"Sticky Note3","type":"n8n-nodes-base.stickyNote","position":[-3520,640],"parameters":{"color":4,"width":1289,"height":2238,"content":"Here's a full, polished write-up of your **Abandoned Checkout Recovery Workflow** following the format of your **High-Value Order Alert Workflow** example:\n\n---\n\n# 🛒 Abandoned Checkout Recovery Workflow\n\n**Description:**\nThis workflow helps recover lost sales by identifying customers who abandon their checkout process. It begins by fetching abandoned cart data from a store, waits for a specific duration (1 hour), and rechecks to see if the customer has still not completed the purchase. If abandonment persists, the workflow generates a personalized recovery email using AI and sends it to the customer. This increases the chance of conversion and improves overall sales recovery rates.\n\n---\n\n## 🟢 Section 1: Checkout Monitoring & Initial Data Fetch\n\nThe workflow is initiated manually or on a scheduled basis to scan for abandoned checkouts via an API call to the store. This request returns a list of customers who added products to their cart but did not complete the purchase.\n\nThis initial fetch sets the baseline for comparison. The data includes essential customer identifiers and cart details, which will be used later to determine if the customer has recovered on their own.\n\nThis step ensures that the workflow only targets genuine abandonment scenarios and avoids acting on transient or temporary cases.\n\n---\n\n## ⏱️ Section 2: Grace Period Wait\n\nAfter the initial abandoned checkout list is retrieved, the workflow pauses for **1 hour**. This buffer period gives customers time to complete their checkout naturally, without being nudged prematurely.\n\nThis approach respects customer autonomy and avoids sending unnecessary reminders, thereby reducing the risk of annoying users or cluttering inboxes.\n\n---\n\n## 🔄 Section 3: Rechecking Abandonment Status\n\nOnce the wait time has elapsed, the workflow makes a second HTTP request to fetch the latest list of abandoned checkouts. It then uses a conditional check to determine if a particular customer from the initial list still appears in the updated data.\n\n* **If the customer is still present** in the new list, they are considered to still be in an abandoned state.\n* **If the customer is not present**, it is assumed that they completed their purchase and no further action is taken.\n\nThis section acts as a smart filter to prevent sending recovery emails unnecessarily.\n\n---\n\n## ✉️ Section 4: Personalized Recovery Email Flow\n\nIf the customer is confirmed to still have an abandoned cart, the workflow proceeds to engage them with a recovery email.\n\nAn AI email writer generates a **personalized email** based on the abandoned cart data. The message can include specific products, a friendly reminder, and optional incentives such as discounts.\n\nThe email is then sent to the customer via an integrated email service provider. Immediately after, the workflow logs the email activity to a spreadsheet or database for tracking purposes. This helps monitor campaign effectiveness and customer engagement over time.\n\n---\n\n## 🛑 Fallback: Customer Completed Purchase\n\nIf the customer is **not found** in the second check, it means they successfully completed the checkout during the wait period. In this case, the workflow follows a \"do nothing\" path — no email is sent, and the process ends gracefully.\n\nThis fallback mechanism ensures customers aren't contacted unnecessarily, maintaining a respectful user experience.\n\n---\n\n## 🔁 Full Workflow Logic Overview\n\n1. Start the workflow manually or on a schedule.\n2. Fetch a list of current abandoned checkouts.\n3. Wait for 1 hour.\n4. Fetch updated abandoned checkout data.\n5. Compare both datasets:\n\n   * If customer still appears:\n\n     * Use AI to generate a personalized recovery email.\n     * Send the email to the customer.\n     * Log the activity.\n   * If customer no longer appears:\n\n     * End the workflow without taking action.\n\n---\n\nLet me know if you’d like this converted into a PDF or added to a documentation system!\n"},"typeVersion":1},{"id":"7a5fce94-6ae8-43a3-9e45-b15e1d6ecf61","name":"No Operation, do nothing","type":"n8n-nodes-base.noOp","position":[100,1060],"parameters":{},"typeVersion":1},{"id":"e8966160-eb7b-470c-9754-52048cb01551","name":"Start Workflow","type":"n8n-nodes-base.manualTrigger","position":[-1720,720],"parameters":{},"typeVersion":1},{"id":"7ac542e0-5379-4416-a33e-c2ba13947a30","name":"Get Initial Abandoned Checkout","type":"n8n-nodes-base.httpRequest","position":[-1420,720],"parameters":{"url":"https://your-store.myshopify.com/admin/api/2023-10/checkouts.json","options":{},"sendQuery":true,"sendHeaders":true,"queryParameters":{"parameters":[{"name":"status","value":"abandoned"}]},"headerParameters":{"parameters":[{"name":"X-Shopify-Access-Token","value":"your-access-token"}]}},"typeVersion":4.2},{"id":"2409af7c-7df8-4825-b31a-7d2f4bb84a59","name":"Wait 1 Hour","type":"n8n-nodes-base.wait","position":[-1120,720],"webhookId":"12d15136-8aa1-4177-a572-04da4b88b28c","parameters":{"unit":"hours","amount":1},"typeVersion":1.1},{"id":"449c40d4-e1fa-4984-9b3b-c9dd6863e71a","name":"Recheck Abandoned Checkouts","type":"n8n-nodes-base.httpRequest","position":[-900,720],"parameters":{"url":"https://your-store.myshopify.com/admin/api/2023-10/checkouts.json","options":{},"sendQuery":true,"sendHeaders":true,"queryParameters":{"parameters":[{"name":"status","value":"abandoned"}]},"headerParameters":{"parameters":[{"name":"X-Shopify-Access-Token","value":"your-access-token"}]}},"typeVersion":4.2},{"id":"023ea763-155f-4c3c-8c3b-d7de0ef1687a","name":"Is Customer Still Abandoned?","type":"n8n-nodes-base.if","position":[-620,720],"parameters":{"options":{},"conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"or","conditions":[{"id":"8119001f-78d5-40b4-bcd7-8f13495b6d51","operator":{"type":"number","operation":"equals"},"leftValue":"={{ $('Get Initial Abandoned Checkout').item.json.checkouts[0].id }}","rightValue":"={{ $json.checkouts[0].id }}"},{"id":"229cf7e1-5490-4bd0-9004-2baadbe15b4f","operator":{"type":"number","operation":"equals"},"leftValue":"={{ $('Get Initial Abandoned Checkout').item.json.checkouts[0].id }}","rightValue":"={{ $json.checkouts[1].id }}"},{"id":"163c04b1-6e4b-42da-9a5f-2168c4148023","operator":{"type":"number","operation":"equals"},"leftValue":"={{ $('Get Initial Abandoned Checkout').item.json.checkouts[0].id }}","rightValue":"={{ $json.checkouts[2].id }}"},{"id":"42461258-29f4-4dc2-9c34-598654debaa6","operator":{"type":"number","operation":"equals"},"leftValue":"={{ $('Get Initial Abandoned Checkout').item.json.checkouts[0].id }}","rightValue":"={{ $json.checkouts[3].id }}"},{"id":"a0c9d76f-66fc-454b-b59c-990291c85ebf","operator":{"type":"number","operation":"equals"},"leftValue":"={{ $('Get Initial Abandoned Checkout').item.json.checkouts[0].id }}","rightValue":"={{ $json.checkouts[4].id }}"}]}},"typeVersion":2.2},{"id":"c0a92444-8d4d-4eeb-8c8f-7757d90dff2c","name":"Sticky Note4","type":"n8n-nodes-base.stickyNote","position":[-1760,320],"parameters":{"width":520,"height":600,"content":"🔁 Section 1: Initialization & First Abandoned Checkout Fetch\n1. Start Abandoned Checkout Recovery\nPurpose: Triggers the workflow.\n\nTrigger Type: Manual or Scheduled.\n\nWhen: Could be set to run periodically (e.g., every hour).\n\n2. Get Initial Abandoned Checkouts\nNode Type: HTTP Request (GET).\n\nURL: https://your_store.myshopify.com/admin/api/...\n\nPurpose: Fetches the list of all abandoned checkouts at the start of the workflow.\n\nOutput: A list of abandoned carts with customer ID."},"typeVersion":1},{"id":"4748bf2d-732b-48f5-a506-01ab5f5ebbe8","name":"Sticky Note5","type":"n8n-nodes-base.stickyNote","position":[-1180,320],"parameters":{"width":460,"height":600,"content":"⏳ Section 2: Wait and Re-evaluation\n3. Wait 1 Hour\nNode Type: Wait.\n\nDuration: 1 hour.\n\nPurpose: Gives the customer a grace period to complete the checkout naturally before initiating any recovery steps.\n\n4. Recheck Abandoned Checkouts\nNode Type: HTTP Request (GET).\n\nURL: Same as the initial fetch.\n\nPurpose: Fetches the updated list of abandoned checkouts.\n\nOutput: A new list of customer IDs who still haven’t completed their checkout."},"typeVersion":1}],"pinData":{},"connections":{"Wait 1 Hour":{"main":[[{"node":"Recheck Abandoned Checkouts","type":"main","index":0}]]},"Email Writer":{"ai_languageModel":[[{"node":"Generate Recovery Email","type":"ai_languageModel","index":0}]]},"Start Workflow":{"main":[[{"node":"Get Initial Abandoned Checkout","type":"main","index":0}]]},"Send Email to Customer":{"main":[[{"node":"Log Email Activity","type":"main","index":0}]]},"Generate Recovery Email":{"main":[[{"node":"Send Email to Customer","type":"main","index":0}]]},"Recheck Abandoned Checkouts":{"main":[[{"node":"Is Customer Still Abandoned?","type":"main","index":0}]]},"Is Customer Still Abandoned?":{"main":[[{"node":"Generate Recovery Email","type":"main","index":0}],[{"node":"No Operation, do nothing","type":"main","index":0}]]},"Get Initial Abandoned Checkout":{"main":[[{"node":"Wait 1 Hour","type":"main","index":0}]]}}}


name: Anthropic AI Agent: Claude Sonnet 4 and Opus 4 with Think and Web Search tool
author_name: Davide
author_username: n3witalia
categories: []
created_at: 2025-05-26T12:27:34.726Z
updated_at: 2025-05-26T12:27:34.726Z
url: https://n8n.io/workflows/4399
scraped_at: 2025-06-19 22:48:53
description:
  This workflow dynamically chooses between two new powerful Anthropic models — Claude Opus 4 and Claude Sonnet 4 — to handle user queries, based on their complexity and nature, maintaining scalability and context awareness with Anthropic web search function and Think tool.

  Key Advantages

  🔁 Dynamic Model Selection

     Automatically routes each user query to either Claude Sonnet 4 (for routine tasks) or Claude Opus 4 (for complex reasoning), ensuring optimal performance and cost-efficiency.

  🧠 AI Agent with Tool Use

     The AI agent can utilize a web search tool to retrieve up-to-date information and a Think tool for complex reasoning processes — improving response quality.

  📎 Memory Integration

     Uses session-based memory to maintain conversational context, making interactions more coherent and human-like.

  🧮 Built-in Calculation Tool

     Handles numeric queries using an integrated calculator tool, reducing the need for external processing.

  📤 Structured Output Parser

     Ensures outputs are always well-structured and formatted in JSON, which improves consistency and downstream integrations.

  🌐 Web Search Capability

     Supports real-time information retrieval for current events, statistics, or details not available in the AI’s base knowledge.

  Components Overview

  Trigger**: Listens for new chat messages.
  Routing Agent**: Analyzes the message and returns the best model to use.
  AI Agent**: Handles the conversation, decides when to use tools.
  Tools**:

    web_search for internet queries
    Think for reasoning
    Calculator for math tasks
  Models Used**:

    claude-sonnet-4-20250514: Optimized for general and business logic tasks.
    claude-opus-4-20250514: Best for deep, strategic, and analytical queries.

  How It Works
  Dynamic Model Selection  
     The workflow begins when a chat message is received. The Anthropic Routing Agent analyzes the user's query to determine the most suitable model (either Claude Sonnet 4 or Claude Opus 4) based on the query's complexity and requirements.  
     The routing agent uses predefined criteria to decide:  
       Claude Sonnet 4: Best for standard tasks like real-time workflow routing, data validation, and routine business logic.  
       Claude Opus 4: Reserved for complex scenarios requiring deep reasoning, advanced analysis, or high-impact decisions.  

  Query Processing and Response Generation  
     The selected model processes the query, leveraging tools like web_search for real-time information retrieval, Think for internal reasoning, and Calculator for numerical tasks.  
     The AI Agent coordinates these tools, ensuring the response is accurate and context-aware. A Simple Memory node retains session context for coherent multi-turn conversations.  
     The final response is formatted and returned to the user without intermediate steps or metadata.  

  Set Up Steps
  Node Configuration  
     Trigger: Configure the "When chat message received" node to handle incoming user queries.  
     Routing Agent: Set up the "Anthropic Routing Agent" with the system message defining model selection logic. Ensure it outputs a JSON object with prompt and model fields.  
     AI Model Nodes: Link the "Sonnet 4 or Opus 4" node to dynamically use the selected model. The "Sonnet 3.7" node powers the routing agent itself.  

  Tool Integration  
     Attach the "web_search" HTTP tool to enable internet searches, ensuring the API endpoint and headers (e.g., anthropic-version) are correctly configured.  
     Connect auxiliary tools (Think, Calculator) to the "AI Agent" for extended functionality.  
     Add the "Simple Memory" node to maintain conversation history.  

  Credentials  
     Provide an Anthropic API key to all nodes requiring authentication (e.g., model nodes, web search).  

  Testing  
     Activate the workflow and test with sample queries to verify:  
       Correct model selection (e.g., Sonnet for simple queries, Opus for complex ones).  
       Proper tool usage (e.g., web searches trigger when needed).  
       Memory retention across chat turns.  

  Deployment  
     Once validated, set the workflow to active for live interactions.  

  Need help customizing?  
  Contact me for consulting and support or add me on Linkedin. 

nodes_used:
  ["@n8n/n8n-nodes-langchain.agent","@n8n/n8n-nodes-langchain.lmChatAnthropic","@n8n/n8n-nodes-langchain.memoryBufferWindow","@n8n/n8n-nodes-langchain.outputParserStructured","@n8n/n8n-nodes-langchain.toolCalculator","@n8n/n8n-nodes-langchain.toolThink"]

workflow_json:
  {"id":"qjLD1os0l5ISHRFO","meta":{"instanceId":"a4bfc93e975ca233ac45ed7c9227d84cf5a2329310525917adaf3312e10d5462","templateCredsSetupCompleted":true},"name":"Agent AI Anthropic Opus 4 and Sonnet 4","tags":[],"nodes":[{"id":"4f01cd9b-16b6-4b6a-a55b-64531e867dcc","name":"When chat message received","type":"@n8n/n8n-nodes-langchain.chatTrigger","position":[20,60],"webhookId":"a0032740-26d8-491b-93f9-2250906d0e17","parameters":{"options":{}},"typeVersion":1.1},{"id":"c0a5e6b1-9c43-4f92-884e-95b1e91ff54a","name":"Structured Output Parser","type":"@n8n/n8n-nodes-langchain.outputParserStructured","position":[420,280],"parameters":{"schemaType":"manual","inputSchema":"{\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"prompt\": {\n\t\t\t\"type\": \"string\"\n\t\t},\n\t\t\"model\": {\n\t\t\t\"type\": \"string\"\n\t\t}\n\t}\n}"},"typeVersion":1.2},{"id":"e46a6a64-8875-44f0-830e-febebaa10dd7","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[20,-180],"parameters":{"width":840,"height":180,"content":"## Dynamic Model Selector for Optimal AI Responses\n\nThe **New Anthropic Agent Decisioner** is a dynamic, AI-powered routing system that automatically selects the most appropriate large language model (Anthropic Sonnet 4 or Opus 4) to respond to a user's query based on the query’s content and purpose.\n\nThis workflow ensures **dynamic, optimized AI responses** by intelligently routing queries to the best-suited model."},"typeVersion":1},{"id":"0f4208aa-c4f5-44aa-ba43-4c3143751a79","name":"AI Agent","type":"@n8n/n8n-nodes-langchain.agent","position":[600,60],"parameters":{"text":"={{ $json.output.prompt }}","options":{"systemMessage":"=You have access to a web_search tool that allows you to browse the internet for up-to-date information. Here's how you should operate:\n\n1. Website Information:\nFamiliarize yourself with this information about the website you're assisting. Use this as context for user interactions.\n\n2. Web Search Tool:\nYou have access to a web_search tool that can browse the internet. To use it, write the variable {web_search_question}. The tool will return relevant search results. Set the variable {model} to {{ $json.output.model }}.\n\n3. Handling User Queries:\nWhen a user asks a question, follow these steps:\na) Analyze the query to determine if it's related to the website or requires external information.\nb) If the query is about the website, use the provided website information to answer.\nc) If external information is needed, use the web_search tool to find relevant data.\n\n4. Using web_search:\n- Use web_search for factual, current information that isn't provided in the website info.\n- Formulate clear, concise search queries.\n- If the first search doesn't yield useful results, refine your query and search again.\n- Limit searches to a maximum of three per user query to maintain efficiency.\n\n5. Using Think:\n- Using Think tool to think about something. It will not obtain new information or change the database, but just append the thought to the log. Use it when complex reasoning or some cache memory is needed.\n\n6. Formulating Responses:\n- Begin with information from the website if relevant.\n- Incorporate web search results to provide up-to-date, accurate information.\n- Summarize findings concisely and coherently.\n- If you're unsure or can't find reliable information, be honest about limitations.\n\n7. Ethical Considerations:\n- Respect user privacy. Don't ask for or store personal information.\n- Provide factual information. Avoid speculation or unverified claims.\n- If asked about controversial topics, strive for a balanced, neutral response.\n- Don't engage in or encourage illegal activities.\n\n8. Output Format:\nDo not include your thought process, web searches, or any other tags in the final output.\n"},"promptType":"define"},"typeVersion":1.9},{"id":"0e08600f-f35c-408a-9b8a-f886aeea37d6","name":"Think","type":"@n8n/n8n-nodes-langchain.toolThink","position":[800,280],"parameters":{},"typeVersion":1},{"id":"5adf09be-e278-49f0-bb66-d7e3d265b120","name":"Calculator","type":"@n8n/n8n-nodes-langchain.toolCalculator","position":[900,280],"parameters":{},"typeVersion":1},{"id":"d5fa04bf-e40b-41d7-9d48-c71cd7ced93f","name":"Anthropic Routing Agent","type":"@n8n/n8n-nodes-langchain.agent","position":[240,60],"parameters":{"options":{"systemMessage":"=You are a **Routing Agent**.\n\nYour task is to analyze user queries and determine the most appropriate model to handle each specific use case.\n\n## Available Models\n\nYou have access to the following models:\n\n1. **claude-sonnet-4-20250514**\n2. **claude-opus-4-20250514**\n\n## Model Strengths\n\n### 1. claude-sonnet-4-20250514\n- Standard decision-making tasks\n- Real-time workflow routing\n- Data validation and processing\n- Pattern recognition in structured data\n- Routine business logic evaluation\n\n### 2. claude-sonnet-4-20250514\n- Complex multi-factor decision scenarios\n- Advanced data analysis requiring deep reasoning\n- Critical business decisions with high impact\n- Complex pattern recognition in unstructured data\n- Strategic workflow optimization\n\n## Output Format\n\nYour output must always be a valid JSON object in the following format:\n\n```json\n{\n  \"prompt\": \"user query goes here\",\n  \"model\": \"selected-model-name\"\n}\n```\n\n- The **\"prompt\"** field should contain the exact query to be sent to the selected model.\n- The **\"model\"** field should contain the model name (one of: claude-sonnet-4-20250514, claude-opus-4-20250514).\n\n**Important:** Only return the JSON object. Do not include any explanations or additional text."},"hasOutputParser":true},"typeVersion":1.9},{"id":"0f358356-37d4-4693-a694-382a8bc1b20f","name":"Sonnet 4 or Opus 4","type":"@n8n/n8n-nodes-langchain.lmChatAnthropic","position":[600,280],"parameters":{"model":{"__rl":true,"mode":"id","value":"={{ $json.output.model }}"},"options":{}},"credentials":{"anthropicApi":{"id":"NNTZAD0Gmf7lcniq","name":"Anthropic account"}},"typeVersion":1.3},{"id":"c92104a6-9aa4-4a55-84b1-484df25f83ac","name":"Sonnet 3.7","type":"@n8n/n8n-nodes-langchain.lmChatAnthropic","position":[220,280],"parameters":{"model":{"__rl":true,"mode":"list","value":"claude-3-7-sonnet-20250219","cachedResultName":"Claude Sonnet 3.7"},"options":{"maxTokensToSample":1024}},"credentials":{"anthropicApi":{"id":"NNTZAD0Gmf7lcniq","name":"Anthropic account"}},"typeVersion":1.3},{"id":"513642ef-b4d6-46fc-8542-319dd54271f8","name":"Simple Memory1","type":"@n8n/n8n-nodes-langchain.memoryBufferWindow","position":[720,280],"parameters":{"sessionKey":"={{ $('When chat message received').item.json.sessionId }}","sessionIdType":"customKey"},"typeVersion":1.3},{"id":"6c81dcd9-7faf-4b34-8e78-a471de80fa1e","name":"web_search","type":"n8n-nodes-base.httpRequestTool","position":[1020,280],"parameters":{"url":"https://api.anthropic.com/v1/messages","method":"POST","options":{},"jsonBody":"={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('JSON', `{\n  \"model\": \"{model}\",\n  \"max_tokens\": 1024,\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"{web_search_question}\"\n    }\n  ],\n  \"tools\": [\n    {\n      \"type\": \"web_search_20250305\",\n      \"name\": \"web_search\",\n      \"max_uses\": 5\n    }\n  ]\n}\n`, 'json') }}","sendBody":true,"sendHeaders":true,"specifyBody":"json","authentication":"predefinedCredentialType","toolDescription":"Use this tool to search on the web","headerParameters":{"parameters":[{"name":"anthropic-version","value":"=2023-06-01"},{"name":"content-type","value":"application/json"}]},"nodeCredentialType":"anthropicApi"},"credentials":{"anthropicApi":{"id":"NNTZAD0Gmf7lcniq","name":"Anthropic account"}},"typeVersion":4.2}],"active":false,"pinData":{},"settings":{"executionOrder":"v1"},"versionId":"c0947a41-be77-4ac0-89e2-eb8cf04b7c48","connections":{"Think":{"ai_tool":[[{"node":"AI Agent","type":"ai_tool","index":0}]]},"Calculator":{"ai_tool":[[{"node":"AI Agent","type":"ai_tool","index":0}]]},"Sonnet 3.7":{"ai_languageModel":[[{"node":"Anthropic Routing Agent","type":"ai_languageModel","index":0}]]},"web_search":{"ai_tool":[[{"node":"AI Agent","type":"ai_tool","index":0}]]},"Simple Memory1":{"ai_memory":[[{"node":"AI Agent","type":"ai_memory","index":0}]]},"Sonnet 4 or Opus 4":{"ai_languageModel":[[{"node":"AI Agent","type":"ai_languageModel","index":0}]]},"Anthropic Routing Agent":{"main":[[{"node":"AI Agent","type":"main","index":0}]]},"Structured Output Parser":{"ai_outputParser":[[{"node":"Anthropic Routing Agent","type":"ai_outputParser","index":0}]]},"When chat message received":{"main":[[{"node":"Anthropic Routing Agent","type":"main","index":0}]]}}}


name: Build a PDF Document RAG System with Mistral OCR, Qdrant and Gemini AI
author_name: Davide
author_username: n3witalia
categories: []
created_at: 2025-05-26T12:28:14.350Z
updated_at: 2025-05-26T12:28:14.350Z
url: https://n8n.io/workflows/4400
scraped_at: 2025-06-19 22:48:40
description:
  This workflow is designed to process PDF documents using Mistral's OCR capabilities, store the extracted text in a Qdrant vector database, and enable Retrieval-Augmented Generation (RAG) for answering questions. Here’s how it functions:  

  Once configured, the workflow automates document ingestion, vectorization, and intelligent querying, enabling powerful RAG applications.

  Benefits

  End-to-End Automation**
    No manual interaction is needed: documents are read, processed, and made queryable with minimal setup.

  Scalable and Modular**
    The workflow uses subflows and batching, making it easy to scale and customize.

  Multi-Model Support**
    Combines Mistral for OCR, OpenAI for embeddings, and Gemini for intelligent answering—taking advantage of the strengths of each.

  Real-Time Q\&A**
    With RAG integration, users can query document content through natural language and receive accurate responses grounded in the PDF data.

  Light or Full Mode**
    Users can choose to index full page content or only summarized text, optimizing for either performance or richness.

  How It Works 

  PDF Processing with Mistral OCR:  
     The workflow starts by uploading a PDF file to Mistral's API, which performs OCR to extract text and metadata.  
     The extracted content is split into manageable chunks (e.g., pages or sections) for further processing.  

  Vector Storage in Qdrant:  
     The extracted text is converted into embeddings using OpenAI's embedding model.  
     These embeddings are stored in a Qdrant vector database, enabling efficient similarity searches for RAG.  

  Question-Answering with RAG:  
     When a user submits a question via a chat interface, the workflow retrieves relevant text chunks from Qdrant using vector similarity.  
     A language model (Google Gemini) generates answers based on the retrieved context, providing accurate and context-aware responses.  

  Optional Summarization:  
     The workflow includes an optional summarization step using Google Gemini to condense the extracted text for faster processing or lighter RAG usage.  

  Set Up Steps  
  To deploy this workflow in n8n, follow these steps:  

  Configure Qdrant Database:  
     Replace QDRANTURL and COLLECTION in the "Create collection" and "Refresh collection" nodes with your Qdrant instance details.  
     Ensure the Qdrant collection is configured with the correct vector size (e.g., 1536 for OpenAI embeddings) and distance metric (e.g., Cosine).  

  Set Up Credentials:  
     Add credentials for:  
       Mistral Cloud API (for OCR processing).  
       OpenAI API (for embeddings).  
       Google Gemini API (for chat and summarization).  
       Google Drive (if sourcing PDFs from Drive).  
       Qdrant API (for vector storage).  

  PDF Source Configuration:  
     If using Google Drive, specify the folder ID in the "Search PDFs" node.  
     Alternatively, modify the workflow to accept PDFs from other sources (e.g., direct uploads or external APIs).  

  Customize Text Processing:  
     Adjust chunk size and overlap in the "Token Splitter" node to optimize for your document type.  
     Choose between raw text or summarized content for RAG by toggling between the "Set page" and "Summarization Chain" nodes.  

  Test the RAG:  
     Trigger the workflow manually or via a chat message to verify OCR, embedding, and Qdrant storage.  
     Use the "Question and Answer Chain" node to test query responses.  

  Optional Sub-Workflows:  
     The workflow supports execution as a sub-workflow for batch processing (e.g., handling multiple PDFs).  

  Need help customizing?  
  Contact me for consulting and support or add me on Linkedin. 

nodes_used:
  ["n8n-nodes-base.httpRequest","n8n-nodes-base.googleDrive","n8n-nodes-base.code","@n8n/n8n-nodes-langchain.chainSummarization","@n8n/n8n-nodes-langchain.chainRetrievalQa","@n8n/n8n-nodes-langchain.embeddingsOpenAi","@n8n/n8n-nodes-langchain.retrieverVectorStore","@n8n/n8n-nodes-langchain.textSplitterTokenSplitter","@n8n/n8n-nodes-langchain.documentDefaultDataLoader","@n8n/n8n-nodes-langchain.vectorStoreQdrant","@n8n/n8n-nodes-langchain.lmChatGoogleGemini"]

workflow_json:
  {"id":"IwtOfHq5pZQNDAF0","meta":{"instanceId":"a4bfc93e975ca233ac45ed7c9227d84cf5a2329310525917adaf3312e10d5462","templateCredsSetupCompleted":true},"name":"Complete RAG from PDF with Mistral OCR","tags":[],"nodes":[{"id":"01a1b5b8-353f-4bfe-8bd0-c5dff1214c86","name":"Mistral Upload","type":"n8n-nodes-base.httpRequest","position":[180,520],"parameters":{"url":"https://api.mistral.ai/v1/files","method":"POST","options":{},"sendBody":true,"contentType":"multipart-form-data","authentication":"predefinedCredentialType","bodyParameters":{"parameters":[{"name":"purpose","value":"ocr"},{"name":"file","parameterType":"formBinaryData","inputDataFieldName":"data"}]},"nodeCredentialType":"mistralCloudApi"},"credentials":{"mistralCloudApi":{"id":"FydnNvrpqnG0B7ee","name":"Mistral Cloud account"}},"typeVersion":4.2},{"id":"45267068-bdbc-45d3-bfe9-354cad73285b","name":"Mistral Signed URL","type":"n8n-nodes-base.httpRequest","position":[500,520],"parameters":{"url":"=https://api.mistral.ai/v1/files/{{ $json.id }}/url","options":{},"sendQuery":true,"sendHeaders":true,"authentication":"predefinedCredentialType","queryParameters":{"parameters":[{"name":"expiry","value":"24"}]},"headerParameters":{"parameters":[{"name":"Accept","value":"application/json"}]},"nodeCredentialType":"mistralCloudApi"},"credentials":{"mistralCloudApi":{"id":"FydnNvrpqnG0B7ee","name":"Mistral Cloud account"}},"typeVersion":4.2},{"id":"61416fe4-d5d9-4417-9142-461dd6a45fa4","name":"Mistral DOC OCR","type":"n8n-nodes-base.httpRequest","position":[820,520],"parameters":{"url":"https://api.mistral.ai/v1/ocr","method":"POST","options":{},"jsonBody":"={\n  \"model\": \"mistral-ocr-latest\",\n  \"document\": {\n    \"type\": \"document_url\",\n    \"document_url\": \"{{ $json.url }}\"\n  },\n  \"include_image_base64\": true\n}","sendBody":true,"specifyBody":"json","authentication":"predefinedCredentialType","nodeCredentialType":"mistralCloudApi"},"credentials":{"mistralCloudApi":{"id":"FydnNvrpqnG0B7ee","name":"Mistral Cloud account"}},"typeVersion":4.2},{"id":"c45ea050-c65b-48b2-b817-d651c3a0de8a","name":"When clicking ‘Test workflow’","type":"n8n-nodes-base.manualTrigger","position":[-480,-300],"parameters":{},"typeVersion":1},{"id":"db931c73-916e-48ce-af17-cd5ab2e7c64d","name":"Loop Over Items","type":"n8n-nodes-base.splitInBatches","position":[1540,520],"parameters":{"options":{}},"typeVersion":3},{"id":"76daea49-34f2-4567-8547-4b3d89ce921c","name":"Refresh collection","type":"n8n-nodes-base.httpRequest","position":[-140,-300],"parameters":{"url":"http://QDRANTURL/collections/COLLECTION/points/delete","method":"POST","options":{},"jsonBody":"{\n  \"filter\": {}\n}","sendBody":true,"sendHeaders":true,"specifyBody":"json","authentication":"genericCredentialType","genericAuthType":"httpHeaderAuth","headerParameters":{"parameters":[{"name":"Content-Type","value":"application/json"}]}},"credentials":{"httpHeaderAuth":{"id":"qhny6r5ql9wwotpn","name":"Qdrant API (Hetzner)"}},"typeVersion":4.2},{"id":"ac7c469e-d0e8-4146-b323-f3948c3331fa","name":"Embeddings OpenAI","type":"@n8n/n8n-nodes-langchain.embeddingsOpenAi","position":[2320,800],"parameters":{"options":{"stripNewLines":false}},"credentials":{"openAiApi":{"id":"4zwP0MSr8zkNvvV9","name":"OpenAi account"}},"typeVersion":1.1},{"id":"67591961-ef29-4bef-9905-8be18d5e9814","name":"Default Data Loader","type":"@n8n/n8n-nodes-langchain.documentDefaultDataLoader","position":[2460,760],"parameters":{"options":{}},"typeVersion":1},{"id":"54c38164-6492-42d6-8b44-e10bbfdcd807","name":"Token Splitter","type":"@n8n/n8n-nodes-langchain.textSplitterTokenSplitter","position":[2560,940],"parameters":{"chunkSize":400,"chunkOverlap":40},"typeVersion":1},{"id":"661137fc-7afa-49a8-900c-a8c7fd63f557","name":"When chat message received","type":"@n8n/n8n-nodes-langchain.chatTrigger","position":[-480,960],"webhookId":"97d60090-1717-4195-bf27-2e3c3105b7f8","parameters":{"options":{}},"typeVersion":1.1},{"id":"fe971655-b323-4ccf-a6c5-764d7cc3d8bc","name":"Question and Answer Chain","type":"@n8n/n8n-nodes-langchain.chainRetrievalQa","position":[-160,960],"parameters":{"options":{}},"typeVersion":1.5},{"id":"8806cf11-83e8-4c75-ba96-71a62d1fb632","name":"Google Gemini Chat Model","type":"@n8n/n8n-nodes-langchain.lmChatGoogleGemini","position":[-220,1160],"parameters":{"options":{},"modelName":"models/gemini-1.5-flash"},"credentials":{"googlePalmApi":{"id":"0p34rXqIqy8WuoPg","name":"Google Gemini(PaLM) Api account"}},"typeVersion":1},{"id":"8012569d-5e29-4f36-89be-394ac4928194","name":"Vector Store Retriever","type":"@n8n/n8n-nodes-langchain.retrieverVectorStore","position":[0,1180],"parameters":{},"typeVersion":1},{"id":"f33e13dd-2465-4971-bcbf-d2d9461f5453","name":"Qdrant Vector Store1","type":"@n8n/n8n-nodes-langchain.vectorStoreQdrant","position":[20,1380],"parameters":{"options":{},"qdrantCollection":{"__rl":true,"mode":"list","value":"ocr_mistral_test","cachedResultName":"ocr_mistral_test"}},"credentials":{"qdrantApi":{"id":"iyQ6MQiVaF3VMBmt","name":"QdrantApi account (Hetzner)"}},"typeVersion":1.1},{"id":"f864b8c1-8b4f-4116-812a-843aea0347ac","name":"Embeddings OpenAI1","type":"@n8n/n8n-nodes-langchain.embeddingsOpenAi","position":[-100,1520],"parameters":{"options":{}},"credentials":{"openAiApi":{"id":"4zwP0MSr8zkNvvV9","name":"OpenAi account"}},"typeVersion":1.2},{"id":"48799279-d580-4c3f-ab39-e2da1bf1d577","name":"Code","type":"n8n-nodes-base.code","position":[1140,520],"parameters":{"jsCode":"const data = $json.pages;\n\nreturn data.map(entry => ({\n  json: {\n    markdown: entry.markdown\n  }\n}));"},"typeVersion":2},{"id":"5c68cd54-3841-46e0-9b2e-05a1188e92c0","name":"Wait","type":"n8n-nodes-base.wait","position":[2860,540],"webhookId":"1000b40d-5dc5-4795-9dd2-8a23653c2b49","parameters":{},"typeVersion":1.1},{"id":"0853153e-33a3-44a8-ab22-c296b7aab892","name":"Qdrant Vector Store","type":"@n8n/n8n-nodes-langchain.vectorStoreQdrant","position":[2380,540],"parameters":{"mode":"insert","options":{"collectionConfig":""},"qdrantCollection":{"__rl":true,"mode":"list","value":"ocr_mistral_test","cachedResultName":"ocr_mistral_test"}},"credentials":{"qdrantApi":{"id":"iyQ6MQiVaF3VMBmt","name":"QdrantApi account (Hetzner)"}},"typeVersion":1.1},{"id":"4123fa10-ec36-40cd-ad85-b8353479db28","name":"Loop Over Items1","type":"n8n-nodes-base.splitInBatches","position":[540,-300],"parameters":{"options":{}},"typeVersion":3},{"id":"16fadeb2-5612-421e-8da3-37bed966d966","name":"Execute Workflow","type":"n8n-nodes-base.executeWorkflow","position":[1160,-280],"parameters":{"mode":"each","options":{"waitForSubWorkflow":true},"workflowId":{"__rl":true,"mode":"list","value":"AdVUaHTE9Jk1KO72","cachedResultName":"Mistral OCR_subworkflow"},"workflowInputs":{"value":{},"schema":[],"mappingMode":"defineBelow","matchingColumns":[],"attemptToConvertTypes":false,"convertFieldsToString":true}},"typeVersion":1.2},{"id":"0f61b1ab-45a3-4167-a4f1-baeca03109bd","name":"When Executed by Another Workflow","type":"n8n-nodes-base.executeWorkflowTrigger","position":[-460,520],"parameters":{"inputSource":"passthrough"},"typeVersion":1.1},{"id":"034fc82c-b13a-4e72-ae86-97676d5b8867","name":"Edit Fields1","type":"n8n-nodes-base.set","position":[860,-280],"parameters":{"options":{},"assignments":{"assignments":[{"id":"ca7c30f2-444d-4551-988d-0f513e5ee4b1","name":"file_id","type":"string","value":"={{ $json.id }}"}]}},"typeVersion":3.4},{"id":"0c5d144c-77de-4d3b-a30b-3674ea858f3e","name":"Create collection","type":"n8n-nodes-base.httpRequest","position":[-480,-760],"parameters":{"url":"http://QDRANTURL/collections/COLLECTION","method":"PUT","options":{},"jsonBody":"{\n  \"vectors\": {\n    \"size\": 1536,\n    \"distance\": \"Cosine\"  \n  },\n  \"shard_number\": 1,  \n  \"replication_factor\": 1,  \n  \"write_consistency_factor\": 1 \n}","sendBody":true,"sendHeaders":true,"specifyBody":"json","authentication":"genericCredentialType","genericAuthType":"httpHeaderAuth","headerParameters":{"parameters":[{"name":"Content-Type","value":"application/json"}]}},"credentials":{"httpHeaderAuth":{"id":"qhny6r5ql9wwotpn","name":"Qdrant API (Hetzner)"}},"typeVersion":4.2},{"id":"5dab4a20-0daa-43f2-8878-eae8720aa50f","name":"Sticky Note3","type":"n8n-nodes-base.stickyNote","position":[-280,-820],"parameters":{"color":6,"width":880,"height":220,"content":"# STEP 1\n\n## Create Qdrant Collection\nChange:\n- QDRANTURL\n- COLLECTION"},"typeVersion":1},{"id":"b78c160a-0e73-4fa0-9015-d8b2a249fd33","name":"Sticky Note4","type":"n8n-nodes-base.stickyNote","position":[-540,-400],"parameters":{"color":4,"width":620,"height":520,"content":"# STEP 2\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n## Documents vectorization with Qdrant and Google Drive\nChange:\n- QDRANTURL\n- COLLECTION"},"typeVersion":1},{"id":"8988f19e-259b-4e01-833a-f8ed2f89c7d6","name":"Summarization Chain","type":"@n8n/n8n-nodes-langchain.chainSummarization","position":[1820,140],"parameters":{"options":{"summarizationMethodAndPrompts":{"values":{"prompt":"Write a concise summary of the following (in italiano):\n\n\n\"{text}\"\n\n\nCONCISE SUMMARY:","combineMapPrompt":"Write a concise summary of the following (in italiano):\n\n\n\"{text}\"\n\n\nCONCISE SUMMARY:"}}}},"typeVersion":2},{"id":"b7581380-5431-42f1-b4de-279faf4bdf16","name":"Google Gemini Chat Model1","type":"@n8n/n8n-nodes-langchain.lmChatGoogleGemini","position":[1840,320],"parameters":{"options":{},"modelName":"models/gemini-2.0-flash-exp"},"credentials":{"googlePalmApi":{"id":"0p34rXqIqy8WuoPg","name":"Google Gemini(PaLM) Api account"}},"typeVersion":1},{"id":"037896c0-7561-4ca1-9130-adc1175408b5","name":"Set page","type":"n8n-nodes-base.set","position":[2000,540],"parameters":{"options":{},"assignments":{"assignments":[{"id":"189f4944-a692-423c-bc6d-76747e1d04df","name":"text","type":"string","value":"={{ $json.markdown }}"}]}},"typeVersion":3.4},{"id":"06444ac1-382a-41df-8ff7-a1a5fea9e6ec","name":"Set summary","type":"n8n-nodes-base.set","position":[2180,140],"parameters":{"options":{},"assignments":{"assignments":[{"id":"189f4944-a692-423c-bc6d-76747e1d04df","name":"text","type":"string","value":"={{ $json.response.text }}"}]}},"typeVersion":3.4},{"id":"00bd51e2-a969-415a-9fca-f67bf9df96dc","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[1760,20],"parameters":{"width":600,"height":680,"content":"## STEP 3\nIf you want a \"light\" and faster rag with the main contents replace the \"Set page\" node with \"Summarization Chain\""},"typeVersion":1},{"id":"da71f8f9-bff9-48e1-b2e4-9fbbe7ac8924","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[320,960],"parameters":{"color":2,"width":500,"height":120,"content":"## STEP 4\nTest the RAG"},"typeVersion":1},{"id":"b0c57120-6b07-4823-9341-c3f42ca313f5","name":"Search PDFs","type":"n8n-nodes-base.googleDrive","position":[200,-300],"parameters":{"filter":{"folderId":{"__rl":true,"mode":"list","value":"1LWVo3yn_1bWQJsLskBIbWTGwlfObvtUK","cachedResultUrl":"https://drive.google.com/drive/folders/1LWVo3yn_1bWQJsLskBIbWTGwlfObvtUK","cachedResultName":"PDFs"}},"options":{},"resource":"fileFolder"},"credentials":{"googleDriveOAuth2Api":{"id":"HEy5EuZkgPZVEa9w","name":"Google Drive account (n3w.it)"}},"typeVersion":3},{"id":"26990fbc-3315-42d5-948d-3b670e7d4f84","name":"Get PDF","type":"n8n-nodes-base.googleDrive","position":[-140,520],"parameters":{"fileId":{"__rl":true,"mode":"id","value":"={{ $json.file_id }}"},"options":{},"operation":"download"},"credentials":{"googleDriveOAuth2Api":{"id":"HEy5EuZkgPZVEa9w","name":"Google Drive account (n3w.it)"}},"typeVersion":3},{"id":"013e49fe-7ee2-4d24-b640-dda63fa034b3","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[-540,-1080],"parameters":{"width":1140,"height":140,"content":"## Complete RAG system from PDF Documents with Mistral OCR, Qdrant and Gemini AI\n\nThis workflow is designed to process PDF documents using Mistral's OCR capabilities, store the extracted text in a Qdrant vector database, and enable Retrieval-Augmented Generation (RAG) for answering questions. "},"typeVersion":1}],"active":false,"pinData":{},"settings":{"executionOrder":"v1"},"versionId":"45bfd9c5-ea80-49f9-bc3a-d2719a16b363","connections":{"Code":{"main":[[{"node":"Loop Over Items","type":"main","index":0}]]},"Wait":{"main":[[{"node":"Loop Over Items","type":"main","index":0}]]},"Get PDF":{"main":[[{"node":"Mistral Upload","type":"main","index":0}]]},"Set page":{"main":[[{"node":"Qdrant Vector Store","type":"main","index":0}]]},"Search PDFs":{"main":[[{"node":"Loop Over Items1","type":"main","index":0}]]},"Edit Fields1":{"main":[[{"node":"Execute Workflow","type":"main","index":0}]]},"Mistral Upload":{"main":[[{"node":"Mistral Signed URL","type":"main","index":0}]]},"Token Splitter":{"ai_textSplitter":[[{"node":"Default Data Loader","type":"ai_textSplitter","index":0}]]},"Loop Over Items":{"main":[[],[{"node":"Set page","type":"main","index":0}]]},"Mistral DOC OCR":{"main":[[{"node":"Code","type":"main","index":0}]]},"Execute Workflow":{"main":[[{"node":"Loop Over Items1","type":"main","index":0}]]},"Loop Over Items1":{"main":[[],[{"node":"Edit Fields1","type":"main","index":0}]]},"Embeddings OpenAI":{"ai_embedding":[[{"node":"Qdrant Vector Store","type":"ai_embedding","index":0}]]},"Embeddings OpenAI1":{"ai_embedding":[[{"node":"Qdrant Vector Store1","type":"ai_embedding","index":0}]]},"Mistral Signed URL":{"main":[[{"node":"Mistral DOC OCR","type":"main","index":0}]]},"Refresh collection":{"main":[[{"node":"Search PDFs","type":"main","index":0}]]},"Default Data Loader":{"ai_document":[[{"node":"Qdrant Vector Store","type":"ai_document","index":0}]]},"Qdrant Vector Store":{"main":[[{"node":"Wait","type":"main","index":0}]]},"Summarization Chain":{"main":[[{"node":"Set summary","type":"main","index":0}]]},"Qdrant Vector Store1":{"ai_vectorStore":[[{"node":"Vector Store Retriever","type":"ai_vectorStore","index":0}]]},"Vector Store Retriever":{"ai_retriever":[[{"node":"Question and Answer Chain","type":"ai_retriever","index":0}]]},"Google Gemini Chat Model":{"ai_languageModel":[[{"node":"Question and Answer Chain","type":"ai_languageModel","index":0}]]},"Google Gemini Chat Model1":{"ai_languageModel":[[{"node":"Summarization Chain","type":"ai_languageModel","index":0}]]},"When chat message received":{"main":[[{"node":"Question and Answer Chain","type":"main","index":0}]]},"When Executed by Another Workflow":{"main":[[{"node":"Get PDF","type":"main","index":0}]]},"When clicking ‘Test workflow’":{"main":[[{"node":"Refresh collection","type":"main","index":0}]]}}}


