# templates

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-07-06 21:16:30
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-07-06 21:16:30
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,"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-07-06 21:16:30
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,"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: 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-07-06 21:16:30
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}],"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: 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-07-06 21:16:30
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}],"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: 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-07-06 21:16:30
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,"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-07-06 21:16:30
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,"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}]]}}}


name: AI Chatbot Agent with a Panel of Experts using InfraNodus GraphRAG Knowledge
author_name: InfraNodus
author_username: infranodus
categories: []
created_at: 2025-05-26T12:34:52.632Z
updated_at: 2025-05-26T12:34:52.632Z
url: https://n8n.io/workflows/4402
scraped_at: 2025-07-06 21:16:30
description:
  Using the knowledge graphs instead of RAG vector stores

  This workflow creates an AI chatbot agent that has access to several knowledge bases at the same time (used as "experts"). 

  These knowledge bases are provided using the InfraNodus GraphRAG using the knowledge graphs and providing high-quality responses without the need to set up complex RAG vector store workflows.

  The advantages of using GraphRAG instead of the standard vector stores for knowledge are:

  Easy and quick to set up (no complex data import workflows needed)
  A knowledge graph has a holistic view of your knowledge base
  Better retrieval of relations between the document chunks = higher quality responses

  How it works
  This template uses the n8n AI agent node as an orchestrating agent that decides which tool (knowledge graph) to use based on the user's prompt. 

  Here's a description step by step:

  The user submits a question using the AI chatbot (n8n interface, in this case, which can be accessed via a URL or embedded to any website)
  The AI agent node checks a list of tools it has access to. Each tool has a description of the knowledge it has auto-generated by InfraNodus. 
  The AI agent decides which tool should be used to generate a response. It may reformulate user's query to be more suitable for the expert. 
  The query is then sent to the InfraNodus HTTP node endpoint, which will query the graph that corresponds to that expert. 
  Each InfraNodus GraphRAG expert provides a rich response that takes the whole context into account and provides a response from each expert (graph) along with a list of relevant statements retrieved using a combination or RAG and GraphRAG. 
  The n8n AI Agent node integrates the responses received from the experts to produce the final answer.
  The final answer is sent back to the user's chat (or a webhook endpoint)

  How to use

  You need an InfraNodus GraphRAG API account and key to use this workflow. 

  Create an InfraNodus account
  Get the API key at https://infranodus.com/api-access and create a Bearer authorization key for the InfraNodus HTTP nodes.
  Create a separate knowledge graph for each expert (using PDF / content import options) in InfraNodus
  For each graph, go to the workflow, paste the name of the graph into the body name field.
  Keep other settings intact or learn more about them at the InfraNodus access points page. 
  Once you add one or more graphs as experts to your flow, add the LLM key to the OpenAI node and launch the workflow

  Requirements

  An InfraNodus account and API key
  An OpenAI (or any other LLM) API key

  Customizing this workflow

  You can use this same workflow with a Telegram bot, so you can interact with it using Telegram. There are many more customizations available. 

  Check out the complete guide at https://support.noduslabs.com/hc/en-us/articles/20174217658396-Using-InfraNodus-Knowledge-Graphs-as-Experts-for-AI-Chatbot-Agents-in-n8n

  Also check out the video tutorial with a demo:

nodes_used:
[cell repeats an earlier one in this file: 120 characters]

workflow_json:
  {"id":"bHZEpS3GDpUNmmRD","meta":{"instanceId":"2a26454b0172ffcb8d70ba77c235b1209f92cd71bf06c79ba609c7173b416d68","templateCredsSetupCompleted":true},"name":"AI Chatbot Agent: a Panel of Experts using InfraNodus Graph RAG Knowledge","tags":[{"id":"66wgFoDi9Xjl74M3","name":"Support","createdAt":"2025-05-21T17:06:32.355Z","updatedAt":"2025-05-21T17:06:32.355Z"},{"id":"9QurS5Kb1CkCYrnG","name":"Product","createdAt":"2025-05-21T17:06:29.704Z","updatedAt":"2025-05-21T17:06:29.704Z"},{"id":"IzYV3Gv55x1h73cK","name":"Ideation","createdAt":"2025-05-20T14:53:20.662Z","updatedAt":"2025-05-20T14:53:20.662Z"},{"id":"aECLdyckoPZ29skg","name":"Writing","createdAt":"2025-05-20T14:53:23.085Z","updatedAt":"2025-05-20T14:53:23.085Z"},{"id":"ciIq4giMNXaJiyiQ","name":"Thinking Tools","createdAt":"2025-05-20T14:53:17.515Z","updatedAt":"2025-05-20T14:53:17.515Z"},{"id":"hCzs9EJfBuD0RxuX","name":"Other","createdAt":"2025-05-21T17:06:34.674Z","updatedAt":"2025-05-21T17:06:34.674Z"},{"id":"sJk9cUvmMU8FkJXv","name":"AI","createdAt":"2025-05-20T13:16:15.636Z","updatedAt":"2025-05-20T13:16:15.636Z"}],"nodes":[{"id":"41bf047a-eba0-4a7c-ac46-3a5da9826180","name":"Simple Memory","type":"@n8n/n8n-nodes-langchain.memoryBufferWindow","position":[400,280],"parameters":{},"typeVersion":1.3},{"id":"9fb76eda-0a98-4260-a6dd-d1a24d721bfa","name":"When chat message received","type":"@n8n/n8n-nodes-langchain.chatTrigger","position":[0,0],"webhookId":"8925672f-55c8-4c09-b0d9-ba8e87af8807","parameters":{"public":true,"options":{"title":"EightOS Polysingularity Consilium","subtitle":"Let's find a solution to any issue you have","loadPreviousSession":"manually"},"initialMessages":"Get an advice based on EightOS and Polysingularity frameworks. Ask your question and I will provide a response based on InfraNodus GraphRAG analysis of those discourses."},"typeVersion":1.1},{"id":"cedf6471-af63-4ffe-aca3-f8f81530fcc6","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[-120,-440],"parameters":{"color":6,"width":460,"height":400,"content":"## AI Chatbot Agent with Experts\n\n### Uses the InfraNodus knowledge graphs and its Graph RAG to retrieve relevant information.\n\nUse your [InfraNodus graph](https://infranodus.com) as the knowledge base for your AI chatbot. \n\nUpload any data to InfraNodus, generate separate knowledge graphs, then connect them as tools to the agent, so it can decide which \"expert\" to use. InfraNodus' Graph RAG will provide high-quality responses that will augment the chatbot's answers.\n\nVideo demo: [https://www.youtube.com/watch?v=kS0QTUvcH6E](https://www.youtube.com/watch?v=kS0QTUvcH6E)\n\nDetailed description: [Nodus Labs support portal](https://support.noduslabs.com/hc/en-us/articles/20174217658396-Using-InfraNodus-Knowledge-Graphs-as-Experts-for-AI-Chatbot-Agents-in-n8n)\n\nInfraNodus API key can be obtained at [InfraNodus.Com](https://infranodus.com/use-case/ai-knowledge-graphs)"},"typeVersion":1},{"id":"dfbcdf98-a86b-4cd9-b3b2-98a5b94f3d13","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[840,260],"parameters":{"width":200,"height":540,"content":"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n## Expert #2\n\nAdd your InfraNodus graph here via the HTTP node using its name in the `body.name` field.\n\nDescribe what the expert does in the Description of the tool. You can use auto-generated Graph RAG summary from InfraNodus > Graph > Project Notes"},"typeVersion":1},{"id":"bcd44abe-7719-4b67-b8d7-d9887ca08a02","name":"Sticky Note3","type":"n8n-nodes-base.stickyNote","position":[1060,260],"parameters":{"width":200,"height":540,"content":"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n## Expert #3\n\nYou can add more experts here. Just make to give them descriptive names, so the agent knows which one to connect to when it has a question. "},"typeVersion":1},{"id":"c2736799-4921-438c-8b73-b935b1b7df6f","name":"Sticky Note4","type":"n8n-nodes-base.stickyNote","position":[340,260],"parameters":{"width":200,"height":540,"content":"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n## Chat Memory\n\nWe use the Simple Memory node to track the conversation's context so that the user can refer to previous messages as they converse with the model."},"typeVersion":1},{"id":"f20c53f4-4498-4585-8c6b-d7c90bd0619e","name":"Sticky Note5","type":"n8n-nodes-base.stickyNote","position":[400,-220],"parameters":{"width":460,"height":360,"content":"## 2. AI Agent\n\n### Chooses which tool (expert) to use, depending on the user's message. \n\nMake sure you describe the tools available well both in the Agent's System Prompt and in the tools' descriptions. "},"typeVersion":1},{"id":"c7d27990-45b2-457d-be9c-c6171dda2da5","name":"Sticky Note6","type":"n8n-nodes-base.stickyNote","position":[-60,-20],"parameters":{"width":220,"height":540,"content":"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n## 1. Chat Trigger\n\nYou can use this chat inside n8n or you can make it available via a public URL and then use that link or embed it to any website."},"typeVersion":1},{"id":"0273eee6-0eca-4360-ab6c-224eedf221ec","name":"Sticky Note7","type":"n8n-nodes-base.stickyNote","position":[900,-220],"parameters":{"width":220,"height":360,"content":"## 3. Chat Response\n\n### When the answer is produced, it's sent back to the user. \n\nYou can also choose to do something else to the response — e.g. save it to a Google sheet or Airtable to keep logs of the conversation. "},"typeVersion":1},{"id":"9c97ab56-80a6-48af-9d61-f3fb92fc60e7","name":"AI Agent","type":"@n8n/n8n-nodes-langchain.agent","position":[440,20],"parameters":{"options":{"systemMessage":"Always use either EightOS or Polysingularity tool before sending a response to the model. You have to use at least one of them, the one that think is more suitable. Or both if both can provide some help. \nIf you used both tools and received responses from both of them, combine them in one response making sure you merge both perspectives. Ask for specific, actionable advice."}},"typeVersion":1.9},{"id":"f09d74c1-b197-436a-90a5-253749fcbb8c","name":"OpenAI Chat Model","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[200,280],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o","cachedResultName":"gpt-4o"},"options":{}},"credentials":{"openAiApi":{"id":"07wFa8Wa4mMRCHAj","name":"OpenAi account 2"}},"typeVersion":1.2},{"id":"d6c1a430-1900-4c32-a799-a29798b45c7e","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[620,260],"parameters":{"width":200,"height":540,"content":"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n## Expert #1\n\nAdd your InfraNodus graph here via the HTTP node using its name in the `body.name` field.\n\nDescribe what the expert does in the Description of the tool. You can use auto-generated Graph RAG summary from InfraNodus > Graph > Project Notes"},"typeVersion":1},{"id":"d9c40421-f5ef-4f50-bd81-c398c86c5b65","name":"EightOS Expert","type":"n8n-nodes-base.httpRequestTool","position":[680,300],"parameters":{"url":"https://infranodus.com/api/v1/graphAndAdvice?doNotSave=true&addStats=true&optimize=develop&includeStatements=true&includeGraphSummary=true&includeGraph=false","method":"POST","options":{},"sendBody":true,"authentication":"genericCredentialType","bodyParameters":{"parameters":[{"name":"name","value":"panarchy_eightos"},{"name":"requestMode","value":"response"},{"name":"prompt","value":"={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('parameters2_Value', `User query to send to the expert`, 'string') }}"},{"name":"aiTopics","value":"true"}]},"genericAuthType":"httpBearerAuth","toolDescription":"You are an EightOS specialist who is well-versed in the questions of variability, movement, physical development, adaptivity, resilience. \n\nThe main topics of your expertise are:\n<MainTopics> \n1. Dynamic States: state dynamic fractal change hrv recovery movement regeneration \n2. Idea Scale: focus idea scale small specific gap bring sensitive \n3. Ecological Variability: variability stage thinking panarchy schema infranodus bias system \n4. Breath Count: breath give count time result concrete silence effort \n5. Knowledge Structure: structure highly graph influence knowledge ai text network \n6. Biased Discourse: stay discourse long steer objective short term shifting \n</MainTopics>"},"credentials":{"httpBearerAuth":{"id":"6lSuuSDajZrvI2GM","name":"InfraNodus API Key"}},"typeVersion":4.2},{"id":"e58946be-1a4c-4991-86b2-3e51a0241548","name":"Polysingularity Expert","type":"n8n-nodes-base.httpRequestTool","position":[900,300],"parameters":{"url":"https://infranodus.com/api/v1/graphAndAdvice?doNotSave=true&addStats=true&optimize=develop&includeStatements=true&includeGraphSummary=true&includeGraph=false","method":"POST","options":{},"sendBody":true,"authentication":"genericCredentialType","bodyParameters":{"parameters":[{"name":"name","value":"polysingularity_overview"},{"name":"requestMode","value":"response"},{"name":"prompt","value":"={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('parameters2_Value', `User query to send to the expert`, 'string') }}"},{"name":"aiTopics","value":"true"}]},"genericAuthType":"httpBearerAuth","toolDescription":"You are an expert in Polysingularity. You provide responses in the field of multiplicity, networks, seeing multiple points etc. \n\nThe main topics of your expertise are:\n<MainTopics> \n1. Community Dynamics: multiple moment time change state position specific community \n2. Cognitive Practice: polysingularity practice singularity cognitive world social polysingular mind \n3. Network Perception: network make affordance choice perceive constant environmental constantly \n4. Interaction Capacity: capacity human interaction situation node possibility concept describe \n5. Space Creation: condition space form shifting emerge attractor life center \n6. Equation Analysis: find risk fully committed equation sentence rule finding \n7. Process Multiplicity: process multiplicity exist dynamic behavior part show define \n8. Idea Connectivity: ensure diversity metastable idea encounter order connectivity unfold \n9. Directed Evolution: evolution distinct directed kind \n</MainTopics>"},"credentials":{"httpBearerAuth":{"id":"6lSuuSDajZrvI2GM","name":"InfraNodus API Key"}},"typeVersion":4.2}],"active":true,"settings":{"executionOrder":"v1"},"versionId":"8848095b-7ee0-4ab8-bc16-f807f963fb20","connections":{"Simple Memory":{"ai_memory":[[{"node":"AI Agent","type":"ai_memory","index":0}]]},"EightOS Expert":{"ai_tool":[[{"node":"AI Agent","type":"ai_tool","index":0}]]},"OpenAI Chat Model":{"ai_languageModel":[[{"node":"AI Agent","type":"ai_languageModel","index":0}]]},"Polysingularity Expert":{"ai_tool":[[{"node":"AI Agent","type":"ai_tool","index":0}]]},"When chat message received":{"main":[[{"node":"AI Agent","type":"main","index":0}]]}}}


name: Find Content Gaps in Competitors' Websites with InfraNodus GraphRAG for SEO
author_name: InfraNodus
author_username: infranodus
categories: []
created_at: 2025-05-26T12:58:02.888Z
updated_at: 2025-05-26T12:58:02.888Z
url: https://n8n.io/workflows/4403
scraped_at: 2025-07-06 21:16:30
description:
  This template can be used to find the content gaps in your competitors' discourse: identifying the topics they are not yet connecting and giving you an opportunity to fill in this gap with your content and product ideas. It will also generate research questions that will help bridge the gaps and generate new ideas.

  The template showcases the use of multiple n8n nodes and processes:
  enriching Google sheets file with the new data
  data extraction
  content enhancement using GraphRAG approach
  content gap / research question generation

  This approach can be very useful for research, marketing, and SEO applications as you can quickly get an overview of the main topics that are available online for a certain niche and understand what is missing. 

  What are Content Gaps in Marketing and SEO?

  In the context of SEO, content gaps are usually understood as the topics that your competitors rank for but you do not. 

  However, it's hard to rank for these topics because there's very high competition. So a much more effective way is to identify the gaps between the topics your competitors are talking about that are not yet bridged in their discourse.

  If you address these gaps in your content, you will increase the informational gain that your content offers and also offer a novel perspective while touching upon the topics that are relevant in your field.

  For example, if we analyze the top websites for "body and physical practices, fitness, etc." we will see that most of them are talking about the health and fitness aspects and another big topic is the community aspect. 

  However, there is a gap between the two topics: which means that most of the websites (companies) that talk about this topic don't mention the two in the same context. This might be an opportunity: bridging the gap between health, fitness but also emphasizing the community aspect that comes with a collective practice. 

  How it works
  This template consists of the two stages:

  1) Data enrichment of a Google sheet file with a list of your competitors using InfraNodus' GraphRAG to generate topical summaries and graph summaries for every URL you're analyzing. 

  2) Insight generation (using InfraNodus to identify the main topical clusters and gaps in those summaries, these insights are then added to the Google sheet file.

  Additionally, it contains a sub workflow that you can activate and launch to ask Perplexity model to conduct a market research and find the companies that operate in your field and populate the original Google sheet file.

  Here's a description step by step:

  Step 0: Populate the Google sheets file with the company data (either manually or using the sub-workflow provided or Manus AI / Deep Research)
  Steps 1-2: Triggering and Launching the workflow, extracting the company URL from the Google sheet row
  Step 3: Scraping the url content from the companies' websites and cleaning the data
  Steps 5-7: Use InfraNodus GraphRAG Content Enhancer to get a topical summary and graph summary. This is what you're going to get:



  Steps 8-10: Use InfraNodus AI to generate insight advice and research questions based on the content gaps

  How to use

  You need an InfraNodus GraphRAG API account and key to use this workflow. 

  Create an InfraNodus account
  Get the API key at https://infranodus.com/api-access and create a Bearer authorization key for the InfraNodus HTTP nodes.
  Create a separate knowledge graph for each expert (using PDF / content import options) in InfraNodus
  For each graph, go to the workflow, paste the name of the graph into the body name field.
  Keep other settings intact or learn more about them at the InfraNodus access points page. 
  Once you add one or more graphs as experts to your flow, add the LLM key to the OpenAI node and launch the workflow

  Requirements

  An InfraNodus account and API key
  A Google Sheet account and an authorization key

  Note: OpenAI key is not required. But you might want to get a Perplexity AI key if you'd like to use the sub-workflow that populates the Google sheet with your competitors' website addresses (if you don't have this list yet).

  Customizing this workflow

  You can use this same workflow with a Telegram bot or Slack (to be notified of the summaries and ideas). 

  You can also hook up automated social media content creation workflows in the end of this template, so you can generate posts that are relevant (covering the important topics in your niche) but also novel (because they connect them in a new way). 

  Check out our n8n templates for ideas at https://n8n.io/creators/infranodus/

  Check out the complete guide at https://support.noduslabs.com/hc/en-us/articles/20234254556828-Find-Content-Gaps-in-Websites-Market-Research-and-SEO-n8n-Workflow

  Also check the full tutorial with a conceptual explanation at https://support.noduslabs.com/hc/en-us/articles/20454382597916-Beat-Your-Competition-Target-Their-Content-Gaps-with-this-n8n-Automation-Workflow 

  Also check out the video tutorial with a demo:



  For support and help with this workflow, please, contact us at https://support.noduslabs.com

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

workflow_json:
  {"id":"bkRodBs0nMPT5cDv","meta":{"instanceId":"2a26454b0172ffcb8d70ba77c235b1209f92cd71bf06c79ba609c7173b416d68","templateCredsSetupCompleted":true},"name":"Find the Content Gaps in Your Competitors' Discourse for Market Research and SEO","tags":[{"id":"MyFEaUe9Eo4t7SvF","name":"SEO","createdAt":"2025-05-20T13:16:17.982Z","updatedAt":"2025-05-20T13:16:17.982Z"},{"id":"kRM0hQV2zw7VxrON","name":"Research","createdAt":"2025-05-21T19:44:19.136Z","updatedAt":"2025-05-21T19:44:19.136Z"},{"id":"sJk9cUvmMU8FkJXv","name":"AI","createdAt":"2025-05-20T13:16:15.636Z","updatedAt":"2025-05-20T13:16:15.636Z"},{"id":"kldZpTCan1suEN8v","name":"Marketing","createdAt":"2025-05-20T13:16:20.459Z","updatedAt":"2025-05-20T13:16:20.459Z"},{"id":"9QurS5Kb1CkCYrnG","name":"Product","createdAt":"2025-05-21T17:06:29.704Z","updatedAt":"2025-05-21T17:06:29.704Z"}],"nodes":[{"id":"17af96f8-2f12-48b3-864f-bd28aa765ba6","name":"When clicking \"Execute Workflow\"","type":"n8n-nodes-base.manualTrigger","position":[-200,520],"parameters":{},"typeVersion":1},{"id":"9f270d49-c494-4c67-8749-e9ae3dfd0cef","name":"HTTP Request","type":"n8n-nodes-base.httpRequest","position":[380,300],"parameters":{"url":"={{ $json.URL }}","options":{"redirect":{"redirect":{"followRedirects":true}}}},"typeVersion":3,"continueOnFail":true},{"id":"3290629e-655a-4091-aee4-41482f441a52","name":"HTML Extract","type":"n8n-nodes-base.htmlExtract","position":[560,300],"parameters":{"options":{"trimValues":false},"extractionValues":{"values":[{"key":"body","cssSelector":"html"}]}},"typeVersion":1,"continueOnFail":true},{"id":"94146021-3b01-43d0-b6d7-9fcfca0d065a","name":"Merge","type":"n8n-nodes-base.merge","position":[1580,140],"parameters":{"mode":"combine","options":{},"combinationMode":"mergeByPosition"},"typeVersion":2},{"id":"08e5118b-37df-47a7-a50d-dbd2854d3dee","name":"Clean Content","type":"n8n-nodes-base.code","position":[720,300],"parameters":{"mode":"runOnceForEachItem","jsCode":"if ($input.item.json.body){\n\n\n\n$input.item.json.content = $input.item.json.body.replaceAll('/^\\s+|\\s+$/g', '').replace('/(\\r\\n|\\n|\\r)/gm', \"\").replace(/\\s+/g, ' ')\n\n\n  $input.item.json.contentShort = $input.item.json.content.slice(0, 10000)\n}\n\n\n\n\nreturn $input.item"},"executeOnce":false,"typeVersion":1,"continueOnFail":true,"alwaysOutputData":true},{"id":"6eed41aa-176b-4a7c-8288-8c6dd47361df","name":"Split In Batches","type":"n8n-nodes-base.splitInBatches","position":[120,220],"parameters":{"options":{}},"typeVersion":1},{"id":"1ca73312-3b32-4fd7-85e9-05850383d0b4","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[-300,-200],"parameters":{"width":300,"height":640,"content":"## 1. Specify the Google Sheet file\n\n#### It should contain the company names and their URLs (in the URL column). Also the Topical Summary and the Graph Summary columns that we will copy the data to.\n\n🤌 [SEE GOOGLE SHEETS TEMPLATE HERE](https://docs.google.com/spreadsheets/d/14qR7Gi8SRCd3eM6_V3ftRcDODkEFAILEqogjUvk7hKs/edit?usp=sharing) - use the same column names and replace with your data. Can be a list of companies generated with the workflow below, or Manus AI or any other Deep Research mode or a list of URLs you'd like to analyze for SEO.\n\n\n🚨 Make sure you specify the file here"},"typeVersion":1},{"id":"8c657ce2-a363-4a77-9417-a758a8f3d3a0","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[60,-160],"parameters":{"width":220,"height":600,"content":"## 2. Avoid rate limit error\n\n#### Split requests into batches of 10 \n\nso you don't make too many requests at once. \n\n\n"},"typeVersion":1},{"id":"ebd2ae92-1757-4dc4-b21b-09ad906398ca","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[340,-80],"parameters":{"width":520,"height":520,"content":"## 3. Make an HTTP request and extract text content from the links provided\n\n#### Clean up the content to extract only text, not HTML\n\nwe will then use this content to analyze data"},"typeVersion":1},{"id":"6ef3a264-586f-406a-ad44-cdbe2aa28654","name":"Sticky Note3","type":"n8n-nodes-base.stickyNote","position":[920,-240],"parameters":{"width":440,"height":680,"content":"## 4. Use InfraNodus GraphRAG Content Enhancer Tool \n\n#### It will use its AI to generate topical summaries and structural insights from every company's website. \n\nIt will generate a \n\n1) Topical Summary — AI generated summaries of the main topical clusters found in the document (if `graph summary` requestMode is used or a single summary if `summary` requestMode is used.\n\n2) Graph Summary — the information about the content gaps, the main topical clusters, keywords, and keyword combinations for the websites you provided.\n\n"},"typeVersion":1},{"id":"727b3598-b759-4c4c-bbaa-50704d159b96","name":"InfraNodus GraphRAG Content Enhancer","type":"n8n-nodes-base.httpRequest","position":[1080,260],"parameters":{"url":"https://infranodus.com/api/v1/graphAndAdvice?doNotSave=true&optimize=develop&includeGraph=false&includeGraphSummary=true","method":"POST","options":{},"sendBody":true,"authentication":"genericCredentialType","bodyParameters":{"parameters":[{"name":"name","value":"n8n_dummy_graph"},{"name":"aiTopics","value":"true"},{"name":"text","value":"={{ $json.contentShort }}"},{"name":"requestMode","value":"summary"}]},"genericAuthType":"httpBearerAuth"},"credentials":{"httpBearerAuth":{"id":"6lSuuSDajZrvI2GM","name":"InfraNodus API Key"}},"typeVersion":4.2},{"id":"77584973-d4fd-4a5b-9344-baebdfb4e584","name":"Google Docs","type":"n8n-nodes-base.googleDocs","position":[3780,600],"parameters":{"actionsUi":{"actionFields":[{"text":"={{ $('InfraNodus AI Advice').item.json.aiAdvice[0].text }}\n\n{{ $('InfraNodus Question Generator').item.json.aiAdvice.slice(0, 3).map(advice => advice.text).join('\\n\\n') }}","action":"insert"}]},"operation":"update","documentURL":"https://docs.google.com/document/d/1q_pjPlg7flnP5TooBEC_4r-SkyY6F5tgrC-kE7lbFls/edit?tab=t.0"},"credentials":{"googleDocsOAuth2Api":{"id":"EHbGAxRKLI2ejgPv","name":"Google Docs account 2"}},"typeVersion":2},{"id":"fd082093-c2b1-483e-b418-31bebd15d2c6","name":"Aggregate","type":"n8n-nodes-base.aggregate","position":[3100,600],"parameters":{"options":{},"fieldsToAggregate":{"fieldToAggregate":[{"fieldToAggregate":"Topical Summary"},{"fieldToAggregate":"Graph Summary"}]}},"typeVersion":1},{"id":"4c82a7bf-aa76-4d43-83dc-de54679b5f10","name":"Read a Google Sheets File","type":"n8n-nodes-base.googleSheets","position":[-200,240],"parameters":{"options":{},"sheetName":{"__rl":true,"mode":"list","value":1122486654,"cachedResultUrl":"https://docs.google.com/spreadsheets/d/1l4RBfavkqZLz8JdwrgNsSwD8xERlDm6BrA2gXFPm0Dg/edit#gid=1122486654","cachedResultName":"Empty"},"documentId":{"__rl":true,"mode":"list","value":"1l4RBfavkqZLz8JdwrgNsSwD8xERlDm6BrA2gXFPm0Dg","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1l4RBfavkqZLz8JdwrgNsSwD8xERlDm6BrA2gXFPm0Dg/edit?usp=drivesdk","cachedResultName":"Visual Text Analysis Tools"}},"credentials":{"googleSheetsOAuth2Api":{"id":"DHJcCtarL7rWLBsF","name":"Google Sheets account 2"}},"typeVersion":3},{"id":"5c8a772c-573d-4115-ab61-54a492f69907","name":"Update Google Sheets with Content Insights","type":"n8n-nodes-base.googleSheets","position":[2000,240],"parameters":{"options":{},"fieldsUi":{"values":[{"column":"Graph Summary","fieldValue":"={{ $json.graphSummary }}"},{"column":"Topical Summary","fieldValue":"={{ $json.aiAdvice[0].text }}"}]},"operation":"update","sheetName":{"__rl":true,"mode":"list","value":1122486654,"cachedResultUrl":"https://docs.google.com/spreadsheets/d/1l4RBfavkqZLz8JdwrgNsSwD8xERlDm6BrA2gXFPm0Dg/edit#gid=1122486654","cachedResultName":"Empty"},"documentId":{"__rl":true,"mode":"url","value":"https://docs.google.com/spreadsheets/d/1l4RBfavkqZLz8JdwrgNsSwD8xERlDm6BrA2gXFPm0Dg/edit?gid=1287901638#gid=1287901638"},"valueToMatchOn":"={{ $json.URL }}","columnToMatchOn":"URL"},"credentials":{"googleSheetsOAuth2Api":{"id":"DHJcCtarL7rWLBsF","name":"Google Sheets account 2"}},"typeVersion":3},{"id":"47de0abb-b1ff-4620-a80f-ac3c3a2369a6","name":"Sticky Note4","type":"n8n-nodes-base.stickyNote","position":[1500,-140],"parameters":{"width":260,"height":460,"content":"## 5. Add the enhanced content to original row\n\n#### We use this node to match the result to the table row (company and URL) we used to generate this result.\n"},"typeVersion":1},{"id":"0a665031-77de-4649-a274-b19092d5f0cf","name":"Sticky Note5","type":"n8n-nodes-base.stickyNote","position":[1920,-100],"parameters":{"width":260,"height":520,"content":"## 6. Enrich the original Google sheets with the content\n\n#### We save the keywords, topical clusters, topical summaries, and content gaps to the Google sheets, so you can reuse it later in other workflows. \n\n🚨 Make sure to specify the Google sheets file here"},"typeVersion":1},{"id":"6955a297-326e-4c30-bfd7-a3abdb2eb712","name":"Wait to avoid API overload","type":"n8n-nodes-base.wait","position":[2280,500],"webhookId":"e48bd7c5-7bc3-4f1d-8134-e25c7619ba83","parameters":{"unit":"seconds"},"typeVersion":1},{"id":"f1a16bb2-231f-46ae-87d8-91852223092a","name":"If Node: did we process all the data?","type":"n8n-nodes-base.if","position":[2500,500],"parameters":{"options":{},"conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"6b987d9e-7977-4c1e-a22c-42f1bd47e780","operator":{"type":"boolean","operation":"false","singleValue":true},"leftValue":"={{ $node[\"Split In Batches\"].context[\"noItemsLeft\"] }}","rightValue":"value2"}]}},"typeVersion":2.2},{"id":"d6aa6d5d-0cb8-4149-ad78-44b51312ad1a","name":"Sticky Note6","type":"n8n-nodes-base.stickyNote","position":[2240,300],"parameters":{"width":420,"height":400,"content":"## 7. Batch complete? Go to the next one.\n\n#### We process content in batches of 10 to avoid API overload and rate limit errors."},"typeVersion":1},{"id":"e1814824-cb3d-46d3-8747-57bce510493f","name":"Get the content from Google Sheets","type":"n8n-nodes-base.googleSheets","position":[2800,600],"parameters":{"options":{},"sheetName":{"__rl":true,"mode":"list","value":1122486654,"cachedResultUrl":"https://docs.google.com/spreadsheets/d/1l4RBfavkqZLz8JdwrgNsSwD8xERlDm6BrA2gXFPm0Dg/edit#gid=1122486654","cachedResultName":"Empty"},"documentId":{"__rl":true,"mode":"list","value":"1l4RBfavkqZLz8JdwrgNsSwD8xERlDm6BrA2gXFPm0Dg","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1l4RBfavkqZLz8JdwrgNsSwD8xERlDm6BrA2gXFPm0Dg/edit?usp=drivesdk","cachedResultName":"Visual Text Analysis Tools"},"combineFilters":"OR"},"credentials":{"googleSheetsOAuth2Api":{"id":"DHJcCtarL7rWLBsF","name":"Google Sheets account 2"}},"typeVersion":4.6},{"id":"15dbb650-6c59-49fa-a2fd-8cf4a691b667","name":"InfraNodus AI Advice","type":"n8n-nodes-base.httpRequest","position":[3320,480],"parameters":{"url":"https://infranodus.com/api/v1/graphAndAdvice?doNotSave=true&optimize=develop&includeGraph=false&includeGraphSummary=true","method":"POST","options":{},"sendBody":true,"authentication":"genericCredentialType","bodyParameters":{"parameters":[{"name":"aiTopics","value":"true"},{"name":"prompt","value":"=Tell me what are the main topics and gaps in the discourse provided"},{"name":"requestMode","value":"response"},{"name":"text","value":"={{ $json['Topical Summary'].join(' ') }}"}]},"genericAuthType":"httpBearerAuth"},"credentials":{"httpBearerAuth":{"id":"6lSuuSDajZrvI2GM","name":"InfraNodus API Key"}},"typeVersion":4.2},{"id":"c7512eb4-d37f-4613-9b35-94739190515f","name":"Sticky Note7","type":"n8n-nodes-base.stickyNote","position":[2740,240],"parameters":{"height":580,"content":"## 8. Enrich the original Google sheets with your insights\n\n#### We can then use this data for further research and SEO\n\n🚨 Make sure to specify the Google sheets file here"},"typeVersion":1},{"id":"987fd873-00ed-48c8-bbb5-ef309fbd2f21","name":"Sticky Note8","type":"n8n-nodes-base.stickyNote","position":[3040,240],"parameters":{"width":500,"height":580,"content":"## 9. Get all the insights obtained from all the documents and create the final report.\n\n#### Synthesize the final report based on the main topics, summaries, and content gaps discovered in the previous steps\n\nOptional: You can also feed this output to another workflow to create a full report or SEO-friendly article. "},"typeVersion":1},{"id":"7c83852a-8a77-471e-b105-6ef31e1e210e","name":"Sticky Note9","type":"n8n-nodes-base.stickyNote","position":[-300,760],"parameters":{"width":300,"height":300,"content":"## 0. Specify the starting point\n\n#### You may choose to connect this node directly to the Step 8 if you already enriched the data in the Excel sheet.\n\nIn that case, the workflow will take data from the Topical Summary column and generate the results for you\n\n"},"typeVersion":1},{"id":"f0b063d7-65e3-4bea-8065-af0b6fdb7e8f","name":"Sticky Note10","type":"n8n-nodes-base.stickyNote","position":[-300,-400],"parameters":{"color":7,"width":2940,"height":100,"content":"# Stage 1: Data Enrichment"},"typeVersion":1},{"id":"5e697fdf-85b2-4761-a4e1-d555179afed8","name":"Sticky Note11","type":"n8n-nodes-base.stickyNote","position":[2720,-400],"parameters":{"color":7,"width":1220,"height":100,"content":"# Stage 2: Insight Generation"},"typeVersion":1},{"id":"75beedd8-bbb4-465e-98be-932af51e5199","name":"Sticky Note12","type":"n8n-nodes-base.stickyNote","position":[3720,240],"parameters":{"height":580,"content":"## 10. Save the insights into a Google Doc\n\n#### We can then use this data for further research and SEO\n\n🚨 Make sure to specify the Google docs file here"},"typeVersion":1},{"id":"3fdfae7a-456e-45fb-b1ed-c263838a5e20","name":"Merge1","type":"n8n-nodes-base.merge","position":[3580,600],"parameters":{"mode":"combine","options":{},"joinMode":"keepEverything","fieldsToMatchString":"aiAdvice"},"typeVersion":3.1},{"id":"f1ef6074-08e1-4afe-8175-9f6d9d0317a7","name":"InfraNodus Question Generator","type":"n8n-nodes-base.httpRequest","position":[3320,700],"parameters":{"url":"https://infranodus.com/api/v1/graphAndAdvice?doNotSave=true&optimize=gap&includeGraph=false&includeGraphSummary=true","method":"POST","options":{},"sendBody":true,"authentication":"genericCredentialType","bodyParameters":{"parameters":[{"name":"aiTopics","value":"true"},{"name":"prompt","value":"=Tell me what are the main topics and gaps in the discourse provided"},{"name":"requestMode","value":"question"},{"name":"text","value":"={{ $json['Topical Summary'].join(' ') }}"}]},"genericAuthType":"httpBearerAuth"},"credentials":{"httpBearerAuth":{"id":"6lSuuSDajZrvI2GM","name":"InfraNodus API Key"}},"typeVersion":4.2},{"id":"0b415fbb-5a2b-4b9a-a4ff-53d2cd3a9a33","name":"Perplexity Research","type":"n8n-nodes-base.httpRequest","position":[620,1060],"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 professional  researcher  whose task is to create the most comprehensive list of links that relate to the niche provided.\"\n    },\n    {\n      \"role\": \"user\",\n      \"content\": \"Find all the link that relate to the following field: '{{ $json['Niche'] }}'\\n\\nAdditional instructions: '{{ $json['Model Instructions'] }}'\\n IMPORTANT: \\nMake a json list of at least 20 of them. One column is the name, the other is the URL, the third one is the category they operate in. Be as comprehensive in your search as you can. IMPORTANT: answer exclusively in JSON, do NOT add any additional comments.EXAMPLE OF YOUR RESPONSE\\n\\n[{\\\"Name\\\":\\\"A\\\",\\\"URL\\\":\\\"https://website.com\\\"}]\"\n    }\n  ]\n}\n","sendBody":true,"specifyBody":"json","authentication":"genericCredentialType","genericAuthType":"httpBearerAuth"},"credentials":{"httpBearerAuth":{"id":"9fXf9Np7XsCWgxhg","name":"Perplexity"}},"typeVersion":4.2},{"id":"a73d5f72-c5f1-46c8-ae7a-08c9ec7f0755","name":"On form submission","type":"n8n-nodes-base.formTrigger","disabled":true,"position":[280,1060],"webhookId":"fcf3ba43-d94f-4aad-a8a0-62492274b372","parameters":{"options":{},"formTitle":"Generate a List of Companies for a Market Niche","formFields":{"values":[{"fieldLabel":"Niche","placeholder":"e.g. customer feedback analysis tools","requiredField":true},{"fieldLabel":"Additional Search Instructions","placeholder":"e.g. make sure to include only big companies"}]},"formDescription":"Describe the market for which you want to get a list of companies"},"typeVersion":2.2},{"id":"19becdd1-a2f6-4be7-89c7-780a8e80a11b","name":"OpenAI","type":"@n8n/n8n-nodes-langchain.openAi","position":[920,1060],"parameters":{"modelId":{"__rl":true,"mode":"list","value":"gpt-4o-mini","cachedResultName":"GPT-4O-MINI"},"options":{},"messages":{"values":[{"content":"=Take this content and generate a JSON from it: {{ $json.choices[0].message.content }}. Make sure your JSON is just a list of companies like an array. Don't give it an additional name. Your response should be in the `response` object."}]},"jsonOutput":true},"credentials":{"openAiApi":{"id":"07wFa8Wa4mMRCHAj","name":"OpenAi account 2"}},"typeVersion":1.8},{"id":"5a14b12b-9645-4a16-a377-e707562af837","name":"Google Sheets","type":"n8n-nodes-base.googleSheets","position":[1760,1060],"parameters":{"columns":{"value":{},"schema":[{"id":"Name","type":"string","display":true,"removed":true,"required":false,"displayName":"Name","defaultMatch":false,"canBeUsedToMatch":true},{"id":"URL","type":"string","display":true,"removed":true,"required":false,"displayName":"URL","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Category","type":"string","display":true,"removed":true,"required":false,"displayName":"Category","defaultMatch":false,"canBeUsedToMatch":true}],"mappingMode":"autoMapInputData","matchingColumns":[],"attemptToConvertTypes":false,"convertFieldsToString":false},"options":{},"operation":"append","sheetName":{"__rl":true,"mode":"list","value":1122486654,"cachedResultUrl":"https://docs.google.com/spreadsheets/d/1l4RBfavkqZLz8JdwrgNsSwD8xERlDm6BrA2gXFPm0Dg/edit#gid=1122486654","cachedResultName":"Empty"},"documentId":{"__rl":true,"mode":"list","value":"1l4RBfavkqZLz8JdwrgNsSwD8xERlDm6BrA2gXFPm0Dg","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1l4RBfavkqZLz8JdwrgNsSwD8xERlDm6BrA2gXFPm0Dg/edit?usp=drivesdk","cachedResultName":"Visual Text Analysis Tools"}},"credentials":{"googleSheetsOAuth2Api":{"id":"DHJcCtarL7rWLBsF","name":"Google Sheets account 2"}},"typeVersion":4.6},{"id":"068b21f2-b4e8-4ccb-9756-b0e5ee3a6833","name":"Split Out","type":"n8n-nodes-base.splitOut","position":[1260,1060],"parameters":{"options":{},"fieldToSplitOut":"message.content.response"},"typeVersion":1},{"id":"02e38788-8624-4e8f-bb9a-3e0cbed63b49","name":"Loop Over Items","type":"n8n-nodes-base.splitInBatches","position":[1460,1060],"parameters":{"options":{"reset":false}},"typeVersion":3},{"id":"c2a4b61b-74c4-443c-a15e-252f896c372e","name":"Sticky Note13","type":"n8n-nodes-base.stickyNote","position":[220,840],"parameters":{"color":6,"width":1740,"height":480,"content":"## Generate a List of URLs to Analyze \n\n#### Use this workflow to seed the Excel file with the list of URLs you'd like to analyze using the workflow above \n\nTrigger execution by clicking \"Test Workflow\" next to the form"},"typeVersion":1}],"active":false,"settings":{"executionOrder":"v1"},"versionId":"2e3a437d-bf75-4612-9ca4-b53e6c2efd31","connections":{"Merge":{"main":[[{"node":"Update Google Sheets with Content Insights","type":"main","index":0}]]},"Merge1":{"main":[[{"node":"Google Docs","type":"main","index":0}]]},"OpenAI":{"main":[[{"node":"Split Out","type":"main","index":0}]]},"Aggregate":{"main":[[{"node":"InfraNodus AI Advice","type":"main","index":0},{"node":"InfraNodus Question Generator","type":"main","index":0}]]},"Split Out":{"main":[[{"node":"Loop Over Items","type":"main","index":0}]]},"HTML Extract":{"main":[[{"node":"Clean Content","type":"main","index":0}]]},"HTTP Request":{"main":[[{"node":"HTML Extract","type":"main","index":0}]]},"Clean Content":{"main":[[{"node":"InfraNodus GraphRAG Content Enhancer","type":"main","index":0}]]},"Google Sheets":{"main":[[{"node":"Loop Over Items","type":"main","index":0}]]},"Loop Over Items":{"main":[[],[{"node":"Google Sheets","type":"main","index":0}]]},"Split In Batches":{"main":[[{"node":"HTTP Request","type":"main","index":0},{"node":"Merge","type":"main","index":0}]]},"On form submission":{"main":[[{"node":"Perplexity Research","type":"main","index":0}]]},"Perplexity Research":{"main":[[{"node":"OpenAI","type":"main","index":0}]]},"InfraNodus AI Advice":{"main":[[{"node":"Merge1","type":"main","index":0}]]},"Read a Google Sheets File":{"main":[[{"node":"Split In Batches","type":"main","index":0}]]},"Wait to avoid API overload":{"main":[[{"node":"If Node: did we process all the data?","type":"main","index":0}]]},"InfraNodus Question Generator":{"main":[[{"node":"Merge1","type":"main","index":1}]]},"When clicking \"Execute Workflow\"":{"main":[[{"node":"Read a Google Sheets File","type":"main","index":0}]]},"Get the content from Google Sheets":{"main":[[{"node":"Aggregate","type":"main","index":0}]]},"InfraNodus GraphRAG Content Enhancer":{"main":[[{"node":"Merge","type":"main","index":1}]]},"If Node: did we process all the data?":{"main":[[{"node":"Split In Batches","type":"main","index":0}],[{"node":"Get the content from Google Sheets","type":"main","index":0}]]},"Update Google Sheets with Content Insights":{"main":[[{"node":"Wait to avoid API overload","type":"main","index":0}]]}}}


name: One-way sync between Telegram, Notion, Google Drive, and Google Sheets
author_name: Lakshit Ukani
author_username: lakshit1996
categories: []
created_at: 2025-05-26T13:36:26.445Z
updated_at: 2025-05-26T13:36:26.445Z
url: https://n8n.io/workflows/4404
scraped_at: 2025-07-06 21:16:30
description:
  One-way sync between Telegram, Notion, Google Drive, and Google Sheets

  Who is this for?

  This workflow is perfect for productivity-focused teams, remote workers, virtual assistants, and digital knowledge managers who receive documents, images, or notes through Telegram and want to automatically organize and store them in Notion, Google Drive, and Google Sheets—without any manual work.

  What problem is this workflow solving?

  Managing Telegram messages and media manually across different tools like Notion, Drive, and Sheets can be tedious. This workflow automates the classification and storage of incoming Telegram content, whether it’s a text note, an image, or a document. It saves time, reduces human error, and ensures that media is stored in the right place with metadata tracking.

  What this workflow does

  Triggers on a new Telegram message** using the Telegram Trigger node.
  Classifies the message type** using a Switch node:
    Text messages are appended to a Notion block.
    Images are converted to base64, uploaded to imgbb, and then added to Notion as toggle-image blocks.
    Documents are downloaded, uploaded to Google Drive, and the metadata is logged in Google Sheets.
  Sends a completion confirmation** back to the original Telegram chat.

  Setup

  Telegram Bot: Set up a bot and get the API token.
  Notion Integration:
     Share access to your target Notion page/block.
     Use the Notion API credentials and block ID where content should be appended.
  Google Drive & Sheets:
     Connect the relevant accounts.
     Select the destination folder and spreadsheet.
  imgbb API: Obtain a free API key from imgbb.

  Replace placeholder credential IDs and asset URLs as needed in the imported workflow.

  How to customize this workflow to your needs

  Change Storage Locations**:
    Update the Notion block ID or Google Drive folder ID.
    Switch Google Sheet to log in a different file or sheet.
  Add More Filters**:
    Use additional Switch rules to handle other Telegram message types (like videos or voice messages).
  Modify Response Message**:
    Personalize the Telegram confirmation text based on the file type or sender.
  Use a different image hosting service** if you don’t want to use imgbb.

nodes_used:
  ["n8n-nodes-base.googleSheets","n8n-nodes-base.httpRequest","n8n-nodes-base.telegram","n8n-nodes-base.googleDrive","n8n-nodes-base.notion"]

workflow_json:
  {"id":"qI138Ghy6iEI1N6z","meta":{"instanceId":"353ac65d120d2007b8a1503e85a96651a9b2cbb94b0334693ebac2129fa6a7ee"},"name":"My workflow 4","tags":[],"nodes":[{"id":"7fb97ccd-9572-4e0f-8504-907f6b3e7032","name":"Main Description","type":"n8n-nodes-base.stickyNote","position":[740,-20],"parameters":{"width":520,"height":540,"content":"# 📱 Telegram Productivity Assistant\n\nThis workflow automatically processes different types of content sent via Telegram:\n- 📸 **Images**: Uploaded to Notion with captions\n- 📝 **Text**: Added as headings in Notion\n- 📁 **Files**: Stored in Google Drive with tracking"},"typeVersion":1},{"id":"22ae4187-082c-4bc4-910b-f1f4fa4fc382","name":"📱 Telegram Message Trigger","type":"n8n-nodes-base.telegramTrigger","position":[840,240],"webhookId":"1c4f6611-d006-4305-8c3b-a35690a03858","parameters":{"updates":["message"],"additionalFields":{}},"credentials":{"telegramApi":{"id":"HTmNODGaUscEHOIF","name":"AI Employee"}},"typeVersion":1.1},{"id":"5baab503-9bdf-40b1-b9c1-c4af7fc41f3a","name":"🔀 Content Type Router","type":"n8n-nodes-base.switch","position":[1080,240],"parameters":{"rules":{"values":[{"outputKey":"Image","conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"d7a05336-69bc-44c2-8b65-d5dfe4392aec","operator":{"type":"array","operation":"exists","singleValue":true},"leftValue":"={{ $json.message.photo }}","rightValue":""}]},"renameOutput":true},{"outputKey":"=Text","conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"ad5f60f6-76a9-44b7-a02d-d5899894fb89","operator":{"type":"string","operation":"exists","singleValue":true},"leftValue":"={{ $json.message.text }}","rightValue":""}]},"renameOutput":true},{"outputKey":"File","conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"eeb67e61-4a67-4abe-8a5e-841d8e82969d","operator":{"type":"object","operation":"exists","singleValue":true},"leftValue":"={{ $json.message.document }}","rightValue":""}]},"renameOutput":true}]},"options":{}},"typeVersion":3.2},{"id":"52202a7a-8425-4c78-9bc3-5a7b6d469f2e","name":"Image Path Description","type":"n8n-nodes-base.stickyNote","position":[1485,-200],"parameters":{"color":4,"width":870,"height":400,"content":"## 📸 IMAGE PROCESSING PATH\nHandles photos sent via Telegram:\n1. Downloads image from Telegram\n2. Converts to base64\n3. Uploads to ImgBB for hosting\n4. Adds to Notion with caption"},"typeVersion":1},{"id":"6a457799-2c91-4315-926a-e7ec700f9058","name":"📥 Download Telegram Image","type":"n8n-nodes-base.telegram","position":[1900,-160],"webhookId":"eb105ffc-c110-4cb5-846d-714c1601a9b6","parameters":{"fileId":"={{ $json.message.photo[2].file_id }}","resource":"file"},"credentials":{"telegramApi":{"id":"HTmNODGaUscEHOIF","name":"AI Employee"}},"typeVersion":1.2},{"id":"deb12631-3d35-43d9-aea7-75175346a4aa","name":"🔄 Convert to Base64","type":"n8n-nodes-base.extractFromFile","position":[2160,-160],"parameters":{"options":{},"operation":"binaryToPropery"},"typeVersion":1},{"id":"bd89c3f3-1dd9-474d-a759-422e0fda3193","name":"🌐 Upload to ImgBB","type":"n8n-nodes-base.httpRequest","position":[1900,40],"parameters":{"url":"https://api.imgbb.com/1/upload","method":"POST","options":{"redirect":{"redirect":{}}},"sendBody":true,"sendQuery":true,"contentType":"form-urlencoded","bodyParameters":{"parameters":[{"name":"image","value":"={{ $json.data }}"}]},"queryParameters":{"parameters":[{"name":"expiration","value":"600"},{"name":"key","value":"<api_key>"}]}},"typeVersion":4.2},{"id":"2921fbd4-b279-4f98-8e83-2f3969d33a26","name":"📝 Add Image to Notion","type":"n8n-nodes-base.httpRequest","position":[2160,40],"parameters":{"url":"https://api.notion.com/v1/blocks/1fdb06aa7d2e80b384a6eb99788f67fb/children","method":"PATCH","options":{},"jsonBody":"={\n  \"children\": [\n    {\n      \"object\": \"block\",\n      \"type\": \"toggle\",\n      \"toggle\": {\n        \"rich_text\": [\n          {\n            \"type\": \"text\",\n            \"text\": {\n              \"content\": \"{{ $('🔀 Content Type Router').item.json.message.caption }} - {{ $('📱 Telegram Message Trigger').item.json.message.from.first_name }} {{ $('📱 Telegram Message Trigger').item.json.message.from.last_name }}\"\n            }\n          }\n        ],\n        \"children\": [\n          {\n            \"object\": \"block\",\n            \"type\": \"image\",\n            \"image\": {\n              \"type\": \"external\",\n              \"external\": {\n                \"url\": \"{{ $json.data.url }}\"\n              }\n            }\n          }\n        ]\n      }\n    }\n  ]\n}","sendBody":true,"sendHeaders":true,"specifyBody":"json","authentication":"genericCredentialType","genericAuthType":"httpHeaderAuth","headerParameters":{"parameters":[{"name":"Notion-Version","value":"2022-06-28"}]}},"credentials":{"httpHeaderAuth":{"id":"OTXO91Lx1ygu5w6m","name":"Lakshit Notion Account"}},"typeVersion":4.2},{"id":"04f89ce6-488e-451e-8301-d2a251102a64","name":"Text Path Description","type":"n8n-nodes-base.stickyNote","position":[1820,240],"parameters":{"color":5,"width":350,"height":100,"content":"## 📝 TEXT PROCESSING PATH\nHandles text messages sent via Telegram:\n- Adds text as heading in Notion page"},"typeVersion":1},{"id":"c3387bd6-7b83-4a5b-8974-9478d95d7081","name":"📝 Add Text to Notion","type":"n8n-nodes-base.notion","position":[2200,240],"parameters":{"blockId":{"__rl":true,"mode":"id","value":"1fdb06aa7d2e80b384a6eb99788f67fb"},"blockUi":{"blockValues":[{"type":"heading_3","textContent":"={{ $json.message.text }}"}]},"resource":"block"},"credentials":{"notionApi":{"id":"kRSdLPqa2uISxm89","name":"Lakshit Notion Account"}},"typeVersion":2.2},{"id":"eea10444-64d2-4612-9900-5a8523e5f423","name":"File Path Description","type":"n8n-nodes-base.stickyNote","position":[1280,380],"parameters":{"color":6,"width":770,"height":500,"content":"## 📁 FILE PROCESSING PATH\nHandles document files sent via Telegram:\n1. Downloads file from Telegram\n2. Uploads to Google Drive\n3. Records file details in Google Sheets\n4. Tracks: name, uploader, size, type, creation date"},"typeVersion":1},{"id":"dead3577-529b-4a9c-9ab5-12e6ba6438fe","name":"📥 Download Telegram File","type":"n8n-nodes-base.telegram","position":[1640,500],"webhookId":"daf3efb6-7ba8-4c33-b0bd-83987b86851b","parameters":{"fileId":"={{ $json.message.document.file_id }}","resource":"file"},"credentials":{"telegramApi":{"id":"HTmNODGaUscEHOIF","name":"AI Employee"}},"typeVersion":1.2},{"id":"a3e77a99-a848-478c-a488-7245d3231a40","name":"☁️ Upload to Google Drive","type":"n8n-nodes-base.googleDrive","position":[1640,720],"parameters":{"name":"={{ $('📱 Telegram Message Trigger').item.json.message.document.file_name }}","driveId":{"__rl":true,"mode":"list","value":"My Drive"},"options":{},"folderId":{"__rl":true,"mode":"list","value":"1Y9p3y0P7X39ZnMCH16iFpJbRofLnmR9u","cachedResultUrl":"https://drive.google.com/drive/folders/1Y9p3y0P7X39ZnMCH16iFpJbRofLnmR9u","cachedResultName":"n8n"}},"credentials":{"googleDriveOAuth2Api":{"id":"mKBEbVvdjhh9SFpW","name":"Google Drive Lakshit77 account"}},"typeVersion":3},{"id":"e33ca757-0ee8-45eb-9242-21b64814384d","name":"📊 Record in Google Sheets","type":"n8n-nodes-base.googleSheets","position":[1860,600],"parameters":{"columns":{"value":{"File Size":"={{ ($json.size / (1024 * 1024)).toFixed(2) }} mb","File Type":"={{ $json.fileExtension }}","Created At":"={{ $json.createdTime.toDateTime().toFormat(\"dd-MM-yyyy HH:mm\") }}","Drive Link":"={{ $json.webViewLink }}","File Name ":"={{ $('🔀 Content Type Router').item.json.message.document.file_name }}","Person Uploaded":"={{ $('🔀 Content Type Router').item.json.message.from.first_name }} {{ $('🔀 Content Type Router').item.json.message.from.last_name }}"},"schema":[{"id":"Person Uploaded","type":"string","display":true,"removed":false,"required":false,"displayName":"Person Uploaded","defaultMatch":false,"canBeUsedToMatch":true},{"id":"File Name ","type":"string","display":true,"required":false,"displayName":"File Name ","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Created At","type":"string","display":true,"required":false,"displayName":"Created At","defaultMatch":false,"canBeUsedToMatch":true},{"id":"File Type","type":"string","display":true,"removed":false,"required":false,"displayName":"File Type","defaultMatch":false,"canBeUsedToMatch":true},{"id":"File Size","type":"string","display":true,"removed":false,"required":false,"displayName":"File Size","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Drive Link","type":"string","display":true,"required":false,"displayName":"Drive Link","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/1RZs7yzvmJZrlHMonYhHNrgmyNIBlYaZt3Lp5XY5fen0/edit#gid=0","cachedResultName":"Sheet1"},"documentId":{"__rl":true,"mode":"list","value":"1RZs7yzvmJZrlHMonYhHNrgmyNIBlYaZt3Lp5XY5fen0","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1RZs7yzvmJZrlHMonYhHNrgmyNIBlYaZt3Lp5XY5fen0/edit?usp=drivesdk","cachedResultName":"File Storage"}},"credentials":{"googleSheetsOAuth2Api":{"id":"uvQG3YEEXtu5NVSj","name":"Freelance Account"}},"typeVersion":4.5},{"id":"2687e751-f308-4d37-9583-c061cce1810a","name":"Completion Description","type":"n8n-nodes-base.stickyNote","position":[2520,80],"parameters":{"color":3,"width":300,"height":380,"content":"## ✅ COMPLETION NOTIFICATION\nSends confirmation message back to Telegram user after successful processing"},"typeVersion":1},{"id":"aad8ae8c-ac34-460f-bce3-dc9d644963d6","name":"✅ Send Completion Message","type":"n8n-nodes-base.telegram","position":[2620,240],"webhookId":"5cf134ee-b78d-4603-bb13-a88ff5f42f7b","parameters":{"text":"✅ Task Completed Successfully! Your content has been processed and saved.","chatId":"={{ $('📱 Telegram Message Trigger').item.json.message.chat.id }}","additionalFields":{"appendAttribution":false}},"credentials":{"telegramApi":{"id":"HTmNODGaUscEHOIF","name":"AI Employee"}},"typeVersion":1.2}],"active":false,"settings":{"executionOrder":"v1"},"versionId":"a22c5fab-cacd-426e-83be-39d017098d0d","connections":{"🌐 Upload to ImgBB":{"main":[[{"node":"📝 Add Image to Notion","type":"main","index":0}]]},"🔄 Convert to Base64":{"main":[[{"node":"🌐 Upload to ImgBB","type":"main","index":0}]]},"📝 Add Text to Notion":{"main":[[{"node":"✅ Send Completion Message","type":"main","index":0}]]},"📝 Add Image to Notion":{"main":[[{"node":"✅ Send Completion Message","type":"main","index":0}]]},"🔀 Content Type Router":{"main":[[{"node":"📥 Download Telegram Image","type":"main","index":0}],[{"node":"📝 Add Text to Notion","type":"main","index":0}],[{"node":"📥 Download Telegram File","type":"main","index":0}]]},"📥 Download Telegram File":{"main":[[{"node":"☁️ Upload to Google Drive","type":"main","index":0}]]},"📊 Record in Google Sheets":{"main":[[{"node":"✅ Send Completion Message","type":"main","index":0}]]},"📥 Download Telegram Image":{"main":[[{"node":"🔄 Convert to Base64","type":"main","index":0}]]},"☁️ Upload to Google Drive":{"main":[[{"node":"📊 Record in Google Sheets","type":"main","index":0}]]},"📱 Telegram Message Trigger":{"main":[[{"node":"🔀 Content Type Router","type":"main","index":0}]]}}}


name: Weekly AI News Digest with Perplexity AI and Gmail Newsletter
author_name: Derek Schatz
author_username: derekschatz
nodes_used: ["n8n-nodes-base.httpRequest","n8n-nodes-base.gmail","n8n-nodes-base.code"]
categories: []
created_at: 2025-05-27T01:18:31.882Z
updated_at: 2025-05-27T01:18:31.882Z
url: https://n8n.io/workflows/4412
scraped_at: 2025-07-06 21:16:30
description:
  Overview

  This automated workflow delivers a weekly digest of the most important AI news directly to your inbox. Every Monday at 9 AM, it uses Perplexity AI to research the latest developments and organizes them into four key categories: New Technology, Trending Topics, Top Stories, and AI Security. The workflow then formats this information into a beautifully designed HTML email with summaries, significance explanations, and source links.

  What It Does

  Automatically searches for the latest AI news using Perplexity AI
  Categorizes content into four focused areas most relevant to AI enthusiasts and professionals
  Generates comprehensive summaries explaining why each story matters
  Creates a professional HTML email with styled sections and clickable links
  Sends weekly on Monday at 9 AM (customizable schedule)
  Includes error handling with fallback content if news parsing fails

  Setup Instructions

  Import the Workflow

  Copy the JSON code and import it into your n8n instance
  The workflow will appear as “Daily AI News Summary”

  Configure Perplexity API

  Sign up for a Perplexity API account at perplexity.ai
  Create new credentials in n8n:

    Type: “OpenAI”
    Name: “perplexity-credentials”
    API Key: Your Perplexity API key
    Base URL: https://api.perplexity.ai

  Set Up Email Credentials

  Configure SMTP credentials in n8n:

    Name: “email-credentials”
    Add your email provider’s SMTP settings
    Test the connection to ensure emails can be sent

  Customize Email Settings

  Open the “Send Email Summary” node
  Update the toEmail field with your email address
  Modify the fromEmail if needed (must match your SMTP credentials)

  Optional Customizations

  Change Schedule:** Modify the “Daily Trigger” node to run at your preferred time
  Adjust Categories:** Edit the Perplexity prompt to focus on different AI topics or change the theme altogether
  Modify Styling:** Update the HTML template in the “Format Email Content” node

  Test and Activate

  Run a test execution to ensure everything works correctly
  Activate the workflow to start receiving daily AI news summaries

  Requirements

  n8n instance (cloud or self-hosted)
  Perplexity API account and key
  SMTP email access (Gmail, Outlook, etc.)

workflow_json:
  {"id":"1TrBJJYAdnNO3EjR","meta":{"instanceId":"1a11bd3c275e3c33214cb43c016339cfab9e21a0caa657df228ee3ea5a628101","templateCredsSetupCompleted":true},"name":"AI Daily News","tags":[],"nodes":[{"id":"a808eaa1-744e-4a01-98d8-d96428346d11","name":"Daily Trigger","type":"n8n-nodes-base.scheduleTrigger","position":[-120,60],"parameters":{"rule":{"interval":[{"field":"weeks","triggerAtDay":[1],"triggerAtHour":8}]}},"typeVersion":1.2},{"id":"702221b3-c127-462a-a4f1-9b32518dd4ea","name":"Set Dates","type":"n8n-nodes-base.set","position":[80,60],"parameters":{"options":{},"assignments":{"assignments":[{"id":"current-date","name":"currentDate","type":"string","value":"={{ $now.format('yyyy-MM-dd') }}"},{"id":"yesterday-date","name":"lastweekDate","type":"string","value":"={{ $now.minus({days: 7}).format('yyyy-MM-dd') }}"}]}},"typeVersion":3.4},{"id":"e4e02799-c6e2-44ce-8015-5fd71ef9a848","name":"Workflow Documentation","type":"n8n-nodes-base.stickyNote","position":[-280,-400],"parameters":{"color":6,"width":350,"height":400,"content":"## Daily AI News Summary Workflow\n\nThis workflow runs every day at 9 AM to:\n\n1. **Fetch Latest AI News**: Uses Perplexity to find recent AI developments\n2. **Categorize Content**: Organizes news into three key areas:\n   - 🚀 New Technology (breakthroughs, models, research)\n   - 💡 Tips & Tricks (practical applications, tutorials)\n   - 🛡️ AI Ethics & Security (privacy, safety, regulations)\n3. **Format & Send**: Creates a beautiful HTML email with summaries and links\n\n### Setup Required:\n- Perplexity API credentials\n- SMTP email credentials\n- Update recipient email address\n\n### Customization:\n- Change schedule time in Daily Trigger\n- Modify categories in Perplexity prompt\n- Adjust email styling in Format Email Content node"},"typeVersion":1},{"id":"dd06d61f-a4bd-4813-9586-d690e0177dc8","name":"Setup Instructions","type":"n8n-nodes-base.stickyNote","position":[360,-280],"parameters":{"color":3,"width":300,"height":260,"content":"⚙️ **Configuration Needed:**\n\n1. **Perplexity API**: Add your Perplexity API key to \"perplexity-credentials\"\n\n2. **Email Settings**: \n   - Update SMTP credentials in \"email-credentials\"\n   - Change recipient email in \"Send Email Summary\" node\n   - Update sender email if needed\n\n3. **Timing**: Modify schedule in \"Daily Trigger\" if you want different timing\n\n4. **Content**: Customize the news categories or add more in the Perplexity prompt"},"typeVersion":1},{"id":"d1990f1e-04bb-4a64-a3ed-9f4dc01416f3","name":"Perplexity AI News Search","type":"n8n-nodes-base.httpRequest","position":[300,60],"parameters":{"url":"https://api.perplexity.ai/chat/completions","method":"POST","options":{},"jsonBody":"={\n  \"model\": \"sonar\",\n  \"messages\": [\n    {\n      \"content\": \"Summarize top AI news from the last week for the following categories: \\\"New Tech\\\", \\\"AI Security\\\", \\\"Top Stories\\\", \\\"Trending Topics\\\". Provide Links. \",\n      \"role\": \"user\"\n    }\n  ],\n  \"max_tokens\": 1000,\n  \"temperature\": 0.2,\n  \"top_p\": 0.9,\n  \"return_images\": false,\n  \"return_related_questions\": false,\n  \"search_recency_filter\": \"week\",\n  \"top_k\": 0,\n  \"stream\": false,\n  \"presence_penalty\": 0,\n  \"frequency_penalty\": 1,\n  \"web_search_options\": {\n    \"search_context_size\": \"low\"\n  }\n}","sendBody":true,"sendHeaders":true,"specifyBody":"json","headerParameters":{"parameters":[{"name":"Authorization","value":"Bearer YOUR_TOKEN_HERE"}]}},"typeVersion":4.2},{"id":"492432d5-3c18-4517-85b9-4407c4ed26a3","name":"Gmail","type":"n8n-nodes-base.gmail","position":[820,60],"webhookId":"6e5776e8-b6b9-4c56-8b3a-812f68959433","parameters":{"sendTo":"","message":"={{ $json.emailHtml }}","options":{},"subject":"={{ $json.emailSubject }}"},"credentials":{"gmailOAuth2":{"id":"QFihRQlqedvJQxrX","name":"Gmail account"}},"typeVersion":2.1},{"id":"9d871937-9d72-40ff-8c26-8680475ae183","name":"Format Email Content1","type":"n8n-nodes-base.code","position":[600,60],"parameters":{"jsCode":"try {\n  // Get the Perplexity response - using the correct node reference\n  const perplexityData = $input.first().json;\n  const newsContent = perplexityData.choices[0].message.content;\n  const citations = perplexityData.citations || [];\n  \n  // Get current date from Set Dates node\n  const currentDate = $('Set Dates').first().json.currentDate;\n  \n  // Format the news content into HTML\n  const formattedContent = newsContent\n    .replace(/\\n/g, '<br>')\n    .replace(/## (.*?)\\n/g, '<h2 style=\"color: #2563eb; margin: 25px 0 15px 0; border-bottom: 2px solid #e5e7eb; padding-bottom: 8px;\">$1</h2>')\n    .replace(/\\*\\*(.*?)\\*\\*/g, '<strong>$1</strong>')\n    .replace(/\\*(.*?)\\*/g, '<em>$1</em>')\n    .replace(/- \\*\\*(.*?)\\*\\*:/g, '<div style=\"margin: 15px 0;\"><strong style=\"color: #1e40af;\">• $1:</strong>')\n    .replace(/\\[\\d+\\]/g, '') // Remove citation numbers for cleaner display\n    .replace(/(https?:\\/\\/[^\\s]+)/g, '<a href=\"$1\" style=\"color: #2563eb; text-decoration: none;\">Read more</a>');\n  \n  // Create citations section if available\n  let citationsHtml = '';\n  if (citations.length > 0) {\n    citationsHtml = `\n      <div style=\"margin-top: 30px; padding: 20px; background-color: #f0f9ff; border-radius: 8px; border: 1px solid #e0f2fe;\">\n        <h3 style=\"color: #0369a1; margin: 0 0 15px 0;\">📚 Sources</h3>\n        <ul style=\"margin: 0; padding-left: 20px;\">`;\n    \n    citations.forEach((citation, index) => {\n      citationsHtml += `<li style=\"margin: 8px 0;\"><a href=\"${citation}\" style=\"color: #2563eb; text-decoration: none;\">${citation}</a></li>`;\n    });\n    \n    citationsHtml += `</ul></div>`;\n  }\n  \n  // Create complete email HTML\n  const emailHtml = `\n    <!DOCTYPE html>\n    <html>\n    <head>\n      <meta charset=\"utf-8\">\n      <title>Daily AI News Summary</title>\n    </head>\n    <body style=\"font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px; line-height: 1.6; background-color: #f9fafb;\">\n      <header style=\"text-align: center; margin-bottom: 30px; padding: 30px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 12px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);\">\n        <h1 style=\"margin: 0; font-size: 2.5em; font-weight: 700;\">🤖 Daily AI News Summary</h1>\n        <p style=\"margin: 15px 0 0 0; font-size: 1.2em; opacity: 0.9;\">${currentDate}</p>\n        <p style=\"margin: 10px 0 0 0; font-size: 1em; opacity: 0.8;\">Your curated AI news digest</p>\n      </header>\n      \n      <main style=\"background-color: white; padding: 30px; border-radius: 12px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);\">\n        <div style=\"margin-bottom: 25px;\">\n          <div style=\"margin: 20px 0; padding: 20px; background-color: #f8fafc; border-radius: 8px; border-left: 4px solid #3b82f6;\">\n            ${formattedContent}\n          </div>\n        </div>\n        \n        ${citationsHtml}\n        \n        <div style=\"margin-top: 30px; padding: 20px; background-color: #ecfdf5; border-radius: 8px; border: 1px solid #d1fae5;\">\n          <p style=\"margin: 0; color: #065f46; font-size: 0.9em; text-align: center;\">\n            <strong>💡 Tip:</strong> Click on any links to read the full articles and stay ahead of AI trends!\n          </p>\n        </div>\n      </main>\n      \n      <footer style=\"margin-top: 30px; padding: 20px; text-align: center; color: #6b7280; font-size: 0.9em;\">\n        <p style=\"margin: 0;\">Generated by your AI News Workflow</p>\n        <p style=\"margin: 5px 0 0 0;\">${new Date().toLocaleString()}</p>\n      </footer>\n    </body>\n    </html>\n  `;\n  \n  return {\n    emailHtml,\n    emailSubject: `🤖 Daily AI News Summary - ${currentDate}`,\n    rawNewsContent: newsContent,\n    citationCount: citations.length\n  };\n  \n} catch (error) {\n  console.error('Error processing news data:', error);\n  \n  // Get current date safely\n  let currentDate;\n  try {\n    currentDate = $('Set Dates').first().json.currentDate;\n  } catch {\n    currentDate = new Date().toISOString().split('T')[0];\n  }\n  \n  // Get raw response safely  \n  let rawResponse;\n  try {\n    rawResponse = $input.first().json;\n  } catch {\n    rawResponse = 'Unable to retrieve response';\n  }\n  \n  // Fallback email in case of parsing errors\n  const fallbackHtml = `\n    <!DOCTYPE html>\n    <html>\n    <body style=\"font-family: Arial, sans-serif; max-width: 800px; margin: 0 auto; padding: 20px;\">\n      <h1 style=\"color: #dc2626;\">🤖 Daily AI News Summary - ${currentDate}</h1>\n      <div style=\"padding: 20px; background-color: #fef2f2; border: 1px solid #fecaca; border-radius: 8px; margin: 20px 0;\">\n        <h2 style=\"color: #dc2626; margin-top: 0;\">⚠️ Processing Error</h2>\n        <p>There was an issue processing today's AI news. Please check the workflow configuration.</p>\n        <p><strong>Error:</strong> ${error.message}</p>\n        <details style=\"margin-top: 15px;\">\n          <summary style=\"cursor: pointer; font-weight: bold;\">View Raw Response</summary>\n          <pre style=\"background-color: #f3f4f6; padding: 15px; border-radius: 4px; overflow-x: auto; margin-top: 10px; font-size: 12px;\">${JSON.stringify(rawResponse, null, 2)}</pre>\n        </details>\n      </div>\n    </body>\n    </html>\n  `;\n  \n  return {\n    emailHtml: fallbackHtml,\n    emailSubject: `⚠️ AI News Summary Error - ${currentDate}`,\n    error: error.message,\n    rawResponse: JSON.stringify(rawResponse)\n  };\n}\n"},"typeVersion":2}],"active":true,"settings":{"executionOrder":"v1"},"versionId":"24396203-6135-419c-a500-c97583f0eb1a","connections":{"Set Dates":{"main":[[{"node":"Perplexity AI News Search","type":"main","index":0}]]},"Daily Trigger":{"main":[[{"node":"Set Dates","type":"main","index":0}]]},"Format Email Content1":{"main":[[{"node":"Gmail","type":"main","index":0}]]},"Perplexity AI News Search":{"main":[[{"node":"Format Email Content1","type":"main","index":0}]]}}}


name: Automate News Publishing to LinkedIn with Gemini AI and RSS Feeds
author_name: Club de Inteligencia Artificial Politécnico CIAP
author_username: ciap
categories: []
created_at: 2025-05-27T04:13:35.056Z
updated_at: 2025-05-27T04:13:35.056Z
url: https://n8n.io/workflows/4414
scraped_at: 2025-07-06 21:16:30
description:
  📰 LinkedIn News Auto-Publisher

  Overview 📋

  This project is an automated news publisher for LinkedIn. It uses RSS feeds to fetch news, processes the content with the Gemini API to generate precise summaries, and automatically publishes to LinkedIn via its API.

  How It Works

  Architecture and Workflow ⚙️

  n8n**: Efficient orchestration of workflow with automation.
  RSS**: News sources such as TechCrunch and MIT Technology Review.
  Gemini API**: Dynamic generation of content and precise summaries.
  LinkedIn API**: Automatic publication on profiles and corporate pages.

  Content Processing 🧠

  Fetching news through RSS feeds.
  Processing and generating summaries with the Gemini API.
  Automatic publication on LinkedIn.

  Key Benefits ✅

  Complete automation of the news publishing process.
  Dynamic generation of precise and relevant content.
  Integration with reliable news sources and publication on a professional platform.

  Use Cases 💼

  Automation of news publishing for businesses and professionals.
  Keeping corporate profiles and pages updated with relevant content.
  Saving time in managing content on social networks.

  Requirements 👨‍💻

  n8n instance (self-hosted or cloud).
  Gemini API credentials.
  LinkedIn bot setup and API credentials.
  Configured RSS feeds to fetch news.

  Authors 👥

  Joel Choez
  Alan Bajaña
  Jaren Pazmiño
  David Sandoval

  Members of CIAP

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

workflow_json:
  {"id":"LC0IcmbjYuCMHZod","meta":{"instanceId":"8c2c429dd3943ee62e07d4501247518aac7a4e0ac2348a289df368ce47041939","templateCredsSetupCompleted":true},"name":"RSS a linkedin con IA","tags":[{"id":"gvVTOTyDYvE5GHF0","name":"autoreboot","createdAt":"2025-05-05T20:28:22.814Z","updatedAt":"2025-05-05T20:28:22.814Z"}],"nodes":[{"id":"8b3652a8-6b3c-477d-8636-8fbfe9b3c8c2","name":"AI Agent","type":"@n8n/n8n-nodes-langchain.agent","position":[-500,660],"parameters":{"text":"={{ $json.prompt}}","options":{},"promptType":"define"},"typeVersion":1.9},{"id":"f9bdcc21-02ec-4ad6-afc8-b16b40c6c57e","name":"Google Gemini Chat Model","type":"@n8n/n8n-nodes-langchain.lmChatGoogleGemini","position":[-500,860],"parameters":{"options":{},"modelName":"models/gemini-2.0-flash"},"credentials":{"googlePalmApi":{"id":"9KMVOu6vEVg8Q1M3","name":"Google Gemini(PaLM) Api CIAP"}},"typeVersion":1},{"id":"7b30aa2a-c6b4-42cc-b714-8c1e6744b4e6","name":"Schedule Trigger","type":"n8n-nodes-base.scheduleTrigger","position":[-3180,860],"parameters":{"rule":{"interval":[{"field":"weeks","triggerAtDay":[2,3,4,0],"triggerAtHour":15}]}},"typeVersion":1.2},{"id":"f8ee49fd-aaab-4366-8b5d-3be59c5a08ca","name":"RSS Read Testing Catalog","type":"n8n-nodes-base.rssFeedRead","position":[-2960,1060],"parameters":{"url":"https://www.testingcatalog.com/rss/","options":{"ignoreSSL":true}},"typeVersion":1.1},{"id":"a8285394-b8b4-42a4-8be3-45dbfc7ed1e3","name":"Transform date","type":"n8n-nodes-base.set","position":[-2520,860],"parameters":{"options":{},"assignments":{"assignments":[{"id":"9aec0a09-4b6f-4fca-98e6-789abd5fdc51","name":"title","type":"string","value":"={{ $json.title }}"},{"id":"56277e54-31a0-4804-ad23-c9ee6d244641","name":"content","type":"string","value":"={{ $json.contentSnippet }}"},{"id":"a3586a80-588e-42d1-9780-370a956ddf6b","name":"link","type":"string","value":"={{ $json.link }}"},{"id":"58f01618-8014-4685-9192-d15d596ffcd9","name":"timestampDate","type":"number","value":"={{ new Date($json.isoDate).getTime() }}"},{"id":"716bb078-8df3-4d96-8a1b-4aec4f8cf206","name":"categories","type":"array","value":"={{ $json.categories }}"}]}},"typeVersion":3.4},{"id":"5c5392e3-65d9-44f6-b4f2-03bfb6c5ba49","name":"Filter by date (more than 7 days)","type":"n8n-nodes-base.filter","position":[-2300,780],"parameters":{"options":{},"conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"e7cf09fb-af35-495d-a840-341f8d0ddcd8","operator":{"type":"number","operation":"gt"},"leftValue":"={{ $json.timestampDate}}","rightValue":"={{ Date.now() - 7 * 24 * 60 * 60 * 1000 }}"}]}},"typeVersion":2.2},{"id":"db4bedbb-c84e-4acb-83dc-fbb97ca6c2ca","name":"Sort by date","type":"n8n-nodes-base.sort","position":[-2080,780],"parameters":{"options":{},"sortFieldsUi":{"sortField":[{"order":"descending","fieldName":"timestampDate"}]}},"typeVersion":1},{"id":"4842aae7-e5f3-4fcb-8b47-eac954182cde","name":"Limit news to x","type":"n8n-nodes-base.limit","position":[-1860,780],"parameters":{},"typeVersion":1},{"id":"f9a0b527-30b3-4f65-8845-b1ae584d7b76","name":"Merge","type":"n8n-nodes-base.merge","position":[-2740,860],"parameters":{"numberInputs":3},"typeVersion":3},{"id":"1e26c489-cfe1-4b36-9071-4d41bbe1a82a","name":"RSS Read marktechpost","type":"n8n-nodes-base.rssFeedRead","position":[-2960,860],"parameters":{"url":"https://www.marktechpost.com/feed/","options":{}},"typeVersion":1.1},{"id":"44b400c2-6404-488b-8d84-e24cf66445ee","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[-3060,540],"parameters":{"color":4,"width":500,"height":660,"content":"## RSS sources \nHere you can add up to nine sources of RSS. To do so, modify the merge node for the number of RSS feeds you want, duplicate the RSS node and wire it to the trigger and the merge node\n"},"typeVersion":1},{"id":"cd5c4246-01f9-434a-8b38-9514e4e5b0d4","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[-2340,520],"parameters":{"color":5,"width":640,"height":420,"content":"## Age and number of the news \nHere you can set the number of days behind by changing the 7 by any number in the filter by date node:\n```\nDate.now() - 7 * 24 * 60 * 60 * 1000\n```\nYou can also modify the number of news in the \"limit news to x\" node"},"typeVersion":1},{"id":"bd10d075-b967-4633-9ba2-25dbf0b2869e","name":"AI Agent1","type":"@n8n/n8n-nodes-langchain.agent","position":[-1520,640],"parameters":{"text":"=Analyze the news article below. Identify and summarize these elements: core innovation, main goal, problem addressed, benefits, context, significance, key entities. For each element, output one line in plain text using a hyphen, the element name, a colon, and the description. Do not use any markdown formatting, bold, italics, or nested lists. Return only the list.\n\nTitle: {{ $json.title }}\nContent: {{ $json.content }}","options":{},"promptType":"define"},"typeVersion":1.9},{"id":"ab1c0a4d-01e8-4100-a62a-886587526299","name":"Google Gemini Chat Model1","type":"@n8n/n8n-nodes-langchain.lmChatGoogleGemini","position":[-1520,840],"parameters":{"options":{},"modelName":"models/gemini-2.0-flash"},"credentials":{"googlePalmApi":{"id":"9KMVOu6vEVg8Q1M3","name":"Google Gemini(PaLM) Api CIAP"}},"typeVersion":1},{"id":"e76371ee-84cc-41f0-8959-7d0741354ffa","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[-1620,440],"parameters":{"color":3,"width":680,"height":560,"content":"# Etapa de IA: usando el API de Gemini\n\n## Modulo de análisis de contenido"},"typeVersion":1},{"id":"24a564ad-32d3-42b9-aaca-4c9d8d77fb46","name":"Sticky Note3","type":"n8n-nodes-base.stickyNote","position":[-900,440],"parameters":{"color":3,"width":680,"height":560,"content":"# Etapa de IA: usando el API de Gemini\n\n## Modulo de obtención de hashtags"},"typeVersion":1},{"id":"0092b8e8-c0d3-4d9c-a790-8617e93e43db","name":"Information","type":"n8n-nodes-base.merge","position":[-160,180],"parameters":{"mode":"combine","options":{},"combineBy":"combineByPosition","numberInputs":3},"typeVersion":3.1},{"id":"a57550da-78ec-4d54-a416-622859ed017d","name":"Information2","type":"n8n-nodes-base.set","position":[-1700,180],"parameters":{"options":{},"assignments":{"assignments":[{"id":"a87eedc7-035a-4672-8f4b-025603473aa0","name":"Enlace","type":"string","value":"={{ $json.link }}"},{"id":"586747c1-cdde-46b2-b504-50721e22c7e1","name":"Fecha_sinFormato","type":"string","value":"={{ $json.timestampDate}}"},{"id":"891b44a6-7e36-4bfc-97c2-73defa2e4aef","name":"Titulo_original","type":"string","value":"={{ $json.title }}"},{"id":"0549ed91-6247-45d7-b165-c7ece53accc9","name":"Contenido","type":"string","value":"={{ $json.content }}"}]}},"typeVersion":3.4},{"id":"7876cd0d-cc88-4912-815c-c43ea2d25448","name":"Information3","type":"n8n-nodes-base.set","position":[-1360,1240],"parameters":{"options":{},"assignments":{"assignments":[{"id":"341ed383-56fc-4ebb-a76a-3c5ad97da091","name":"Categorias","type":"string","value":"={{ $json.categories }}"}]}},"typeVersion":3.4},{"id":"6ce78f24-fa0d-4843-b9e2-6321beb262ff","name":"Code1","type":"n8n-nodes-base.code","position":[-700,660],"parameters":{"mode":"runOnceForEachItem","jsCode":"// Accede a los datos del merge\nconst analysis = $json.output.trim();\nconst categories = JSON.parse($json.Categorias);\n\n// Construye el prompt de ingeniería avanzada\nconst prompt = `Based on the analysis: ${analysis} and these categories: ${categories.join(', ')}, select the most relevant keywords to convert into LinkedIn hashtags. Choose only those closely related to the topic, popular within the AI community, innovative, and attention-grabbing. Generate five hashtags minimum. Return only the list of hashtags formatted with “#” and separated by commas, with no additional text or line breaks. Example: #AI, #Langchain, #ModelContextProtocols.`;\n\n// Devuelve el prompt para usarlo en el siguiente nodo\nreturn { prompt };"},"typeVersion":2},{"id":"025824b0-92b1-4fef-896e-ed659a31259c","name":"Information1","type":"n8n-nodes-base.merge","position":[-880,660],"parameters":{"mode":"combine","options":{},"combineBy":"combineByPosition"},"typeVersion":3.1},{"id":"3f479d20-69eb-42f1-9de3-94fafe0cfea9","name":"Edit Fields","type":"n8n-nodes-base.set","position":[-800,300],"parameters":{"options":{},"assignments":{"assignments":[{"id":"516a13eb-fd6d-4524-870f-937bd0c8a4ec","name":"Analisis","type":"string","value":"={{ $json.output }}"}]}},"typeVersion":3.4},{"id":"466fb541-3a67-422e-94cc-79ff7aa564a1","name":"LinkedIn","type":"n8n-nodes-base.linkedIn","position":[3080,260],"parameters":{"text":"={{ $('AI Agent2').item.json.output }}","postAs":"organization","organization":"=89339025","authentication":"communityManagement","additionalFields":{},"shareMediaCategory":"IMAGE"},"credentials":{"linkedInCommunityManagementOAuth2Api":{"id":"1Wx2ujF9qglMVHJi","name":"LinkedIn Community Management account"}},"typeVersion":1},{"id":"b65ea250-f029-43c8-9aa2-4da538b468c5","name":"Sticky Note5","type":"n8n-nodes-base.stickyNote","position":[2860,0],"parameters":{"color":5,"width":560,"height":540,"content":"# Etapa: Publicación en LinkedIn \n\n## Módulo de publicación de información obtenida en LinkedIn"},"typeVersion":1},{"id":"7e668a0d-99fa-42f4-9609-cad6a02b844c","name":"Sticky Note6","type":"n8n-nodes-base.stickyNote","position":[3540,0],"parameters":{"color":2,"width":900,"height":540,"content":"# Generación de Código QR\n\n## Módulo de generación de código QR de la publicación realizada"},"typeVersion":1},{"id":"afa9677c-283e-45c7-817c-98ef5147bab9","name":"Conversión a enlace de LinkedIn","type":"n8n-nodes-base.set","position":[3620,260],"parameters":{"mode":"raw","options":{},"jsonOutput":"={\n  \"link\": \"https://www.linkedin.com/feed/update/{{ $json.urn }}\"\n} "},"typeVersion":3.4},{"id":"25a8647e-093e-4f95-bdcc-002b36d52704","name":"Generar QR","type":"n8n-nodes-base.httpRequest","position":[3920,260],"parameters":{"url":"https://api.qrserver.com/v1/create-qr-code/","options":{},"sendQuery":true,"queryParameters":{"parameters":[{"name":"data","value":"={{ $json.link }}"},{"name":"size","value":"300x300"}]}},"typeVersion":4.2},{"id":"1f482175-4527-44d7-899b-c59ffcf0dd33","name":"Escribir archivo","type":"n8n-nodes-base.writeBinaryFile","position":[4200,260],"parameters":{"options":{},"fileName":"qr.png"},"typeVersion":1},{"id":"9f2f06d6-c200-43c9-87ca-3bac64f6a752","name":"Convert to File","type":"n8n-nodes-base.convertToFile","position":[2500,260],"parameters":{"options":{},"operation":"toBinary","sourceProperty":"candidates[0].content.parts[0].inlineData.data"},"typeVersion":1.1},{"id":"7e842770-c617-4adc-a0cd-e0c6295d2e2e","name":"Sticky Note10","type":"n8n-nodes-base.stickyNote","position":[2080,0],"parameters":{"color":4,"width":680,"height":540,"content":"# Etapa de IA: Generación de Imagen\n\n## Generación de Imagen mediante Gemini 2.0 y conversión a PNG"},"typeVersion":1},{"id":"0f7f43ab-c827-43fe-9daf-f6b659fb060f","name":"Generación de Imagen1","type":"n8n-nodes-base.httpRequest","position":[2220,260],"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.output.slice(0, -2) }}\"\n        }\n      ]\n    }\n  ],\n  \"generationConfig\": {\n    \"responseModalities\": [\"Text\", \"Image\"]\n  }\n}","sendBody":true,"specifyBody":"json","authentication":"predefinedCredentialType","nodeCredentialType":"googlePalmApi"},"credentials":{"googlePalmApi":{"id":"4oDRxTpOIr5AefZt","name":"Google Gemini(PaLM) Api account 2"}},"typeVersion":4.2},{"id":"559ade49-80f1-4fab-9388-bbd32d1cdca0","name":"Google Sheets","type":"n8n-nodes-base.googleSheets","position":[3940,600],"parameters":{"columns":{"value":{"Title":"={{ $('Information').item.json.Titulo_original }}","Link_pub":"={{ $json.link }}","Link_raw":"={{ $('Information').item.json.Enlace }}"},"schema":[{"id":"Title","type":"string","display":true,"required":false,"displayName":"Title","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Link_raw","type":"string","display":true,"required":false,"displayName":"Link_raw","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Link_pub","type":"string","display":true,"required":false,"displayName":"Link_pub","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/13Q6dJDpnuQBYiPvXRWElkhKT0c7MvfmeDmG8Gbz-1Cs/edit#gid=0","cachedResultName":"Hoja 1"},"documentId":{"__rl":true,"mode":"url","value":"https://docs.google.com/spreadsheets/d/13Q6dJDpnuQBYiPvXRWElkhKT0c7MvfmeDmG8Gbz-1Cs/edit?usp=sharing"}},"credentials":{"googleSheetsOAuth2Api":{"id":"gHDZ1bBcTv3KGueR","name":"Google Sheets account 2"}},"typeVersion":4.5},{"id":"63b9cc44-abac-4a07-8a7b-4e7809af1cc6","name":"Google Sheets1","type":"n8n-nodes-base.googleSheets","position":[40,180],"parameters":{"options":{},"filtersUI":{"values":[{"lookupValue":"={{ $json.Enlace }}","lookupColumn":"Link_raw"}]},"sheetName":{"__rl":true,"mode":"list","value":"gid=0","cachedResultUrl":"https://docs.google.com/spreadsheets/d/13Q6dJDpnuQBYiPvXRWElkhKT0c7MvfmeDmG8Gbz-1Cs/edit#gid=0","cachedResultName":"Hoja 1"},"documentId":{"__rl":true,"mode":"url","value":"https://docs.google.com/spreadsheets/d/13Q6dJDpnuQBYiPvXRWElkhKT0c7MvfmeDmG8Gbz-1Cs/edit?usp=sharing"}},"credentials":{"googleSheetsOAuth2Api":{"id":"gHDZ1bBcTv3KGueR","name":"Google Sheets account 2"}},"typeVersion":4.5,"alwaysOutputData":true},{"id":"937c68b8-9f9a-46bc-89ca-966c638e1f68","name":"If exists","type":"n8n-nodes-base.if","position":[240,180],"parameters":{"options":{},"conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"04a473df-24f7-4dd6-aa55-0960263caa71","operator":{"type":"string","operation":"exists","singleValue":true},"leftValue":"={{ $json.Link_raw }}","rightValue":""}]}},"typeVersion":2.2},{"id":"68c4d695-bad7-41e4-b88a-fbd5d8cb0867","name":"Code","type":"n8n-nodes-base.code","position":[600,200],"parameters":{"jsCode":"// Acceder a todas las entradas fusionadas del nodo \"Information\" (Merge)\nconst outputs = $('Information').all();  // Accede a todas las salidas fusionadas\n\n// Extraer la información de la noticia desde la primera entrada (índice 0)\nconst informacion = outputs[0].json[\"Contenido\"] || \"No disponible\";  // Información (noticia)\n\n// Extraer los hashtags desde la tercera entrada (índice 2)\nconst hashtags = outputs[0].json[\"output\"] || \"No disponibles\";  // Hashtags\n\n// Extraer los datos adicionales de la tercera entrada (índice 2)\nconst enlace = outputs[0].json[\"Enlace\"] || \"No disponible\";  // Enlace\nconst titulo_original = outputs[0].json[\"Titulo_original\"] || \"No disponible\";  // Título original\nconst analisis = outputs[0].json[\"Analisis\"] || \"No disponible\";  // Análisis\n\n// Construir el prompt final con toda la información y estructura requerida\nconst prompt = `\n\nYour Input Fields:\n- News Title: ${titulo_original}\n- News Content: ${informacion}\n- News Analysis: ${analisis}\n- Suggested Hashtags: ${hashtags}\n- Article Link: ${enlace}\n\nPost Structure:\n1. Attractive title with emoji: create a catchy title using a relevant emoji (for example, 🚀, 💡, 🔍). The title should be concise and appropriate for LinkedIn, but it should not be the same as the news title. Make it appealing to grab the readers' attention.\n\n2. Initial summary (max. 3 lines): write a clear and direct summary that introduces the core of the news. Use professional, simple language. Avoid unnecessary technical terms.\n\n3. Relevance of the Advancement (mandatory, 3 bullet points exactly): emphasize the potential impact of the advancement and how it could shape future developments. Avoid repeating information already presented in the title or summary. This section is the most persuasive part of the post, so it must be compelling and informative. Do not use hashtags or similar elements in the opening question or bullet points. \n\n- Opening question: the opening question should introduce the significance of the advancement and prompt curiosity, directly tying it to the topic and analysis of the news. This question should smoothly lead into the 3 key points. Ensureis not too long. Ensure the opening question are shorter than a line and concise. \n\n- Bullet points: provide context (AI, science, industry, etc.) and explain its significance. Capture attention by illustrating the benefits, implications, or future potential of the advancement. Ensure the bullet points are shorter than a line and concise, avoiding excessive detail. You can use emojis if necessary, but avoid overusing them.\n\n4. Call to Action (CTA – topic-related): end the post with a short, clever question or comment directly related to the topic. It must encourage reflection or interaction. Place it as the final line, after the article link\n\n5. Link to full article: add this line right before the closing *conoce más de esta noticia en el artículo completo: ${enlace}*\n\n6. Hashtags: choose 5 to 7 hashtags from the provided list. Include only those highly relevant to the topic and professional community.\n`;\n\n// Retornar solo el prompt\nreturn { \"prompt\": prompt };"},"typeVersion":2},{"id":"879ad0d7-6c0e-481d-b203-5637ef6cd580","name":"AI Agent2","type":"@n8n/n8n-nodes-langchain.agent","position":[820,200],"parameters":{"text":"={{ $json.prompt }}","options":{"systemMessage":"=You are a professional content creator preparing a LinkedIn post in Spanish based on the news provided. The post must be concise (approx. 1200 characters), visually structured, and written in a professional and accessible tone. Follow the format and constraints below exactly."},"promptType":"define"},"typeVersion":1.9},{"id":"99792b7b-919f-42d2-9ac4-75f4512e5eaf","name":"Google Gemini Chat Model2","type":"@n8n/n8n-nodes-langchain.lmChatGoogleGemini","position":[820,380],"parameters":{"options":{},"modelName":"models/gemini-2.0-flash"},"credentials":{"googlePalmApi":{"id":"9KMVOu6vEVg8Q1M3","name":"Google Gemini(PaLM) Api CIAP"}},"typeVersion":1},{"id":"d145c813-7366-45f4-b35c-1606c5323277","name":"Sticky Note4","type":"n8n-nodes-base.stickyNote","position":[520,20],"parameters":{"color":3,"width":680,"height":540,"content":"# Etapa de IA: usando el API de Gemini\n\n## Modulo de obtención de la publicación"},"typeVersion":1},{"id":"aa78a09e-53a2-45ca-8603-7ab8d2071c0c","name":"AI Agent4","type":"@n8n/n8n-nodes-langchain.agent","position":[1620,220],"parameters":{"text":"=Create a prompt that generates only one response with no comments and no line breaks: a clean professional image for a LinkedIn news post based on the following news {{ $json.text }}. Ensure it reflects the core message conveying trust innovation and professionalism with space for overlay text. Do not use quotation marks, apostrophes, or any other punctuation marks.","options":{"systemMessage":"=1. Title Placement: place the provided title in Spanish at the upper center of the image. The title must be legible and appropriately sized. It should integrate smoothly into the design without overpowering other visual elements. Ensure it clearly reflects the core message of the news without disrupting the overall balance.\n\n2. Color Palette: choose a color palette that aligns with the theme of the news. Use colors that enhance the core message—such as blue or gray for technology or business, earth tones for sustainability, or neutral tones for leadership. The colors should work together harmoniously, supporting the message without causing distractions or overwhelming the design.\n\n3. Core Message Visualization: visualize the core message through minimalistic and relevant visuals. Use abstract symbols, icons, or relevant imagery that represent the key concepts of the article, ensuring the visuals enhance the message. Avoid overcrowding the design, maintaining a professional, clean appearance.\n\n4. Overlay Text Space: ensure clear space for overlay text (e.g., subtitles or keywords). The text should be legible, well-integrated into the design, and should not obscure important visual elements or the main message. The design should be balanced and allow the text to enhance the image, not overpower it.\n\n5. Composition: maintain a minimalist, balanced composition that adheres to LinkedIn’s professional standards. All elements—title, visuals, and text—should work harmoniously together. Ensure that nothing feels cluttered, and the layout directs the viewer’s attention in a clear, logical flow. The design should feel polished and professional.\n\n6. Output Format: the image must be designed to fit LinkedIn’s standard post dimensions. Ensure the resolution is high enough for clarity and sharpness across both desktop and mobile devices, maintaining high visual quality while fitting LinkedIn’s specifications.\n\n"},"promptType":"define"},"typeVersion":1.9},{"id":"5e15478c-cef0-4f33-ad76-5ac9e4970680","name":"Google Gemini Chat Model4","type":"@n8n/n8n-nodes-langchain.lmChatGoogleGemini","position":[1620,420],"parameters":{"options":{},"modelName":"models/gemini-2.0-flash"},"credentials":{"googlePalmApi":{"id":"9KMVOu6vEVg8Q1M3","name":"Google Gemini(PaLM) Api CIAP"}},"typeVersion":1},{"id":"68fd37f9-c871-410a-b533-9da3d5599d40","name":"Sticky Note9","type":"n8n-nodes-base.stickyNote","position":[1340,-20],"parameters":{"width":640,"height":600,"content":"# Etapa de IA: Prompt para imagen\n\n## Limpieza de contenido de noticia y generación de prompt para obtener una imagen adecuada al contexto de la noticia"},"typeVersion":1},{"id":"83afd162-9160-4a0e-8ac4-deee4e65690c","name":"Limpieza de contenido de Noticia1","type":"n8n-nodes-base.code","position":[1400,220],"parameters":{"jsCode":"let texto = $input.first().json.output\n  .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":"93bae040-4a3b-415d-80d6-fd3c8dac97a3","name":"RSS LatinxinAI","type":"n8n-nodes-base.rssFeedRead","position":[-2960,660],"parameters":{"url":"https://medium.com/feed/latinxinai","options":{}},"typeVersion":1.1}],"active":true,"settings":{"timezone":"America/Guayaquil","callerPolicy":"workflowsFromSameOwner","executionOrder":"v1"},"versionId":"e0a1c8c3-bece-4ab6-ae4f-cd83e486d413","connections":{"Code":{"main":[[{"node":"AI Agent2","type":"main","index":0}]]},"Code1":{"main":[[{"node":"AI Agent","type":"main","index":0}]]},"Merge":{"main":[[{"node":"Transform date","type":"main","index":0}]]},"AI Agent":{"main":[[{"node":"Information","type":"main","index":2}]]},"LinkedIn":{"main":[[{"node":"Conversión a enlace de LinkedIn","type":"main","index":0}]]},"AI Agent1":{"main":[[{"node":"Information1","type":"main","index":0},{"node":"Edit Fields","type":"main","index":0}]]},"AI Agent2":{"main":[[{"node":"Limpieza de contenido de Noticia1","type":"main","index":0}]]},"AI Agent4":{"main":[[{"node":"Generación de Imagen1","type":"main","index":0}]]},"If exists":{"main":[[],[{"node":"Code","type":"main","index":0}]]},"Generar QR":{"main":[[{"node":"Escribir archivo","type":"main","index":0}]]},"Edit Fields":{"main":[[{"node":"Information","type":"main","index":1}]]},"Information":{"main":[[{"node":"Google Sheets1","type":"main","index":0}]]},"Information1":{"main":[[{"node":"Code1","type":"main","index":0}]]},"Information2":{"main":[[{"node":"Information","type":"main","index":0}]]},"Information3":{"main":[[{"node":"Information1","type":"main","index":1}]]},"Sort by date":{"main":[[{"node":"Limit news to x","type":"main","index":0}]]},"Google Sheets":{"main":[[]]},"Google Sheets1":{"main":[[{"node":"If exists","type":"main","index":0}]]},"RSS LatinxinAI":{"main":[[{"node":"Merge","type":"main","index":0}]]},"Transform date":{"main":[[{"node":"Filter by date (more than 7 days)","type":"main","index":0}]]},"Convert to File":{"main":[[{"node":"LinkedIn","type":"main","index":0}]]},"Limit news to x":{"main":[[{"node":"Information2","type":"main","index":0},{"node":"Information3","type":"main","index":0},{"node":"AI Agent1","type":"main","index":0}]]},"Schedule Trigger":{"main":[[{"node":"RSS Read Testing Catalog","type":"main","index":0},{"node":"RSS Read marktechpost","type":"main","index":0},{"node":"RSS LatinxinAI","type":"main","index":0}]]},"RSS Read marktechpost":{"main":[[{"node":"Merge","type":"main","index":1}]]},"Generación de Imagen1":{"main":[[{"node":"Convert to File","type":"main","index":0}]]},"Google Gemini Chat Model":{"ai_languageModel":[[{"node":"AI Agent","type":"ai_languageModel","index":0}]]},"RSS Read Testing Catalog":{"main":[[{"node":"Merge","type":"main","index":2}]]},"Google Gemini Chat Model1":{"ai_languageModel":[[{"node":"AI Agent1","type":"ai_languageModel","index":0}]]},"Google Gemini Chat Model2":{"ai_languageModel":[[{"node":"AI Agent2","type":"ai_languageModel","index":0}]]},"Google Gemini Chat Model4":{"ai_languageModel":[[{"node":"AI Agent4","type":"ai_languageModel","index":0}]]},"Conversión a enlace de LinkedIn":{"main":[[{"node":"Generar QR","type":"main","index":0},{"node":"Google Sheets","type":"main","index":0}]]},"Filter by date (more than 7 days)":{"main":[[{"node":"Sort by date","type":"main","index":0}]]},"Limpieza de contenido de Noticia1":{"main":[[{"node":"AI Agent4","type":"main","index":0}]]}}}


name: Generate Content Ideas with Gemini Pro and Store in Google Sheets
author_name: Dvir Sharon
author_username: dvirsharon
categories: []
created_at: 2025-05-27T09:44:11.274Z
updated_at: 2025-05-27T09:44:11.274Z
url: https://n8n.io/workflows/4432
scraped_at: 2025-07-06 21:16:30
description:
  Automated Content Idea Generation and Expansion with Google Gemini and Google Sheets

  This n8n workflow automates the process of generating content ideas based on a user-defined topic, then expands each idea into a more detailed content piece (like a blog post) using Google Gemini, and finally saves all the generated data (idea title, description, and full content) into a Google Sheet. It's a powerful tool for streamlining content creation workflows.

  This workflow includes:
  Generation of multiple content ideas from a single topic.
  Expansion of each idea into detailed content using AI.
  Storage of ideas and generated content in a structured Google Sheet.
  Sticky Notes within the workflow for inline documentation and setup guidance.

  Prerequisites

  n8n Instance: You need a running n8n instance (self-hosted or cloud).
  Google AI Account: Access to Google AI (Gemini). You will need an API key.
  Google Account: Access to Google Sheets. You will need to create or use an existing spreadsheet with specific column headers.

  Installation and Setup

  Import the Workflow:
      Copy the entire JSON code provided.
      In your n8n instance, go to "Workflows".
      Click "New" -&gt; "Import from JSON".
      Paste the JSON code and click "Import".

  Configure Credentials:
      Google AI (Gemini):
          Find the "Google Gemini Chat Model for Content Idea Generator" node and the "Google Gemini Chat Model for Content Generation" node.
          Click on the "Credentials" field in both nodes (it will likely show a placeholder name like "Google Gemini(PaLM) Api account").
          Click "Create New".
          Select "Google AI API".
          Enter your Google AI API Key.
          Save the credential. (You can reuse the same credential for both nodes).
      Google Sheets:
          Find the "Google Sheets" node.
          Click on the "Credentials" field (it will likely show a placeholder name like "Google Sheets account").
          Click "Create New".
          Select "Google Sheets OAuth2 API".
          Follow the steps to connect your Google Account and grant n8n access to Google Sheets.
          Save the credential.

  Configure Google Sheets Node:
      Open the "Google Sheets" node settings.
      Spreadsheet ID: Replace the placeholder value with the actual ID of your Google Sheet. You can find the Spreadsheet ID in the URL of your Google Sheet (it's the long string of characters between /d/ and /edit).
      Sheet Name: Select or enter the name or GID of the sheet within your spreadsheet where you want to save the data (e.g., Sheet1 or gid=0).
      Columns: Ensure your Google Sheet has columns named title, description, and content. The node is configured to map the generated data to these specific column headers.
      Save the node settings.

  Review Sticky Notes:
      Look at the Sticky Notes placed around the workflow canvas. They provide helpful context and reminders for setup, required Google Sheet columns, and the AI models used.

  How to Use

  Activate the Workflow: Toggle the workflow switch to "Active".
  Trigger the Workflow:
      Since this workflow uses a "When clicking ‘Execute workflow’" node as the trigger, you can run it directly from the n8n editor.
      Click the "Execute Workflow" button.
      The workflow will start automatically.
  Set the Topic:
      Open the "Set the input fields" node.
      Modify the topic value to the subject you want to generate content ideas about.
      Save the node settings.
  Monitor Execution: Watch the workflow execute. The nodes will light up as they process. The "Loop Over Items" node will show multiple executions as it processes each generated idea.
  Check Results:
      The generated content ideas (title, description) and the expanded content will be written as new rows in the Google Sheet you configured. Each row will correspond to one generated idea and its content.

  This workflow provides a robust starting point for AI-assisted content creation. You can customize the AI prompts in the "Content Idea Generator" and "LLM Content Generator" nodes to refine the output style and format, or integrate additional steps like sending notifications or further processing the generated content.

nodes_used:
  ["n8n-nodes-base.googleSheets","n8n-nodes-base.code","@n8n/n8n-nodes-langchain.chainLlm","@n8n/n8n-nodes-langchain.outputParserStructured","@n8n/n8n-nodes-langchain.lmChatGoogleGemini"]

workflow_json:
  {"id":"BuGoXATjseKjMTPb","meta":{"instanceId":"885b4fb4a6a9c2cb5621429a7b972df0d05bb724c20ac7dac7171b62f1c7ef40","templateCredsSetupCompleted":true},"name":"Generate Content Ideas with Gemini and Store in Google Sheets","tags":[{"id":"ddPkw7Hg5dZhQu2w","name":"AI","createdAt":"2025-04-13T05:38:08.053Z","updatedAt":"2025-04-13T05:38:08.053Z"},{"id":"ZOwtAMLepQaGW76t","name":"Building Blocks","createdAt":"2025-04-13T15:23:40.462Z","updatedAt":"2025-04-13T15:23:40.462Z"},{"id":"Kujft2FOjmOVQAmJ","name":"Engineering","createdAt":"2025-04-09T01:31:00.558Z","updatedAt":"2025-04-09T01:31:00.558Z"}],"nodes":[{"id":"09c0ca0d-d7d1-4fbf-a24a-4e42d7dc90f5","name":"When clicking ‘Execute workflow’","type":"n8n-nodes-base.manualTrigger","position":[-540,-40],"parameters":{},"typeVersion":1},{"id":"841332db-96ec-4892-a253-5de4194aa8e0","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[-540,-380],"parameters":{"width":540,"height":280,"content":"## Workflow Setup\n\n**Credentials:** Configure your Google AI and Google Sheets credentials in n8n.\n\n**Google Sheets:** Create a new Google Sheet or use an existing one. Note down the Spreadsheet ID (found in the URL)\n\n**Google Sheets Node:** Update the 'Write to Google Sheet' node with your Spreadsheet ID and desired sheet/range\n\nThis workflow generates content ideas using Google AI based on a topic and saves them to your Google Sheet."},"typeVersion":1},{"id":"d1ac37c4-554b-4d72-9f55-f922a2aeccee","name":"Loop Over Items","type":"n8n-nodes-base.splitInBatches","position":[480,-40],"parameters":{"options":{}},"typeVersion":3},{"id":"dbc70763-d6a2-4ca0-b146-32dd1c896fa5","name":"Code","type":"n8n-nodes-base.code","position":[280,-40],"parameters":{"jsCode":"return $input.first().json.output"},"typeVersion":2},{"id":"3001a6ba-6ce0-4eb8-b690-91a691c5542a","name":"LLM Content Generator","type":"@n8n/n8n-nodes-langchain.chainLlm","position":[960,-20],"parameters":{"text":"=Provide me a blog post for the following title : {{ $json.title }} and description {{ $json.description }}","batching":{},"messages":{"messageValues":[{"message":"You are an expert content generator"}]},"promptType":"define"},"retryOnFail":true,"typeVersion":1.7},{"id":"8f0b5c9d-81d8-49cd-80ff-cbb73742af49","name":"Google Gemini Chat Model for Content Generation","type":"@n8n/n8n-nodes-langchain.lmChatGoogleGemini","position":[1060,140],"parameters":{"options":{},"modelName":"models/gemini-2.0-flash-exp"},"credentials":{"googlePalmApi":{"id":"YeO7dHZnuGBVQKVZ","name":"Google Gemini(PaLM) Api account"}},"typeVersion":1},{"id":"b1661b78-752d-47c6-bb8d-87de862c12ed","name":"Structured Output Parser for Content Idea Generator","type":"@n8n/n8n-nodes-langchain.outputParserStructured","position":[80,140],"parameters":{"schemaType":"manual","inputSchema":"[{\n\t\"type\": \"array\",\n\t\"properties\": {\n\t\t\"title\": {\n\t\t\t\"type\": \"string\"\n\t\t},\n\t\t\"description\": {\n\t\t\t\"type\": \"string\"\n\t\t}\n\t}\n}]"},"typeVersion":1.2},{"id":"52f76748-1eac-406b-bacd-f27a65a69665","name":"Google Sheets","type":"n8n-nodes-base.googleSheets","position":[1340,-20],"parameters":{"columns":{"value":{"title":"={{ $('Set the title & description').item.json.title }}","content":"={{ $json.text }}","description":"={{ $('Set the title & description').item.json.description }}"},"schema":[{"id":"title","type":"string","display":true,"removed":false,"required":false,"displayName":"title","defaultMatch":false,"canBeUsedToMatch":true},{"id":"description","type":"string","display":true,"required":false,"displayName":"description","defaultMatch":false,"canBeUsedToMatch":true},{"id":"content","type":"string","display":true,"required":false,"displayName":"content","defaultMatch":false,"canBeUsedToMatch":true}],"mappingMode":"defineBelow","matchingColumns":["title"],"attemptToConvertTypes":false,"convertFieldsToString":false},"options":{},"operation":"appendOrUpdate","sheetName":{"__rl":true,"mode":"list","value":"gid=0","cachedResultUrl":"https://docs.google.com/spreadsheets/d/17ahJiPGh4mbW9VQpQ_3TZCU-VDV-YlkOKFEhoEU1Zgo/edit#gid=0","cachedResultName":"Sheet1"},"documentId":{"__rl":true,"mode":"list","value":"17ahJiPGh4mbW9VQpQ_3TZCU-VDV-YlkOKFEhoEU1Zgo","cachedResultUrl":"https://docs.google.com/spreadsheets/d/17ahJiPGh4mbW9VQpQ_3TZCU-VDV-YlkOKFEhoEU1Zgo/edit?usp=drivesdk","cachedResultName":"Content Ideas"}},"credentials":{"googleSheetsOAuth2Api":{"id":"Zjoxh2BUZ6VXGQhA","name":"Google Sheets account"}},"typeVersion":4.6},{"id":"c6f1cf1b-89f7-4796-bb20-d8d0a6751a0e","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[60,-380],"parameters":{"color":4,"width":540,"height":280,"content":"## Google Sheet\n\nMake sure to have the following column names on your google sheet.\n\n1. title\n2. description\n3. content"},"typeVersion":1},{"id":"c339eb0f-4978-46b0-a63d-492b7b69a731","name":"Sticky Note4","type":"n8n-nodes-base.stickyNote","position":[660,-380],"parameters":{"color":5,"width":440,"height":240,"content":"## LLM Usages\n\nGoogle Gemini LLM is being utilized for the structured data extraction handling."},"typeVersion":1},{"id":"8f8e28b1-3466-48aa-afab-2f0f4f071ddf","name":"Set the title & description","type":"n8n-nodes-base.set","position":[700,-20],"parameters":{"options":{},"assignments":{"assignments":[{"id":"25acf070-f986-4872-bc30-7ea8143c4b70","name":"title","type":"string","value":"={{ $json.title }}"},{"id":"522324ba-b6c3-4650-b447-469edcc08aee","name":"description","type":"string","value":"={{ $json.description }}"}]}},"typeVersion":3.4},{"id":"ef4b937f-9d16-4747-b863-6b75d79e2319","name":"Set the input fields","type":"n8n-nodes-base.set","position":[-320,-40],"parameters":{"options":{},"assignments":{"assignments":[{"id":"7a1fd824-9256-4a4e-aab6-f86506c0cc91","name":"topic","type":"string","value":"Web scraper"}]}},"typeVersion":3.4},{"id":"4ed4561e-915d-4ebe-aff6-2cb16720a02e","name":"Content Idea Generator","type":"@n8n/n8n-nodes-langchain.chainLlm","position":[-100,-40],"parameters":{"text":"=Generate 5 content ideas related to the following topic: {{ $json.topic }}\n\nOutput the response in the following schema.\n\nJSON Schema\n\n[{\n\t\"type\": \"array\",\n\t\"properties\": {\n\t\t\"title\": {\n\t\t\t\"type\": \"string\"\n\t\t},\n\t\t\"description\": {\n\t\t\t\"type\": \"string\"\n\t\t}\n\t}\n}]","batching":{},"messages":{"messageValues":[{"message":"You are an expert content generator"}]},"promptType":"define","hasOutputParser":true},"retryOnFail":true,"typeVersion":1.7},{"id":"f48de4f1-c46f-4134-afed-e3fcf552f79c","name":"Google Gemini Chat Model for Content Idea Generator","type":"@n8n/n8n-nodes-langchain.lmChatGoogleGemini","position":[-100,140],"parameters":{"options":{},"modelName":"models/gemini-2.0-flash-exp"},"credentials":{"googlePalmApi":{"id":"YeO7dHZnuGBVQKVZ","name":"Google Gemini(PaLM) Api account"}},"typeVersion":1}],"active":false,"settings":{"executionOrder":"v1"},"versionId":"dc820836-0e70-4b3e-856a-68a5f27faab9","connections":{"Code":{"main":[[{"node":"Loop Over Items","type":"main","index":0}]]},"Google Sheets":{"main":[[{"node":"Loop Over Items","type":"main","index":0}]]},"Loop Over Items":{"main":[[],[{"node":"Set the title & description","type":"main","index":0}]]},"Set the input fields":{"main":[[{"node":"Content Idea Generator","type":"main","index":0}]]},"LLM Content Generator":{"main":[[{"node":"Google Sheets","type":"main","index":0}]]},"Content Idea Generator":{"main":[[{"node":"Code","type":"main","index":0}]]},"Set the title & description":{"main":[[{"node":"LLM Content Generator","type":"main","index":0}]]},"When clicking ‘Execute workflow’":{"main":[[{"node":"Set the input fields","type":"main","index":0}]]},"Google Gemini Chat Model for Content Generation":{"ai_languageModel":[[{"node":"LLM Content Generator","type":"ai_languageModel","index":0}]]},"Google Gemini Chat Model for Content Idea Generator":{"ai_languageModel":[[{"node":"Content Idea Generator","type":"ai_languageModel","index":0}]]},"Structured Output Parser for Content Idea Generator":{"ai_outputParser":[[{"node":"Content Idea Generator","type":"ai_outputParser","index":0}]]}}}


name: AI-Powered PDF Invoice Parser with Google Drive, Google Sheets & OpenAI
author_name: Billy Christi
author_username: billy
categories: []
created_at: 2025-05-28T08:35:56.008Z
updated_at: 2025-05-28T08:35:56.008Z
url: https://n8n.io/workflows/4451
scraped_at: 2025-07-06 21:16:30
description:
  Who is this for?

  This workflow is perfect for:

  Companies that manage invoices through Google Drive
  Business owners who want to minimize manual data entry and maximize accuracy
  Accounting teams and finance departments seeking to automate invoice processing

  What problem is this workflow solving?

  Processing invoices manually is time-consuming, error-prone, and inconsistent. This workflow solves those issues by:

  Automating invoice processing** from detection to data extraction to storage
  Improving accuracy** by using AI to extract key invoice data fields reliably
  Reducing human workload** while maintaining compliance and consistency

  What this workflow does

  This workflow creates a fully automated invoice processing system by:

  Monitoring a Google Drive folder for new PDF invoices in real time
  Downloading the PDF files and extracting their content using OCR technology
  Using AI (OpenAI) to parse and extract key invoice fields such as invoice number, date, total amount, vendor name, itemized details, tax, and category
  Validating the extracted data to ensure compliance with a structured JSON schema
  Storing structured data in Google Sheets for easy access, review, and reporting

  Key Features:

  AI-powered extraction handles both text-based and scanned PDF invoices
  Provides a structured, searchable invoice database in Google Sheets
  Configured to run as frequently as the user needs, ensuring timely processing.

  Setup
  Copy the Google Sheet template here:
  👉 PDF Invoice Parser – Google Sheet Template

  Connect your Google Drive account to the Drive Trigger and File Download nodes

  Add your OpenAI API key in the AI Parser node

  Link the Google Sheet in the final storage node

  Drop a test invoice PDF into the monitored Drive folder

  Required Credentials:

  OpenAI API Key**
  Google Drive Credentials**
  Google Sheets Credentials**

  How to customize this workflow to your needs
  Modify the polling interval** (default: every minute) for higher/lower frequency.
  Integrate with your accounting software** by adding nodes (e.g., QuickBooks, Xero).
  Use alternative LLM** such as Gemini, Claude.

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

workflow_json:
  {"meta":{"instanceId":"d1786ab0d745a7498abf13a9c2cdabb1374c006e889b79eef64ce0386b8f8a41"},"nodes":[{"id":"1d83f60a-db5c-495f-a419-8250b5c84bba","name":"OpenAI Chat Model","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[1580,240],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o-mini"},"options":{}},"credentials":{"openAiApi":{"id":"MGwGMKEkdcjzlYCw","name":"OpenAi account"}},"typeVersion":1.2},{"id":"d73d494b-f27f-4e67-b2d0-081b0bb93eee","name":"Structured Output Parser","type":"@n8n/n8n-nodes-langchain.outputParserStructured","position":[1800,240],"parameters":{"jsonSchemaExample":"{\n  \"invoice_number\": \"\",\n  \"invoice_date\": \"\",\n  \"due_date\": \"\",\n  \"vendor_name\": \"\",\n  \"total_amount\": \"\",\n  \"currency\": \"\",\n  \"items\": [\n    {\n      \"description\": \"\",\n      \"amount\": \"\"\n    }\n  ],\n  \"tax\": \"\",\n  \"category\": \"\"\n}"},"typeVersion":1.2},{"id":"e68b00b3-e0c1-48e8-b4b5-225ee5981b14","name":"Invoice Folder Monitor","type":"n8n-nodes-base.googleDriveTrigger","position":[1020,40],"parameters":{"event":"fileCreated","options":{},"pollTimes":{"item":[{"mode":"everyMinute"}]},"triggerOn":"specificFolder","folderToWatch":{"__rl":true,"mode":"id","value":"1KJ4fvXcKVMGJunsKvPYf8PkX5K9SVwFk"}},"credentials":{"googleDriveOAuth2Api":{"id":"SEUhrgz30NMJS3cH","name":"Google Drive account"}},"typeVersion":1},{"id":"bb5d110d-1b33-4c80-8643-de2b289a832b","name":"Download Invoice PDF","type":"n8n-nodes-base.googleDrive","position":[1220,40],"parameters":{"fileId":{"__rl":true,"mode":"id","value":"={{ $json.id }}"},"options":{},"operation":"download"},"credentials":{"googleDriveOAuth2Api":{"id":"SEUhrgz30NMJS3cH","name":"Google Drive account"}},"typeVersion":3},{"id":"f70ba717-0586-46ff-b108-25249e0d49ba","name":"PDF Text Extractor","type":"n8n-nodes-base.extractFromFile","position":[1420,40],"parameters":{"options":{},"operation":"pdf"},"typeVersion":1},{"id":"d3c46af6-51eb-4a5d-9583-3f683713f967","name":"Invoice Parser AI Agent","type":"@n8n/n8n-nodes-langchain.agent","position":[1600,40],"parameters":{"text":"=You are an intelligent invoice parser. I will give you raw text extracted from a PDF invoice. \n\n========================\nSTART OF RAW INVOICE TEXT\n\n{{ $json.text }}\n\nEND OF RAW INVOICE TEXT\n========================\n\nYour job is to:\n\n1. Extract key information from the invoice such as:\n   - invoice_number\n   - invoice_date\n   - due_date (if available)\n   - vendor_name\n   - total_amount\n   - currency (e.g., USD, IDR, etc.)\n   - items (as a list of item descriptions and their amounts)\n   - tax (if available)\n\n2. Detect the invoice **category**, such as:\n   - Utilities\n   - Office Supplies\n   - Travel\n   - Software\n   - Food & Beverage\n   - Others (if unknown)\n\n3. Return the result in this exact JSON format:\n\n```json\n{\n  \"invoice_number\": \"\",\n  \"invoice_date\": \"\",\n  \"due_date\": \"\",\n  \"vendor_name\": \"\",\n  \"total_amount\": \"\",\n  \"currency\": \"\",\n  \"items\": [\n    {\n      \"description\": \"\",\n      \"amount\": \"\"\n    }\n  ],\n  \"tax\": \"\",\n  \"category\": \"\"\n}\n","options":{},"promptType":"define","hasOutputParser":true},"typeVersion":1.9},{"id":"0409d061-9836-46da-bd44-2ebdca72a2d5","name":"Insert Invoice Data","type":"n8n-nodes-base.googleSheets","position":[1940,40],"parameters":{"columns":{"value":{"Tax":"={{ $json.output.tax }}","Items":"={{ $json.output.items }}","Category":"={{ $json.output.category }}","Currency":"={{ $json.output.currency }}","Due Date":"={{ $json.output.due_date }}","Vendor Name":"={{ $json.output.vendor_name }}","Invoice Date":"={{ $json.output.invoice_date }}","Total Amount":"={{ $json.output.total_amount }}","Invoice Number":"={{ $json.output.invoice_number }}"},"schema":[{"id":"Invoice Number","type":"string","display":true,"removed":false,"required":false,"displayName":"Invoice Number","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Invoice Date","type":"string","display":true,"removed":false,"required":false,"displayName":"Invoice Date","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Due Date","type":"string","display":true,"removed":false,"required":false,"displayName":"Due Date","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Vendor Name","type":"string","display":true,"removed":false,"required":false,"displayName":"Vendor Name","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Total Amount","type":"string","display":true,"removed":false,"required":false,"displayName":"Total Amount","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Currency","type":"string","display":true,"removed":false,"required":false,"displayName":"Currency","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Items","type":"string","display":true,"removed":false,"required":false,"displayName":"Items","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Tax","type":"string","display":true,"removed":false,"required":false,"displayName":"Tax","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Category","type":"string","display":true,"removed":false,"required":false,"displayName":"Category","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/1u5dHeytao9y3L0Mgv8cSomPVLS3CMrn_eOwXW3oQ3c8/edit#gid=0","cachedResultName":"Invoices"},"documentId":{"__rl":true,"mode":"list","value":"1u5dHeytao9y3L0Mgv8cSomPVLS3CMrn_eOwXW3oQ3c8","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1u5dHeytao9y3L0Mgv8cSomPVLS3CMrn_eOwXW3oQ3c8/edit?usp=drivesdk","cachedResultName":"PDF Invoice Parser - n8n template"}},"credentials":{"googleSheetsOAuth2Api":{"id":"ypmzFxQFfAacuVVC","name":"Google Sheets account"}},"typeVersion":4.5},{"id":"4fa0e8cf-e2c3-4588-905f-fb129a44a703","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[700,-160],"parameters":{"color":4,"width":280,"height":500,"content":"## SETUP REQUIRED\n**Author:** [Billy Christi](https://n8n.io/creators/billy/)\n\n**Copy the Google Sheet template here**:\n👉 [PDF Invoice Parser – Google Sheet Template](https://docs.google.com/spreadsheets/d/1u5dHeytao9y3L0Mgv8cSomPVLS3CMrn_eOwXW3oQ3c8/edit?gid=0#gid=0)\n\nGoogle Sheets Structure:\nSheet: \"Invoices\"\n• Column A: Invoice Number  \n• Column B: Invoice Date  \n• Column C: Due Date  \n• Column D: Vendor Name  \n• Column E: Total Amount  \n• Column F: Currency  \n• Column G: Items  \n• Column H: Tax  \n• Column I: Category  \n\nRequired Credentials:\n• Google Drive Credential  \n• Google Sheets Credential  \n• OpenAI API Key (GPT-4)\n"},"typeVersion":1},{"id":"4a6a440c-a652-4585-b357-3d1f28a7c10c","name":"Sticky Note3","type":"n8n-nodes-base.stickyNote","position":[700,380],"parameters":{"color":5,"width":460,"height":400,"content":"## 🧾 AI-Powered PDF Invoice Parser for Google Drive & Sheets\n\nWhat This Template Does:\n\n- Monitors a designated Google Drive folder for new incoming PDF invoices  \n- Automatically downloads and extracts text content from the PDFs  \n- Uses GPT-4 to intelligently parse and structure invoice data (amount, vendor, items, date, etc.)  \n- Categorizes invoices by type (Office Supplies, Food & Beverage, etc.)  \n- Saves all parsed invoice data into a Google Sheets document  \n- Fully automates invoice processing and bookkeeping for businesses  "},"typeVersion":1},{"id":"d1c35c48-729f-4409-a461-3f9630fa7ef3","name":"Sticky Note4","type":"n8n-nodes-base.stickyNote","position":[1180,380],"parameters":{"color":5,"width":400,"height":340,"content":"## 📋 WORKFLOW PROCESS OVERVIEW\n\nStep 1: 📂 Invoice Folder Monitor watches a specific Google Drive folder for new PDF invoices  \nStep 2: ⬇️ Download Invoice PDF downloads the new invoice as binary data  \nStep 3: 🔍 PDF Text Extractor converts the PDF binary into readable text using OCR and extraction tools  \nStep 4: 🤖 Invoice Parser AI Agent (GPT-4) analyzes the text and extracts structured invoice data in JSON format  \nStep 5: 📝 Insert Invoice Data appends the structured invoice data to the Google Sheets \"Invoices\""},"typeVersion":1}],"connections":{"OpenAI Chat Model":{"ai_languageModel":[[{"node":"Invoice Parser AI Agent","type":"ai_languageModel","index":0}]]},"PDF Text Extractor":{"main":[[{"node":"Invoice Parser AI Agent","type":"main","index":0}]]},"Download Invoice PDF":{"main":[[{"node":"PDF Text Extractor","type":"main","index":0}]]},"Invoice Folder Monitor":{"main":[[{"node":"Download Invoice PDF","type":"main","index":0}]]},"Invoice Parser AI Agent":{"main":[[{"node":"Insert Invoice Data","type":"main","index":0}]]},"Structured Output Parser":{"ai_outputParser":[[{"node":"Invoice Parser AI Agent","type":"ai_outputParser","index":0}]]}}}


name: Automated PDF Invoice Processing & Approval Flow using OpenAI and Google Sheets
author_name: Billy Christi
author_username: billy
categories: []
created_at: 2025-05-28T08:38:25.269Z
updated_at: 2025-05-28T08:38:25.269Z
url: https://n8n.io/workflows/4452
scraped_at: 2025-07-06 21:16:30
description:
  Who is this for?

  This workflow is ideal for:

  Finance teams** that need to process incoming invoices faster with minimal errors
  Small to mid-sized businesses** that want to automate invoice intake, review, and storage
  Operations managers** who require approval workflows and centralized record-keeping

  What problem is this workflow solving?

  Manually processing invoices is time-consuming, error-prone, and often lacks structure. This workflow solves those challenges by:

  Automating the intake of invoices** from multiple sources (email, Google Drive, web form)
  Extracting invoice data using AI**, eliminating manual data entry
  Implementing an email-based approval system** to add human oversight
  Automatically storing approved invoice data** in Google Sheets for easy access and reporting
  Notifying stakeholders** when invoices are approved or rejected

  What this workflow does

  This end-to-end invoice processing workflow includes:

  Three invoice input methods: Google Drive folder monitor, Gmail attachments, and web form uploads
  PDF to text extraction for each input method using native PDF parsing
  AI-powered invoice analysis with GPT-4 to extract structured fields such as vendor, total, and due date
  Dynamic categorization of invoice type (e.g., Travel, Software, Utilities) via AI
  Email-based approval workflow with embedded forms to collect decisions and notes
  Automated Google Sheets logging of all invoice data, approval status, and reviewer feedback
  Rejection notifications sent automatically to your finance team for transparency and follow-up

  Setup

  Copy the Google Sheet template here:  
  👉 PDF Invoice Parser with Approval Workflow – Google Sheet Template
  Connect your Google Drive account and specify the invoice folder ID  
  Set up Gmail to monitor incoming invoices with PDF attachments  
  Enable your form trigger to accept direct uploads from your internal or external users  
  Enter your OpenAI API key in the AI processing node for data extraction  
  Configure Google Sheets with a target spreadsheet to store invoice data  
  Set recipient email addresses for invoice approvals and rejection notifications  
  Test with a sample invoice to ensure end-to-end flow is working  

  How to customize this workflow to your needs

  Change input sources**: Replace Gmail with Outlook or use Slack uploads instead
  Add validation steps**: Include regex or keyword checks before AI analysis
  Customize the AI schema**: Modify the expected JSON structure based on your internal finance system
  Integrate with accounting tools**: Add Xero, QuickBooks, or custom API nodes to push data
  Route based on category**: Add conditional logic to handle invoices differently based on vendor or category
  Multi-level approvals**: Add additional email steps if higher-level signoff is needed
  Audit logging**: Use database or Google Sheets to maintain a historical log of approvals and rejections

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

workflow_json:
  {"meta":{"instanceId":"d1786ab0d745a7498abf13a9c2cdabb1374c006e889b79eef64ce0386b8f8a41"},"nodes":[{"id":"4bfb09fc-fb78-43bb-9390-122d422b53d4","name":"OpenAI Chat Model","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[1020,420],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o-mini"},"options":{}},"credentials":{"openAiApi":{"id":"MGwGMKEkdcjzlYCw","name":"OpenAi account"}},"typeVersion":1.2},{"id":"8da08588-e83e-4bec-95b1-cb44614570fb","name":"Structured Output Parser","type":"@n8n/n8n-nodes-langchain.outputParserStructured","position":[1240,420],"parameters":{"jsonSchemaExample":"{\n  \"invoice_number\": \"\",\n  \"invoice_date\": \"\",\n  \"due_date\": \"\",\n  \"vendor_name\": \"\",\n  \"total_amount\": \"\",\n  \"currency\": \"\",\n  \"items\": [\n    {\n      \"description\": \"\",\n      \"amount\": \"\"\n    }\n  ],\n  \"tax\": \"\",\n  \"category\": \"\"\n}"},"typeVersion":1.2},{"id":"453d73c0-82b3-4cd5-9f3f-b2a903139421","name":"Invoice Folder Monitor","type":"n8n-nodes-base.googleDriveTrigger","position":[360,0],"parameters":{"event":"fileCreated","options":{},"pollTimes":{"item":[{"mode":"everyMinute"}]},"triggerOn":"specificFolder","folderToWatch":{"__rl":true,"mode":"id","value":"1KJ4fvXcKVMGJunsKvPYf8PkX5K9SVwFk"}},"credentials":{"googleDriveOAuth2Api":{"id":"SEUhrgz30NMJS3cH","name":"Google Drive account"}},"typeVersion":1},{"id":"027f77c5-d98e-4549-be3f-8056347dea63","name":"Download Invoice PDF","type":"n8n-nodes-base.googleDrive","position":[560,0],"parameters":{"fileId":{"__rl":true,"mode":"id","value":"={{ $json.id }}"},"options":{},"operation":"download"},"credentials":{"googleDriveOAuth2Api":{"id":"SEUhrgz30NMJS3cH","name":"Google Drive account"}},"typeVersion":3},{"id":"4a3db8c1-c0e1-41b3-a34c-756c12b0b828","name":"Invoice Parser AI Agent","type":"@n8n/n8n-nodes-langchain.agent","position":[1040,220],"parameters":{"text":"=You are an intelligent invoice parser. I will give you raw text extracted from a PDF invoice. \n\n========================\nSTART OF RAW INVOICE TEXT\n\n{{ $json.text }}\n\nEND OF RAW INVOICE TEXT\n========================\n\nYour job is to:\n\n1. Extract key information from the invoice such as:\n   - invoice_number\n   - invoice_date\n   - due_date (if available)\n   - vendor_name\n   - total_amount\n   - currency (e.g., USD, IDR, etc.)\n   - items (as a list of item descriptions and their amounts)\n   - tax (if available)\n\n2. Detect the invoice **category**, such as:\n   - Utilities\n   - Office Supplies\n   - Travel\n   - Software\n   - Food & Beverage\n   - Others (if unknown)\n\n3. Return the result in this exact JSON format:\n\n```json\n{\n  \"invoice_number\": \"\",\n  \"invoice_date\": \"\",\n  \"due_date\": \"\",\n  \"vendor_name\": \"\",\n  \"total_amount\": \"\",\n  \"currency\": \"\",\n  \"items\": [\n    {\n      \"description\": \"\",\n      \"amount\": \"\"\n    }\n  ],\n  \"tax\": \"\",\n  \"category\": \"\"\n}\n","options":{},"promptType":"define","hasOutputParser":true},"typeVersion":1.9},{"id":"52ad3889-ec04-4f4a-87c6-8c29198df234","name":"Insert Invoice Data","type":"n8n-nodes-base.googleSheets","position":[1920,220],"parameters":{"columns":{"value":{"Tax":"={{ $('Invoice Parser AI Agent').item.json.output.tax }}","Items":"={{ $('Invoice Parser AI Agent').item.json.output.items }}","Approved":"={{ $json.data['Approve Invoice?'] }}","Category":"={{ $('Invoice Parser AI Agent').item.json.output.category }}","Currency":"={{ $('Invoice Parser AI Agent').item.json.output.currency }}","Due Date":"={{ $('Invoice Parser AI Agent').item.json.output.due_date }}","Reviewed By":"={{ $json.data['Reviewed By'] }}","Vendor Name":"={{ $('Invoice Parser AI Agent').item.json.output.vendor_name }}","Invoice Date":"={{ $('Invoice Parser AI Agent').item.json.output.invoice_date }}","Total Amount":"={{ $('Invoice Parser AI Agent').item.json.output.total_amount }}","Approval Notes":"={{ $json.data['Approval Notes'] }}","Invoice Number":"={{ $('Invoice Parser AI Agent').item.json.output.invoice_number }}"},"schema":[{"id":"Invoice Number","type":"string","display":true,"required":false,"displayName":"Invoice Number","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Invoice Date","type":"string","display":true,"required":false,"displayName":"Invoice Date","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Due Date","type":"string","display":true,"required":false,"displayName":"Due Date","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Vendor Name","type":"string","display":true,"required":false,"displayName":"Vendor Name","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Total Amount","type":"string","display":true,"required":false,"displayName":"Total Amount","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Currency","type":"string","display":true,"required":false,"displayName":"Currency","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Items","type":"string","display":true,"required":false,"displayName":"Items","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Tax","type":"string","display":true,"required":false,"displayName":"Tax","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Category","type":"string","display":true,"required":false,"displayName":"Category","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Approved","type":"string","display":true,"required":false,"displayName":"Approved","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Approval Notes","type":"string","display":true,"required":false,"displayName":"Approval Notes","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Reviewed By","type":"string","display":true,"required":false,"displayName":"Reviewed By","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/1ueJfN5dFTXY3_AdvnYUL5_RjV9YwSFvbxwA_ivtqnJk/edit#gid=0","cachedResultName":"Invoices"},"documentId":{"__rl":true,"mode":"list","value":"1ueJfN5dFTXY3_AdvnYUL5_RjV9YwSFvbxwA_ivtqnJk","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1ueJfN5dFTXY3_AdvnYUL5_RjV9YwSFvbxwA_ivtqnJk/edit?usp=drivesdk","cachedResultName":"Copy of PDF Invoice Parser - n8n template"}},"credentials":{"googleSheetsOAuth2Api":{"id":"ypmzFxQFfAacuVVC","name":"Google Sheets account"}},"typeVersion":4.5},{"id":"41ae561e-89ca-46fb-937a-d1f914555f16","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[0,0],"parameters":{"color":4,"width":280,"height":600,"content":"## SETUP REQUIRED\n**Author:** [Billy Christi](https://n8n.io/creators/billy/)\n\n**Copy the Google Sheet template here**:  \n👉 [PDF Invoice Parser with Approval Workflow – Google Sheet Template](https://docs.google.com/spreadsheets/d/1ueJfN5dFTXY3_AdvnYUL5_RjV9YwSFvbxwA_ivtqnJk/edit?gid=0#gid=0)\n\nGoogle Sheets Structure:\nSheet: \"Invoices\"\n• Column A: Invoice Number  \n• Column B: Invoice Date  \n• Column C: Due Date  \n• Column D: Vendor Name  \n• Column E: Total Amount  \n• Column F: Currency  \n• Column G: Items  \n• Column H: Tax  \n• Column I: Category  \n• Column J: Approved\n• Column K: Approval Notes\n• Column L: Reviewed By\n\nRequired Credentials:\n• Google Drive Credential  \n• Gmail Credential \n• Google Sheets Credential \n• OpenAI API Key (GPT-4)\n"},"typeVersion":1},{"id":"156efce3-866d-4350-bbd9-92127b19fb02","name":"Sticky Note3","type":"n8n-nodes-base.stickyNote","position":[340,640],"parameters":{"color":5,"width":700,"height":560,"content":"## 🧾 Automated PDF Invoice Processing & Approval Flow using OpenAI and Google Sheets\n\nWhat This Template Does:\n\n- Monitors **Google Drive**, **Gmail**, and a **web form** for incoming PDF invoices  \n- Automatically downloads and extracts raw text from PDF attachments  \n- Uses **GPT-4o-mini** to intelligently parse invoice data (invoice number, vendor, date, amount, tax, items, etc.)  \n- Categorizes invoices into types such as *Utilities, Travel, Office Supplies, Food & Beverage, Others*  \n- Sends a dynamic **approval request email** with an embedded decision form (Yes/No, reviewer name, notes)  \n- Stores both approved and rejected invoice data into **Google Sheets** for recordkeeping  \n- Sends rejection notifications to the finance team for follow-up  \n- Provides a complete, automated approval pipeline with human oversight  \n- Includes a structured JSON schema for consistent and error-free AI output  \n- Polls input sources every minute to ensure timely and responsive processing  \n- Ideal for businesses seeking to **automate their invoice approval and bookkeeping workflows** with AI\n\n"},"typeVersion":1},{"id":"fc894a1c-91a1-4199-87a6-535e1fd90b08","name":"Sticky Note4","type":"n8n-nodes-base.stickyNote","position":[1080,640],"parameters":{"color":5,"width":620,"height":620,"content":"## 📋 WORKFLOW PROCESS OVERVIEW\n\n1. **Invoice Collection**  \nInvoices are captured through three triggers: new PDFs in a Google Drive folder, incoming Gmail messages with PDF attachments, or direct uploads via a web form.\n\n2. **File Handling**  \nIf uploaded via Drive, the PDF is downloaded using its file ID; if via Gmail or form, the PDF is already available as binary data.\n\n3. **Text Extraction**  \nThe system extracts raw text from the PDF using the appropriate method based on its source (Drive, Email, or Form).\n\n4. **AI Data Parsing**  \nGPT-4 processes the extracted text into structured JSON, identifying invoice details like vendor, date, amount, and categorizing the invoice.\n\n5. **Approval Request**  \nAn email is sent to the reviewer with an approval form asking for a Yes/No decision along with optional notes.\n\n6. **Decision Routing**  \nIf approved, the data moves forward for storage; if rejected, a notification is sent to the finance team.\n\n7. **Save Invoice Data**  \nAll extracted and reviewed invoice data is saved into a Google Sheet, maintaining a full record of each invoice and its status.\n"},"typeVersion":1},{"id":"f568905a-bb5a-45fd-9a74-33476910df0c","name":"Send Invoice for Approval","type":"n8n-nodes-base.gmail","position":[1380,220],"webhookId":"a23938a4-fc6c-4445-8dee-17e501e92e06","parameters":{"sendTo":"replace_with_approver_email@yopmail.com","message":"=A new invoice has been submitted and requires your review and approval:","options":{},"subject":"=[Action Required] Invoice Approval Request – {{ $json.output.vendor_name }}","operation":"sendAndWait","formFields":{"values":[{"fieldType":"dropdown","fieldLabel":"Approve Invoice?","fieldOptions":{"values":[{"option":"Yes"},{"option":"No"}]},"requiredField":true},{"fieldLabel":"Reviewed By","requiredField":true},{"fieldType":"textarea","fieldLabel":"Approval Notes"}]},"responseType":"customForm"},"credentials":{"gmailOAuth2":{"id":"sWl7FFMkEUYBj0zM","name":"Gmail account"}},"typeVersion":2.1},{"id":"2b312903-d446-48f3-aad9-856c5c3272ef","name":"Monitor Email Attachments","type":"n8n-nodes-base.gmailTrigger","position":[560,220],"parameters":{"simple":false,"filters":{},"options":{"downloadAttachments":true,"dataPropertyAttachmentsPrefixName":"attachment_"},"pollTimes":{"item":[{"mode":"everyMinute"}]}},"credentials":{"gmailOAuth2":{"id":"sWl7FFMkEUYBj0zM","name":"Gmail account"}},"typeVersion":1.2},{"id":"ceae44d4-f917-498e-8c34-238e362cc2c7","name":"Upload Invoice (PDF) Form","type":"n8n-nodes-base.formTrigger","position":[560,420],"webhookId":"e033bea9-70e8-41e2-aea4-1b95714ea257","parameters":{"options":{},"formTitle":"Upload Invoice (PDF)","formFields":{"values":[{"fieldType":"file","fieldLabel":"Upload","multipleFiles":false,"requiredField":true,"acceptFileTypes":".pdf"}]},"formDescription":"Upload your invoice PDF using this form."},"typeVersion":2.2},{"id":"f156468b-b7e6-4a80-88b2-b3472cc00753","name":"Extract Text from Drive PDF","type":"n8n-nodes-base.extractFromFile","position":[760,0],"parameters":{"options":{},"operation":"pdf"},"typeVersion":1},{"id":"031914aa-0759-425d-a564-624ca56ce01b","name":"Extract Text from Email PDF","type":"n8n-nodes-base.extractFromFile","position":[760,220],"parameters":{"options":{},"operation":"pdf","binaryPropertyName":"attachment_0"},"typeVersion":1},{"id":"1a3a1109-36c0-4bf2-a919-75d869196757","name":"Extract Text from Form PDF","type":"n8n-nodes-base.extractFromFile","position":[760,420],"parameters":{"options":{},"operation":"pdf","binaryPropertyName":"Upload"},"typeVersion":1},{"id":"9211ef8b-cc47-4975-8dfd-0210b34360cb","name":"Check Approval Decision","type":"n8n-nodes-base.if","position":[1640,220],"parameters":{"options":{},"conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"451bfdfc-f645-4e3c-91cc-895558f45b11","operator":{"type":"string","operation":"equals"},"leftValue":"={{ $json.data['Approve Invoice?'] }}","rightValue":"Yes"}]}},"typeVersion":2.2},{"id":"1c051311-19c3-4c46-b9cb-c60815432fd9","name":"Send Rejection Alert","type":"n8n-nodes-base.gmail","position":[1780,480],"webhookId":"1c33c42a-0d8e-466f-a424-faba306c56af","parameters":{"sendTo":"finance_team@yopmail.com","message":"=Hi Finance Team,\n\nAn invoice from {{ $('Invoice Parser AI Agent').item.json.output.vendor_name }} has been disapproved during the approval process.\n\nReviewed By: {{ $('Send Invoice for Approval').item.json.data['Reviewed By'] }}\nApproval Notes: {{ $('Send Invoice for Approval').item.json.data['Approval Notes'] }}\n\nPlease review and follow up as needed.\n\nThank you,\nAutomated Invoice System\n\n","options":{"appendAttribution":false},"subject":"=[Alert] Invoice Disapproved – {{ $('Invoice Parser AI Agent').item.json.output.vendor_name }}","emailType":"text"},"credentials":{"gmailOAuth2":{"id":"sWl7FFMkEUYBj0zM","name":"Gmail account"}},"typeVersion":2.1}],"connections":{"OpenAI Chat Model":{"ai_languageModel":[[{"node":"Invoice Parser AI Agent","type":"ai_languageModel","index":0}]]},"Download Invoice PDF":{"main":[[{"node":"Extract Text from Drive PDF","type":"main","index":0}]]},"Send Rejection Alert":{"main":[[{"node":"Insert Invoice Data","type":"main","index":0}]]},"Invoice Folder Monitor":{"main":[[{"node":"Download Invoice PDF","type":"main","index":0}]]},"Check Approval Decision":{"main":[[{"node":"Insert Invoice Data","type":"main","index":0}],[{"node":"Send Rejection Alert","type":"main","index":0}]]},"Invoice Parser AI Agent":{"main":[[{"node":"Send Invoice for Approval","type":"main","index":0}]]},"Structured Output Parser":{"ai_outputParser":[[{"node":"Invoice Parser AI Agent","type":"ai_outputParser","index":0}]]},"Monitor Email Attachments":{"main":[[{"node":"Extract Text from Email PDF","type":"main","index":0}]]},"Send Invoice for Approval":{"main":[[{"node":"Check Approval Decision","type":"main","index":0}]]},"Upload Invoice (PDF) Form":{"main":[[{"node":"Extract Text from Form PDF","type":"main","index":0}]]},"Extract Text from Form PDF":{"main":[[{"node":"Invoice Parser AI Agent","type":"main","index":0}]]},"Extract Text from Drive PDF":{"main":[[{"node":"Invoice Parser AI Agent","type":"main","index":0}]]},"Extract Text from Email PDF":{"main":[[{"node":"Invoice Parser AI Agent","type":"main","index":0}]]}}}


name: AI Telegram Bot Agent: Smart Assistant & Content Summarizer
author_name: Yaron Been
author_username: yaron-nofluff
categories: []
created_at: 2025-05-28T14:19:55.730Z
updated_at: 2025-05-28T14:19:55.730Z
url: https://n8n.io/workflows/4457
scraped_at: 2025-07-06 21:16:30
description:
  Create your own intelligent Telegram bot that summarizes articles and processes commands automatically.

  This powerful workflow turns Telegram into your personal AI assistant, handling /help, /summary &lt;URL&gt;, and /img &lt;prompt&gt; commands with intelligent responses - perfect for teams, content creators, and anyone wanting smart automation in their messaging.

  🚀 What It Does

  Smart Command Processing: Automatically recognizes and routes /help, /summary, and /img commands to appropriate AI-powered responses.

  Article Summarization: Fetches any URL, extracts content, and generates professional 10-12 bullet point summaries using OpenAI.

  Image Generation: Processes image prompts and integrates with AI image generation services.

  Help System: Provides users with clear command instructions and usage examples.

  🎯 Key Benefits

  ✅ Personal AI Assistant: Get instant article summaries in Telegram  
  ✅ Team Productivity: Share quick content summaries with colleagues  
  ✅ Content Research: Rapidly digest articles and web content  
  ✅ 24/7 Availability: Bot works around the clock without maintenance  
  ✅ Easy Commands: Simple /summary &lt;link&gt; format anyone can use  
  ✅ Scalable: Handles multiple users and requests simultaneously  

  🏢 Perfect For

  Content Teams & Researchers
  Journalists quickly summarizing news articles
  Marketing teams researching competitor content
  Students processing academic papers and articles
  Analysts digesting industry reports

  Business Applications
  Team Communication**: Share article insights in group chats
  Research Assistance**: Quick content analysis for decision making
  Content Curation**: Summarize articles for newsletters or reports
  Knowledge Sharing**: Help teams stay informed efficiently

  ⚙️ What's Included

  Complete Bot Workflow: Ready-to-deploy Telegram bot with all commands
  AI Integration: OpenAI-powered content summarization and processing
  Smart Routing: Intelligent command recognition and response system
  Error Handling: Robust system handles invalid commands gracefully
  Extensible Design: Easy to add new commands and features

  🔧 Quick Setup Requirements

  n8n Platform**: Cloud or self-hosted instance
  Telegram Bot Token**: Create via @BotFather (free, 5 minutes)
  OpenAI API**: For content summarization (pay-per-use)
  Basic Configuration**: Follow 15-minute setup guide

  📱 User Experience

  Simple Commands:
  /help - Show available commands
  /summary https://example.com - Get article summary
  /img sunset over mountains - Generate image (with supported APIs)

  Sample Summary Output:
  📄 Article Summary:

  • Company reports 40% revenue growth in Q3 2024
  • New AI features driving customer acquisition
  • Expansion into European markets planned for 2025
  • Investment in R&D increased by 25% this quarter
  • Customer satisfaction scores improved to 94%
  • Three new product launches scheduled for next year
  • Remote work policy made permanent post-pandemic
  • Sustainability goals on track to meet 2025 targets
  • Partnership with major tech firm announced
  • Stock price up 15% following earnings report

  🎨 Customization Options

  Command Extensions: Add custom commands for specific workflows
  Response Formatting: Customize summary style and length
  Multi-Language: Support different languages for international teams
  Integration APIs: Connect additional AI services and tools
  User Permissions: Control who can use specific commands
  Analytics: Track usage patterns and popular content

  🏷️ Tags & Categories

  #telegram-bot #ai-automation #content-summarization #article-processing #team-productivity #openai-integration #smart-assistant #workflow-automation #messaging-bot #content-research #ai-agent #n8n-workflow #business-automation #telegram-integration #ai-powered-bot

  💡 Use Case Examples

  News Team: Quickly summarize breaking news articles for editorial meetings
  Marketing Agency: Research competitor content and industry trends efficiently  
  Sales Team: Digest industry reports and share insights with prospects
  Remote Team: Keep everyone informed with summarized company updates

  📈 Expected Results

  80% faster** content research and analysis
  50% more articles** processed per day vs manual reading
  100% team accessibility** through familiar Telegram interface
  24/7 availability** for global teams across time zones

  🛠️ Setup & Support

  Quick Start: Deploy your bot in 15 minutes with included guide
  Video Tutorial: Complete walkthrough available
  Template Commands: Pre-built responses and formatting
  Expert Support: Direct help from workflow creator

  📞 Get Help & Resources

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

  💼 Professional Support  
  LinkedIn: https://www.linkedin.com/in/yaronbeen/

  📧 Direct Help  
  Email: Yaron@nofluff.online - Response within 24 hours

  Ready to build your intelligent Telegram assistant?

  Get this AI Telegram Bot Agent and transform your messaging app into a powerful content processing tool. Perfect for teams, researchers, and anyone who wants AI-powered assistance directly in Telegram.

  Stop manually reading long articles. Start getting instant, intelligent summaries with simple commands.

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

workflow_json:
  {"meta":{"instanceId":"5aaf4236c70e34e423fbdb2c7b754d19253a933bb1476d548f75848a01e473cf"},"nodes":[{"id":"4a19458b-0bf2-45db-8146-734e4e8b352b","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[-580,60],"parameters":{"color":7,"width":400,"content":"Quick-Start Telegram Echo Bot\n\nA single-node Telegram bot that parses /help, /summary <URL>, or /img <prompt> and returns either a help menu, a 10–12-point article summary, or an “image in progress” acknowledgement."},"typeVersion":1},{"id":"d2cceb34-b932-48ce-baf7-43535cfbad29","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[-440,420],"parameters":{"color":7,"content":"Listener\n\nWatches for any new message from Telegram and kicks the flow off."},"typeVersion":1},{"id":"a279a398-4b55-4055-9c9f-8ea937d4d974","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[-80,780],"parameters":{"color":7,"content":"Command Router\n\nChecks if the message starts with /help, /summary, or /img, and sends it down the right path."},"typeVersion":1},{"id":"868bb629-1288-4c8f-816b-001a7ca56be2","name":"Sticky Note3","type":"n8n-nodes-base.stickyNote","position":[440,20],"parameters":{"color":7,"content":"Help Responder\n\nWhen it sees /help, replies with a simple list of commands and how to use them."},"typeVersion":1},{"id":"ec490084-aa34-41bd-8dfd-4e0cdfee5dab","name":"Sticky Note4","type":"n8n-nodes-base.stickyNote","position":[340,740],"parameters":{"color":7,"content":"Summary Checker\n\nSees if the text begins with /summary. If yes, it moves on to fetch the article; if no, skips onward."},"typeVersion":1},{"id":"370842c3-18d9-42cd-946d-694e90a41ff1","name":"Sticky Note5","type":"n8n-nodes-base.stickyNote","position":[740,220],"parameters":{"color":7,"content":"Fetcher\n\nGoes to the provided URL and downloads the page’s HTML.\n"},"typeVersion":1},{"id":"0217818c-85e4-43bb-a8d8-5053394c773f","name":"Sticky Note6","type":"n8n-nodes-base.stickyNote","position":[780,1180],"parameters":{"color":7,"content":"Image Prompt Checker\n\nSees if the text begins with /img. If yes, forwards the prompt to the image generator; if not, ends the flow."},"typeVersion":1},{"id":"ba617c66-4b13-41a1-9428-6d1afc4f458f","name":"Sticky Note7","type":"n8n-nodes-base.stickyNote","position":[1100,440],"parameters":{"color":7,"content":"Text Extractor\n\nPulls out just the main article text (e.g. everything inside <body>)."},"typeVersion":1},{"id":"df9b404e-90d7-4f66-bcd4-9d64595e7b88","name":"Sticky Note8","type":"n8n-nodes-base.stickyNote","position":[1320,1360],"parameters":{"color":7,"content":"Image Generator\n\nSends your prompt to OpenAI’s image endpoint (or your chosen image API)."},"typeVersion":1},{"id":"e7eda1c8-e860-4df2-9d4f-5d12e52b0551","name":"Sticky Note9","type":"n8n-nodes-base.stickyNote","position":[1520,220],"parameters":{"color":7,"content":"Summarizer\n\nSends the raw article text to OpenAI and asks for a 10–12-point professional bullet-point summary."},"typeVersion":1},{"id":"50331c27-388c-490d-b9d7-ff5fe8449290","name":"Sticky Note10","type":"n8n-nodes-base.stickyNote","position":[1940,1020],"parameters":{"color":7,"content":"Image Acknowledger\n\nTells the user “Got it—your image is being made!” (and later you can hook this up to send the actual picture URL)."},"typeVersion":1},{"id":"7315f25a-d63d-4f49-a43f-87dc0ff64ffb","name":"Sticky Note11","type":"n8n-nodes-base.stickyNote","position":[2140,220],"parameters":{"color":7,"content":"Summary Sender\n\nDelivers the bullet-point summary back to the user in Telegram.\n"},"typeVersion":1},{"id":"bcae4d20-e9af-4008-88b6-cfa1a6dcd6c9","name":"Listener","type":"n8n-nodes-base.telegramTrigger","position":[-140,460],"webhookId":"61f2e55d-a41d-4594-a045-154264c78738","parameters":{"updates":["message"],"additionalFields":{}},"typeVersion":1.2},{"id":"8bbcc856-b323-4785-a8ec-9de61052531a","name":"Command Router","type":"n8n-nodes-base.if","position":[160,600],"parameters":{"conditions":{"string":[{"value1":"={{$json[\"message\"][\"text\"]}}","value2":"/help","operation":"startsWith"}]}},"typeVersion":1},{"id":"09bc69c7-8852-46a8-be96-ae10bc652cd8","name":"Help Responder","type":"n8n-nodes-base.telegram","position":[380,220],"webhookId":"ab573ae8-05e4-41bb-bec7-fca1233fc0bb","parameters":{"text":"🤖 *Help Menu*\n\nUse `/summary <link>` to summarize an article.\nUse `/img <prompt>` to generate an image.\n\n_Example:_\n/summary https://example.com\n/img a futuristic cityscape","chatId":"={{$json[\"message\"][\"chat\"][\"id\"]}}","additionalFields":{"parse_mode":"Markdown"}},"typeVersion":1},{"id":"2780e14d-7ebd-43f4-87e9-1d5c7ead564e","name":"Summary Checker","type":"n8n-nodes-base.if","position":[400,540],"parameters":{"conditions":{"string":[{"value1":"={{$json[\"message\"][\"text\"]}}","value2":"/summary","operation":"startsWith"}]}},"typeVersion":1},{"id":"bb3faac2-e3cf-4633-8a69-4e6aedefd0be","name":"Fetcher","type":"n8n-nodes-base.httpRequest","position":[760,420],"parameters":{"url":"={{ $json.message.link_preview_options.url }}","options":{},"sendHeaders":true,"headerParameters":{"parameters":[{"name":"User-Agent","value":"Mozilla/5.0"}]}},"typeVersion":4.2},{"id":"7df71ce1-5680-46b5-a4fd-3fe3169aaaa5","name":"Text Extractor","type":"n8n-nodes-base.html","position":[1160,700],"parameters":{"options":{},"operation":"extractHtmlContent","extractionValues":{"values":[{"key":"text","cssSelector":"body","skipSelectors":"svg, a"}]}},"typeVersion":1.2},{"id":"f1856af1-7236-42f9-88b5-f86e91b42262","name":"Summarizer","type":"@n8n/n8n-nodes-langchain.openAi","position":[1520,440],"parameters":{"modelId":{"__rl":true,"mode":"list","value":""},"options":{},"messages":{"values":[{"content":"=Summarize the entire content provided below into 10–12 concise bullet points. Ensure each point captures a unique and important aspect of the information, covering the core ideas, key facts, major findings, and essential takeaways. Avoid repetition and use clear, professional language suitable for quick understanding by a decision-maker.\n\nContent:\n {{ $json.text }}"}]}},"typeVersion":1.8},{"id":"7fcdd8ab-1afa-4985-a9dd-bb9a13e723bf","name":"Summary Sender","type":"n8n-nodes-base.telegram","position":[2060,440],"webhookId":"c6f19898-b638-4e42-b377-d7664087ab0b","parameters":{"text":"={{$json[\"candidates\"][0][\"content\"][\"parts\"][0][\"text\"]}}","chatId":"={{ $('Listener').item.json.message.chat.id }}","additionalFields":{}},"typeVersion":1},{"id":"c4f73e58-995e-4a6a-a785-72e248121742","name":"Image Prompt Checker","type":"n8n-nodes-base.if","position":[800,1020],"parameters":{"conditions":{"string":[{"value1":"={{$json[\"message\"][\"text\"]}}","value2":"/img","operation":"startsWith"}]}},"typeVersion":1},{"id":"3115364c-3632-4922-82f9-93b45eb9fcb6","name":"Image Generator","type":"@n8n/n8n-nodes-langchain.openAi","position":[1400,1160],"parameters":{"options":{},"resource":"image"},"typeVersion":1.8},{"id":"7c01b0fa-7937-4688-945e-fc949c8a3f40","name":"Image Acknowledger","type":"n8n-nodes-base.telegram","position":[2000,820],"webhookId":"b5fb6529-a924-4885-8d6c-17073ce29bb0","parameters":{"text":"🖼️ Generated image prompt submitted! Gemini image model doesn't return images directly. Use image generation APIs like Stability for actual image URLs.","chatId":"={{$json[\"message\"][\"chat\"][\"id\"]}}","additionalFields":{}},"typeVersion":1},{"id":"e0eae618-d330-4b74-b5a4-528a28ec91c6","name":"Sticky Note12","type":"n8n-nodes-base.stickyNote","position":[-1260,220],"parameters":{"color":4,"width":480,"height":740,"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}],"connections":{"Fetcher":{"main":[[{"node":"Text Extractor","type":"main","index":0}]]},"Listener":{"main":[[{"node":"Command Router","type":"main","index":0}]]},"Summarizer":{"main":[[{"node":"Summary Sender","type":"main","index":0}]]},"Command Router":{"main":[[{"node":"Help Responder","type":"main","index":0}],[{"node":"Summary Checker","type":"main","index":0}]]},"Help Responder":{"main":[[{"node":"Command Router","type":"main","index":0}]]},"Text Extractor":{"main":[[{"node":"Summarizer","type":"main","index":0}]]},"Image Generator":{"main":[[{"node":"Image Acknowledger","type":"main","index":0}]]},"Summary Checker":{"main":[[{"node":"Fetcher","type":"main","index":0}],[{"node":"Image Prompt Checker","type":"main","index":0}]]},"Image Prompt Checker":{"main":[[{"node":"Image Generator","type":"main","index":0}]]}}}


name: AI YouTube Analytics Agent: Comment Analyzer & Insights Reporter
author_name: Yaron Been
author_username: yaron-nofluff
categories: []
created_at: 2025-05-28T14:26:13.676Z
updated_at: 2025-05-28T14:26:13.676Z
url: https://n8n.io/workflows/4459
scraped_at: 2025-07-06 21:16:30
description:
  Transform YouTube comments into actionable insights with automated AI analysis and professional email reports.

  This intelligent workflow monitors your Google Sheets for YouTube video IDs, fetches comments using YouTube API, performs comprehensive AI sentiment analysis, and delivers formatted email reports with viewer insights - helping content creators understand their audience and improve engagement.

  🚀 What It Does

  Smart Video Monitoring: Watches Google Sheets for new YouTube video IDs marked as "Pending" and triggers automated analysis

  Complete Comment Collection: Fetches up to 100 top comments per video using YouTube API with relevance-based ordering

  AI-Powered Analysis: Uses GPT-4 to analyze comments for sentiment, themes, questions, feedback, and actionable insights

  Professional Email Reports: Generates detailed HTML reports with statistics, sentiment breakdown, and improvement recommendations

  Automated Status Tracking: Updates spreadsheet status to prevent duplicate processing and maintain organized workflow

  🎯 Key Benefits

  ✅ Deep Audience Insights: Understand what viewers really think about your content  
  ✅ Save Hours of Manual Work: Automated comment analysis vs reading hundreds of comments  
  ✅ Improve Content Strategy: Get actionable feedback for better video performance  
  ✅ Track Sentiment Trends: Monitor positive/negative feedback patterns  
  ✅ Professional Reporting: Receive formatted analysis reports via email  
  ✅ Scalable Analysis: Process multiple videos automatically  

  🏢 Perfect For

  Content Creators & YouTubers
  Individual creators tracking audience engagement
  Educational channels analyzing learning feedback
  Entertainment creators understanding viewer preferences
  Business channels monitoring brand sentiment

  Marketing & Business Applications
  Brand Monitoring**: Track sentiment on branded content and partnerships
  Audience Research**: Understand viewer demographics and preferences  
  Content Optimization**: Identify what resonates with your audience
  Competitor Analysis**: Analyze comments on competitor videos (where allowed)

  ⚙️ What's Included

  Complete Analytics Workflow: Ready-to-deploy YouTube comment analysis system
  Google Sheets Integration: Simple spreadsheet-based video management
  YouTube API Integration: Automated comment fetching with proper authentication
  AI Analysis Engine: GPT-4 powered sentiment and insight generation
  Email Reporting System: Professional HTML-formatted reports
  Status Management: Automatic processing tracking and duplicate prevention

  🔧 Setup Requirements

  n8n Platform**: Cloud or self-hosted instance
  YouTube API Credentials**: Google Cloud Console API access
  OpenAI API**: GPT-4 access for comment analysis
  Google Sheets**: Video ID management and status tracking
  Gmail Account**: For receiving analysis reports

  📊 Required Google Sheets Structure

  | ID | Video Title | YouTube Video ID | Status |
  |----|-------------|------------------|---------|
  | 1  | My Tutorial | dQw4w9WgXcQ     | Pending |
  | 2  | Product Demo| abc123def456    | Mail Sent |
  | 3  | Weekly Vlog | xyz789uvw012    | Draft |

  Status Options: Draft → Pending → Mail Sent

  📧 Sample Analysis Report

  📺 YouTube Comments Analysis Report
  Video: "How to Build Your First Website"

  📊 Quick Statistics:
  • Total Comments Analyzed: 87
  • Average Likes per Comment: 3.2
  • Total Replies: 156
  • Sentiment Summary: Positive: 65%, Negative: 10%, Neutral: 25%

  ❓ Common Questions:
  • "What hosting service do you recommend?"
  • "Can I do this without coding experience?"
  • "How much does domain registration cost?"

  💡 Key Feedback Points:
  • Tutorial pace is perfect for beginners
  • More examples of finished websites requested
  • Viewers want follow-up video on advanced features

  🎯 Actionable Insights:
  • Create hosting comparison video
  • Add timestamps for different skill levels
  • Consider beginner-friendly series expansion

  🎨 Customization Options

  Analysis Depth: Adjust AI prompts for different analysis focuses (engagement, education, entertainment)
  Comment Limits: Modify maximum comments processed (default: 100, AI analysis: 50)
  Report Recipients: Send reports to multiple team members or clients
  Custom Metrics: Add specific analysis criteria for your content niche
  Multi-Channel: Process videos from multiple YouTube channels
  Scheduling: Set up regular analysis of your latest videos

  🏷️ Tags & Categories

  #youtube-analytics #comment-analysis #content-creator-tools #ai-sentiment-analysis #video-insights #audience-research #youtube-api #content-optimization #social-media-analytics #creator-economy #video-marketing #engagement-analysis #content-strategy #ai-reporting #youtube-automation

  💡 Use Case Examples

  Educational Channel: Analyze tutorial comments to identify confusing concepts and improve teaching methods
  Product Reviews: Monitor sentiment on review videos to understand customer satisfaction trends  
  Entertainment Creator: Track audience reactions to different content formats and optimize future videos

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

workflow_json:
  {"meta":{"instanceId":"5aaf4236c70e34e423fbdb2c7b754d19253a933bb1476d548f75848a01e473cf","templateCredsSetupCompleted":true},"nodes":[{"id":"e0eae618-d330-4b74-b5a4-528a28ec91c6","name":"Sticky Note12","type":"n8n-nodes-base.stickyNote","position":[-1260,220],"parameters":{"color":4,"width":480,"height":740,"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":"e73f0186-b1a7-4ab9-a23e-94a38d51f8bb","name":"Workflow Overview","type":"n8n-nodes-base.stickyNote","position":[-640,420],"parameters":{"color":2,"width":350,"height":820,"content":"# 📊 YouTube Comment Analyzer Workflow\n\n**Purpose:** Automate YouTube comment collection, sentiment analysis, and email reporting\n\n**Schedule:** Triggers every minute for new/updated rows\n\n**Required Setup:**\n1. Google Sheet with video IDs\n2. YouTube API credentials\n3. OpenAI API key\n4. Gmail account\n\n## Workflow Steps:\n1. **Trigger** - Monitor Google Sheet\n2. **Filter** - Process only 'Pending' videos\n3. **Fetch** - Get video details & comments\n4. **Analyze** - AI sentiment analysis\n5. **Report** - Send email summary\n6. **Update** - Mark as processed"},"typeVersion":1},{"id":"606f8cb5-54a5-4a90-be41-089d7ccae72f","name":"Trigger Documentation","type":"n8n-nodes-base.stickyNote","position":[-260,320],"parameters":{"color":3,"width":380,"height":340,"content":"## 🚀 Trigger Section\n\n**Google Sheets Trigger**\nMonitors the spreadsheet every minute for:\n- New video IDs added\n- Status changes to 'Pending'\n\n**Required Sheet Structure:**\n| ID | Video Title | YouTube Video ID | Status |\n\n⚠️ Set Status to 'Pending' to trigger analysis"},"typeVersion":1},{"id":"f225b68e-272e-4414-82c2-2f79cfbcc381","name":"YouTube API Section","type":"n8n-nodes-base.stickyNote","position":[560,440],"parameters":{"width":280,"height":200,"content":"## 📹 YouTube Data Collection\n\n**This section fetches:**\n- Video metadata (title, channel)\n- Top 100 comments\n- Comment statistics\n\n**API Limits:**\n- Max 100 comments per request\n- Ordered by relevance\n- Top-level comments only"},"typeVersion":1},{"id":"628d65ff-007c-4b7a-862e-64158fa80e7c","name":"AI Analysis Documentation","type":"n8n-nodes-base.stickyNote","position":[1300,420],"parameters":{"color":5,"width":320,"height":250,"content":"## 🤖 AI Analysis Section\n\n**GPT-4o analyzes comments for:**\n1. Sentiment breakdown (positive/negative/neutral)\n2. Main themes & topics\n3. Common viewer questions\n4. Key feedback points\n5. Actionable insights\n\n**Output Format:** Structured JSON with underscore keys\n\n💡 Customize the prompt in AI Agent node for different analysis needs"},"typeVersion":1},{"id":"85b58261-88e1-499a-a082-548713da293e","name":"Email & Status Update","type":"n8n-nodes-base.stickyNote","position":[1820,460],"parameters":{"color":4,"width":300,"height":220,"content":"## 📧 Email & Update Section\n\n**Email Report includes:**\n- Video statistics\n- Sentiment analysis\n- Key insights\n- Formatted HTML\n\n**Final Step:**\nUpdates Google Sheet status to 'Mail Sent' to prevent duplicate processing\n\n⚠️ Update recipient email in Gmail node"},"typeVersion":1},{"id":"e0ba6c37-8b04-406b-9158-aef610274135","name":"Data Processing Note","type":"n8n-nodes-base.stickyNote","position":[1060,900],"parameters":{"color":6,"width":250,"height":180,"content":"⚠️ **Data Preparation**\n\nThis node:\n- Extracts comment texts\n- Calculates statistics\n- Performs basic sentiment analysis\n- Prepares data for AI\n\nLimited to 50 comments for AI analysis to manage token usage"},"typeVersion":1},{"id":"d7edbd68-9213-426b-ae6b-71a13bb23690","name":"Limit","type":"n8n-nodes-base.limit","notes":"Limits processing to 1 item at a time to prevent API overload","position":[220,700],"parameters":{},"typeVersion":1},{"id":"42f0f581-57a0-438d-b1a1-29a89e984554","name":"AI Agent","type":"@n8n/n8n-nodes-langchain.agent","notes":"Uses OpenAI GPT-4o to analyze comments and generate insights. Customize the prompt for different analysis needs.","position":[1320,700],"parameters":{"text":"=Analyze these comments from the video \"{{ $json.videoTitle }}\":\n\nTotal Comments: {{ $json.totalComments }}\nAverage Likes: {{ $json.avgLikes }}\n\nComments to analyze:\n{{ $json.commentTexts }}","options":{"maxIterations":100,"systemMessage":"You are a YouTube comment analyst. Analyze the provided comments and return a structured analysis with:\n1. Overall sentiment breakdown (positive/negative/neutral percentages)\n2. Top 3-5 main themes or topics discussed\n3. Common questions from viewers\n4. Key feedback points and suggestions\n5. Actionable insights for content improvement\n\nFormat your response in clear sections with headers in json key value format and use underscore in the key name. Always use following keys for output json: \n1. overall_sentiment_breakdown\n2. main_themes\n3. common_questions\n4. key_feedback_points\n5. actionable_insights"},"promptType":"define"},"typeVersion":1.9},{"id":"35abbd58-e69a-4d86-963e-0a758aaff7b2","name":"OpenAI Chat Model","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[1420,920],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o-mini"},"options":{"responseFormat":"json_object"}},"typeVersion":1.2},{"id":"747fb13b-ee39-4dd7-8338-8db07e3b568e","name":"If","type":"n8n-nodes-base.if","notes":"Filters rows to process only videos with 'Pending' status","position":[0,700],"parameters":{"options":{},"conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"5f1eae10-5270-4e99-8627-597e3451c82c","operator":{"name":"filter.operator.equals","type":"string","operation":"equals"},"leftValue":"={{ $json.Status }}","rightValue":"Pending"}]}},"typeVersion":2.2},{"id":"6895d6b4-4ae4-4092-9302-33b1c69167d6","name":"Set Video Details","type":"n8n-nodes-base.set","notes":"Prepares video ID and sets max comments limit (100)","position":[440,700],"parameters":{"options":{},"assignments":{"assignments":[{"id":"219795ef-daa4-4444-9865-c5d3856be63b","name":"videoId","type":"string","value":"={{ $json['Youtube video id'] }}"},{"id":"cd4f519d-4c84-496c-8974-29ef69c890fc","name":"maxComments ","type":"number","value":100}]}},"typeVersion":3.4},{"id":"df200d75-d932-4bb4-9e57-16a940963db3","name":"Get Youtube Video Details","type":"n8n-nodes-base.youTube","notes":"Fetches video metadata including title, channel name, and other details","position":[660,700],"parameters":{"options":{},"videoId":"={{ $json.videoId }}","resource":"video","operation":"get"},"typeVersion":1},{"id":"5346229d-9386-497b-99c7-192e75896bf2","name":"Get Youtube Video Comments","type":"n8n-nodes-base.httpRequest","notes":"Retrieves top 100 comments ordered by relevance using YouTube API","position":[880,700],"parameters":{"url":"https://www.googleapis.com/youtube/v3/commentThreads","options":{},"sendQuery":true,"authentication":"predefinedCredentialType","queryParameters":{"parameters":[{"name":"part","value":"snippet"},{"name":"videoId","value":"={{ $('Set Video Details').item.json.videoId }}"},{"name":"maxResults","value":"100"},{"name":"order","value":"relevance"}]},"nodeCredentialType":"youTubeOAuth2Api"},"typeVersion":4.2},{"id":"ffee99ec-ad6d-4ac9-b0ad-e466a18ad7de","name":"Prepare Comments Data","type":"n8n-nodes-base.code","notes":"Processes raw comments: extracts text, calculates stats, performs basic sentiment analysis, limits to 50 comments for AI","position":[1100,700],"parameters":{"jsCode":"// Get comments from HTTP Request node\nconst comments = $input.first().json.items\n//const comments = response.items || [];\n\n// Get video title from the YouTube node (step 5)\n//const videoData = ;\nconst videoTitle = $('Get Youtube Video Details').first().json.snippet.title;\n\n// Extract comment data\nconst processedComments = comments.map(item => {\n  const comment = item.snippet.topLevelComment.snippet;\n  return {\n    text: comment.textDisplay,\n    author: comment.authorDisplayName,\n    likes: comment.likeCount || 0,\n    publishedAt: comment.publishedAt,\n    replyCount: item.snippet.totalReplyCount || 0\n  };\n});\n\n// Calculate statistics\nconst totalComments = processedComments.length;\nconst totalLikes = processedComments.reduce((sum, c) => sum + c.likes, 0);\nconst avgLikes = totalComments > 0 ? (totalLikes / totalComments).toFixed(2) : 0;\nconst totalReplies = processedComments.reduce((sum, c) => sum + c.replyCount, 0);\n\n// Get top comments by likes\nconst topComments = processedComments\n  .sort((a, b) => b.likes - a.likes)\n  .slice(0, 5);\n\n// Prepare comment texts for AI analysis\nconst commentTexts = processedComments\n  .slice(0, 50) // Limit to 50 comments for AI analysis\n  .map(c => c.text)\n  .join('\\n---\\n');\n\n// Basic sentiment analysis (count positive/negative keywords)\nconst positiveWords = ['love', 'great', 'awesome', 'amazing', 'excellent', 'good', 'fantastic', 'helpful', 'thanks'];\nconst negativeWords = ['hate', 'terrible', 'awful', 'bad', 'worst', 'horrible', 'useless', 'waste'];\n\nlet positiveCount = 0;\nlet negativeCount = 0;\n\nprocessedComments.forEach(comment => {\n  const lowerText = comment.text.toLowerCase();\n  positiveWords.forEach(word => {\n    if (lowerText.includes(word)) positiveCount++;\n  });\n  negativeWords.forEach(word => {\n    if (lowerText.includes(word)) negativeCount++;\n  });\n});\n\nreturn [{\n  json: {\n    videoTitle,\n    totalComments,\n    avgLikes,\n    totalReplies,\n    topComments,\n    commentTexts,\n    processedComments,\n    sentimentCounts: {\n      positive: positiveCount,\n      negative: negativeCount,\n      neutral: totalComments - positiveCount - negativeCount\n    }\n  }\n}];\n\n"},"typeVersion":2},{"id":"7eab55e1-e9e2-4750-a07d-f02941c7a8c6","name":"Prepare HTML for Email","type":"n8n-nodes-base.code","notes":"Converts AI analysis into formatted HTML email with statistics, insights, and professional styling","position":[1700,700],"parameters":{"mode":"runOnceForEachItem","jsCode":"const output = JSON.parse($json.output)\n //return output; \n//return output.overall_sentiment_breakdown.Positive;\n\nlet common_question = \"\";\n  \noutput.common_questions.map(rec => {\n  return common_question += \"<li>\"+rec.trim().replace(new RegExp(\".*,$\"), \"\")+\"</li>\"\n})\n\nlet key_feedback_points_and_suggestions = \"\";\n\noutput.key_feedback_points.map(rec => {\n  return key_feedback_points_and_suggestions += \"<li>\"+rec.trim().replace(new RegExp(\".*,$\"), \"\")+\"</li>\"\n})\n\n\nlet actionable_insights_for_content_improvement = \"\"\n\noutput.actionable_insights.map(rec => {\n  return actionable_insights_for_content_improvement += \"<li>\"+rec.trim().replace(new RegExp(\".*,$\"), \"\")+\"</li>\"\n})\n\n\n// return {common_question};\n\n\n     \n\n//return output; \n// Generate the email HTML\nconst emailHTML = `\n<!DOCTYPE html>\n<html>\n<head>\n  <style>\n    body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }\n    .header { background: #f4f4f4; padding: 20px; border-radius: 5px; }\n    .section { margin: 20px 0; }\n    .stats { background: #e9ecef; padding: 15px; border-radius: 5px; }\n    .analysis { background: #f8f9fa; padding: 20px; border-radius: 5px; }\n    h2 { color: #2c3e50; }\n    h3 { color: #34495e; }\n    h4 { color: #7f8c8d; }\n    .footer { margin-top: 30px; padding-top: 20px; border-top: 1px solid #ddd; color: #666; font-size: 0.9em; }\n  </style>\n</head>\n<body>\n  <div class=\"header\">\n    <h2>YouTube Comments Analysis Report</h2>\n    <h3>Video: ${$(\"Prepare Comments Data\").item.json.videoTitle}</h3>\n  </div>\n\n  <div class=\"section stats\">\n    <h3> Quick Statistics</h3>\n    <ul>\n      <li><strong>Total Comments Analyzed:</strong> ${$('Prepare Comments Data').item.json.totalComments}</li>\n      <li><strong>Average Likes per Comment:</strong> ${$('Prepare Comments Data').item.json.avgLikes}</li>\n      <li><strong>Total Replies:</strong> ${$('Prepare Comments Data').item.json.totalReplies}</li>\n      <li><strong>Sentiment Summary:</strong> \n        Positive: ${output.overall_sentiment_breakdown.positive}, \n        Negative: ${output.overall_sentiment_breakdown.negative}, \n        Neutral: ${output.overall_sentiment_breakdown.neutral}\n      </li>\n    </ul>\n  </div>\n\n  <div class=\"section stats\">\n    <h3>Common Questions</h3>\n    <ul>\n      ${common_question}\n    </ul>\n  </div>\n\n    <div class=\"section stats\">\n    <h3>Key feedback points and suggestions</h3>\n    <ul>\n      ${key_feedback_points_and_suggestions}\n    </ul>\n  </div>\n\n\n  <div class=\"section stats\">\n    <h3>Actionable insights for content improvement</h3>\n    <ul>\n      ${actionable_insights_for_content_improvement}\n    </ul>\n  </div>\n\n\n\n\n  <div class=\"footer\">\n    <p><em>Report generated on ${new Date().toLocaleString()}</em></p>\n    \n  </div>\n</body>\n</html>`;\n\n\n// Return the formatted data\nreturn  {\n  json: {\n    emailHTML,\n    subject: `YouTube Analysis: ${$('Prepare Comments Data').item.json.videoTitle} - ${$('Prepare Comments Data').item.json.totalComments} comments analyzed`,\n    videoTitle: $('Prepare Comments Data').item.json.videoTitle\n  }\n};"},"typeVersion":2},{"id":"f789c4e0-813b-4f6d-9584-86a274fba969","name":"Gmail Account Configuration","type":"n8n-nodes-base.gmail","notes":"Sends formatted analysis report via Gmail. Update SENDER_EMAIL_ADDRESS with actual recipient","position":[1920,700],"webhookId":"90b8f9ad-4226-42a0-971b-7fa9f5f190bd","parameters":{"sendTo":"SENDER_EMAIL_ADDRESS","message":"={{ $json.emailHTML }}","options":{},"subject":"={{ $json.subject }}"},"typeVersion":2.1},{"id":"309d2e7d-2da0-439b-b2ac-87196d9f5733","name":"Update Status on Google Sheet","type":"n8n-nodes-base.googleSheets","notes":"Updates video status to 'Mail Sent' to prevent duplicate processing","position":[2140,700],"parameters":{"columns":{"value":{"Id":"={{ $('Pick Video Ids from Google sheet').item.json.Id }}","Status":"Mail Sent"},"schema":[{"id":"Id","type":"string","display":true,"removed":false,"required":false,"displayName":"Id","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Youtube video id","type":"string","display":true,"required":false,"displayName":"Youtube video id","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Status","type":"string","display":true,"required":false,"displayName":"Status","defaultMatch":false,"canBeUsedToMatch":true},{"id":"row_number","type":"string","display":true,"removed":true,"readOnly":true,"required":false,"displayName":"row_number","defaultMatch":false,"canBeUsedToMatch":true}],"mappingMode":"defineBelow","matchingColumns":["Id"],"attemptToConvertTypes":false,"convertFieldsToString":false},"options":{},"operation":"update","sheetName":{"__rl":true,"mode":"list","value":"gid=0","cachedResultUrl":"GOOGLE_DRIVE_URL","cachedResultName":"Youtube_Video "},"documentId":{"__rl":true,"mode":"list","value":"1qe6Ovp_pfmwZA2k5c7LmmZx-OKqv3hnu8Dg80Pw4KoY","cachedResultUrl":"GOOGLE_DRIVE_URL","cachedResultName":"Youtube_Video"}},"typeVersion":4.5},{"id":"b62a4e3a-c843-4ed2-9ee4-cbfb1a218259","name":"Pick Video Ids from Google sheet","type":"n8n-nodes-base.googleSheetsTrigger","notes":"Triggers on new YouTube videos added to spreadsheet. Polls every minute for changes","position":[-220,700],"parameters":{"options":{},"pollTimes":{"item":[{"mode":"everyMinute"}]},"sheetName":{"__rl":true,"mode":"list","value":"gid=0","cachedResultUrl":"GOOGLE_DRIVE_URL","cachedResultName":"Youtube_Video "},"documentId":{"__rl":true,"mode":"list","value":"1qe6Ovp_pfmwZA2k5c7LmmZx-OKqv3hnu8Dg80Pw4KoY","cachedResultUrl":"GOOGLE_DRIVE_URL","cachedResultName":"Youtube_Video"}},"typeVersion":1}],"connections":{"If":{"main":[[{"node":"Limit","type":"main","index":0}]]},"Limit":{"main":[[{"node":"Set Video Details","type":"main","index":0}]]},"AI Agent":{"main":[[{"node":"Prepare HTML for Email","type":"main","index":0}]]},"OpenAI Chat Model":{"ai_languageModel":[[{"node":"AI Agent","type":"ai_languageModel","index":0}]]},"Set Video Details":{"main":[[{"node":"Get Youtube Video Details","type":"main","index":0}]]},"Prepare Comments Data":{"main":[[{"node":"AI Agent","type":"main","index":0}]]},"Prepare HTML for Email":{"main":[[{"node":"Gmail Account Configuration","type":"main","index":0}]]},"Get Youtube Video Details":{"main":[[{"node":"Get Youtube Video Comments","type":"main","index":0}]]},"Get Youtube Video Comments":{"main":[[{"node":"Prepare Comments Data","type":"main","index":0}]]},"Gmail Account Configuration":{"main":[[{"node":"Update Status on Google Sheet","type":"main","index":0}]]},"Pick Video Ids from Google sheet":{"main":[[{"node":"If","type":"main","index":0}]]}}}


name: Github Webhook-Based n8n Workflow Import Template
author_name: Dave Bernier
author_username: dbern
nodes_used: ["n8n-nodes-base.github"]
categories: []
created_at: 2025-05-28T21:24:41.338Z
updated_at: 2025-05-28T21:24:41.338Z
url: https://n8n.io/workflows/4471
scraped_at: 2025-07-06 21:16:30
description:
  This n8n workflow template uses community nodes and is only compatible with the self-hosted version of n8n. 

  This template aims to ease the process of deploying workflows from github. It has a companion repository that developers might find useful{. See below for more details

  How it works

  Automatically import and deploy n8n workflows from your GitHub repository to your production n8n instance using a secured webhook-based approach. This template enables teams to maintain version control of their workflows while ensuring seamless deployment through a CI/CD pipeline.

  Receives webhook notifications from GitHub when changes are pushed to your repository
  Lists all files in the repository and filters for .json workflow files
  Downloads each workflow file and saves it locally
  Imports all workflows into n8n using the CLI import command
  Cleans up temporary files after successful import

  To trigger the deployment, send a POST request to your webhook with the set up credentials (basic auth) with the following body:
  {
    "owner": "GITHUB_REPO_OWNER_NAME",
    "repository": "GITHUB_REPOSITORY_NAME"
  }

  Set up steps
  Once importing this template in n8n :
  Setup the webhook basic auth credentials
  Setup the github credentials
  Activate the workflow !

  Companion repository
  There is a companion repository located at https://github.com/dynamicNerdsSolutions/n8n-git-flow-template that has a Github action already setup to work with this workflow.

  It provides a complete development environment with:
  Local n8n instance via Docker
  Automated workflow export and commit scripts
  Version control integration
  CI/CD pipeline setup

  This setup allows teams to maintain a clean separation between development and production environments while ensuring reliable workflow deployment.

workflow_json:
  {"nodes":[{"id":"6dcae6fd-9631-4f73-985c-31c08cfba106","name":"Webhook","type":"n8n-nodes-base.webhook","position":[-200,-45],"webhookId":"182bd0f4-bab3-4d3f-8341-773c2af24107","parameters":{"path":"import-workflows","options":{},"httpMethod":"POST","responseMode":"lastNode","authentication":"basicAuth"},"credentials":{"httpBasicAuth":{"id":"0sXvlBjKe1sDOYj0","name":"Github action user"}},"typeVersion":2},{"id":"62de08a4-db11-4602-9e4b-756fdecd2809","name":"No Operation, do nothing","type":"n8n-nodes-base.noOp","position":[900,-20],"parameters":{},"typeVersion":1},{"id":"faff0550-2ddd-4903-a2c2-c6081cf3098e","name":"create workflows sub folder if not exist","type":"n8n-nodes-base.executeCommand","position":[20,-45],"parameters":{"command":"mkdir -p workflows"},"typeVersion":1},{"id":"2b9a3378-f36a-4a25-bcc1-82fa403b85a7","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[-740,-300],"parameters":{"color":6,"width":520,"height":500,"content":"# Github import\nThis webhook is secured with a basic authentication credential. Make sure to edit it to values you own.\n\nThe webhook receives the github owner and repository from whitch it should import the workflows.\n\nIt will download all json files into a local directory and call the n8n cli to import them.\n\nThere is a companion developement template on github that complements this flow, including the Github Action that can call this workflow. You can get it from here: https://github.com/dynamicNerdsSolutions/n8n-git-flow-template\n\n## First step :\nCreate the credentials for the webhook authentication and github."},"typeVersion":1},{"id":"9143f124-30b5-4a55-b3b7-03cd3c4fdfe8","name":"List files from specified repo root","type":"n8n-nodes-base.github","position":[240,-45],"webhookId":"b04d7d0c-b721-4d30-b4bd-29ed04f5ac9d","parameters":{"owner":{"__rl":true,"mode":"name","value":"={{ $('Webhook').item.json.body.owner }}"},"resource":"file","operation":"list","repository":{"__rl":true,"mode":"name","value":"={{ $('Webhook').item.json.body.repository }}"}},"credentials":{"githubApi":{"id":"Nx9eJjTiUfwyntOr","name":"GitHub account"}},"typeVersion":1.1},{"id":"f28d4f42-e7a0-4a25-8d1e-44de3a04f11a","name":"Loop Over Files","type":"n8n-nodes-base.splitInBatches","position":[460,-40],"parameters":{"options":{}},"typeVersion":3},{"id":"64d6aeac-bc11-4204-bea5-7f678fddf2b7","name":"If it is a json file","type":"n8n-nodes-base.if","position":[680,-120],"parameters":{"options":{},"conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"8ad03c7c-1820-4f9e-998c-a209cc829ea3","operator":{"name":"filter.operator.equals","type":"string","operation":"equals"},"leftValue":"={{ $json.type }}","rightValue":"file"},{"id":"1a26b68e-91d6-468b-aed5-db0e4cee0f74","operator":{"type":"string","operation":"endsWith"},"leftValue":"={{ $json.name }}","rightValue":".json"}]}},"typeVersion":2.2},{"id":"8c4f7bcc-0c3c-4333-a39e-51d29be43c87","name":"Download file","type":"n8n-nodes-base.github","position":[900,-220],"webhookId":"ec903eb1-d4be-4332-8e28-7f384479336a","parameters":{"owner":{"__rl":true,"mode":"name","value":"={{ $('Webhook').item.json.body.owner }}"},"filePath":"={{ $json.path }}","resource":"file","operation":"get","repository":{"__rl":true,"mode":"name","value":"={{ $('Webhook').item.json.body.repository }}"},"additionalParameters":{}},"credentials":{"githubApi":{"id":"Nx9eJjTiUfwyntOr","name":"GitHub account"}},"typeVersion":1.1},{"id":"27ee1e73-66d5-4c86-a6ea-6be4786bc97e","name":"Store file locally","type":"n8n-nodes-base.readWriteFile","position":[1140,-60],"parameters":{"options":{},"fileName":"=workflows/{{ $json.name }}","operation":"write"},"typeVersion":1},{"id":"3a2a58ae-2f8f-447a-8a95-073d1f5575d6","name":"Call n8n import and cleanup folder","type":"n8n-nodes-base.executeCommand","position":[680,-320],"parameters":{"command":"n8n import:workflow --separate --input=workflows && rm -f ./workflows/*.json"},"typeVersion":1}],"connections":{"Webhook":{"main":[[{"node":"create workflows sub folder if not exist","type":"main","index":0}]]},"Download file":{"main":[[{"node":"Store file locally","type":"main","index":0}]]},"Loop Over Files":{"main":[[{"node":"Call n8n import and cleanup folder","type":"main","index":0}],[{"node":"If it is a json file","type":"main","index":0}]]},"Store file locally":{"main":[[{"node":"Loop Over Files","type":"main","index":0}]]},"If it is a json file":{"main":[[{"node":"Download file","type":"main","index":0}],[{"node":"No Operation, do nothing","type":"main","index":0}]]},"No Operation, do nothing":{"main":[[{"node":"Loop Over Files","type":"main","index":0}]]},"List files from specified repo root":{"main":[[{"node":"Loop Over Files","type":"main","index":0}]]},"create workflows sub folder if not exist":{"main":[[{"node":"List files from specified repo root","type":"main","index":0}]]}}}


name: Automate Multi-Channel Customer Support with Gmail, Telegram, and GPT AI
author_name: RedOne
author_username: redone
categories: []
created_at: 2025-05-29T05:09:06.053Z
updated_at: 2025-05-29T05:09:06.053Z
url: https://n8n.io/workflows/4474
scraped_at: 2025-07-06 21:16:30
description:
  Smart Customer Support AI Agent with Gmail and Telegram

  Who is this for?

  This workflow is perfect for:
  Small to medium businesses** looking to automate customer support
  E-commerce stores** handling order inquiries and customer questions
  SaaS companies** providing technical support to users
  Service providers** managing appointment bookings and general inquiries
  Startups** wanting to provide 24/7 customer service without hiring full-time staff
  Agencies** managing client communications across multiple channels

  What problem is this workflow solving?

  Customer support is essential but resource-intensive. Common challenges include:
  Slow response times** leading to frustrated customers
  Repetitive questions** consuming valuable staff time
  Inconsistent responses** across different support agents
  Limited availability** outside business hours
  Scaling support costs** as business grows
  Context loss** when customers switch between channels

  This workflow eliminates these pain points by providing instant, consistent, and intelligent responses 24/7.

  What this workflow does

  Core Functionality
  Multi-Channel Monitoring: Simultaneously watches Gmail and Telegram for customer inquiries
  Intelligent Processing: Uses AI to understand customer intent and context
  Knowledge Base Integration: Accesses your company's FAQ and support information
  Contextual Responses: Provides personalized, helpful replies maintaining conversation history
  Smart Escalation: Automatically escalates complex issues to human agents
  Comprehensive Logging: Tracks all interactions for analytics and improvement

  AI Agent Capabilities
  Natural Language Understanding**: Comprehends customer questions in plain English
  Context Awareness**: Remembers previous conversations with each customer
  Knowledge Retrieval**: Searches your knowledge base for accurate information
  Response Generation**: Creates professional, brand-appropriate responses
  Escalation Decision**: Identifies when human intervention is needed
  Multi-Channel Support**: Handles Gmail and Telegram with channel-specific formatting

  Automation Features
  Auto-Response**: Replies to customers within seconds
  Email Management**: Marks processed emails as read
  Conversation Threading**: Maintains context in email threads and Telegram chats
  Error Handling**: Gracefully handles failures with admin notifications
  Analytics Tracking**: Logs interactions for performance monitoring

  Setup

  Prerequisites
  Active Google Workspace or Gmail account
  Telegram account for bot creation
  OpenAI API access
  Google Sheets access
  n8n instance (cloud or self-hosted)

  Step 1: Credential Setup

  Gmail OAuth2 Configuration
  Go to Google Cloud Console
  Create new project or select existing one
  Enable Gmail API
  Create OAuth 2.0 credentials
  Add authorized redirect URIs for n8n
  In n8n: Settings → Credentials → Add Gmail OAuth2
  Enter Client ID and Client Secret
  Complete OAuth flow

  Telegram Bot Setup
  Message @BotFather on Telegram
  Create new bot with /newbot command
  Choose bot name and username
  Copy the bot token
  In n8n: Settings → Credentials → Add Telegram
  Enter bot token
  Set webhook URL in bot settings

  OpenAI API Configuration
  Sign up at OpenAI Platform
  Generate API key in API Keys section
  In n8n: Settings → Credentials → Add OpenAI
  Enter API key
  Choose appropriate model (gpt-4o-mini recommended)

  Google Sheets Setup
  Use existing Google account from Gmail setup
  In n8n: Settings → Credentials → Add Google Sheets OAuth2
  Complete authorization flow

  Step 2: Google Sheets Preparation

  Create three Google Sheets in your Google Drive:

  Knowledge Base Sheet
  Sheet Name**: "Knowledge Base"
  Columns**: ID, Category, Question/Topic, Answer/Response, Keywords, Last_Updated
  Import sample data from the Knowledge Base example
  Customize with your company's FAQs and policies

  Escalation Tracker Sheet
  Sheet Name**: "Escalations" 
  Columns**: Timestamp, Customer_Name, Customer_Contact, Inquiry_Summary, Escalation_Reason, Priority, Status, Assigned_To
  This will be auto-populated by the AI agent

  Interaction Log Sheet
  Sheet Name**: "Interaction Log"
  Columns**: Timestamp, Channel, Customer_Name, Customer_Contact, Inquiry_Subject, Customer_Message, AI_Response, Response_Time, Status
  This tracks all customer interactions for analytics

  Step 3: Workflow Configuration

  Import Template
  Copy the workflow JSON from the template
  In n8n: Import workflow from JSON
  Replace placeholder Sheet IDs with your actual Google Sheet IDs

  Update Sheet References
  Open each Google Sheets node
  Select your created sheets from the dropdown
  Verify column mappings match your sheet structure

  Customize AI Prompts
  Edit the "Customer Support AI Agent" node
  Update system message with:
     Your company name and description
     Brand voice and tone guidelines
     Specific policies and procedures
     Escalation criteria

  Configure Error Notifications (Optional)
  Set up Slack webhook or email notifications
  Update error notification node with your webhook URL
  Customize error message format

  Step 4: Testing

  Test Gmail Integration
  Send test email to your support Gmail account
  Check workflow execution in n8n
  Verify response is sent and email marked as read
  Check interaction logging in Google Sheets

  Test Telegram Integration  
  Send message to your Telegram bot
  Verify bot responds appropriately
  Test conversation memory with follow-up messages
  Check escalation functionality with complex request

  Test Knowledge Base
  Ask questions covered in your knowledge base
  Verify AI retrieves and uses correct information
  Test with variations of the same question
  Ensure responses are consistent and helpful

  How to customize this workflow to your needs

  Brand Voice Customization
  Update the AI system prompt to include:
  Your company's tone (formal, casual, friendly)
  Key phrases and terminology you use
  Brand personality traits
  Communication style preferences

  Knowledge Base Expansion
  Add industry-specific FAQs
  Include product documentation
  Add troubleshooting guides
  Create category-specific responses

  Escalation Rules
  Customize when to escalate by modifying the AI agent instructions:
  Billing disputes over $X amount
  Technical issues requiring developer help
  Angry or dissatisfied customers
  Requests outside standard services
  Legal or compliance questions

  Additional Channels
  Extend the workflow to support:
  Slack**: Add Slack triggers and response nodes
  WhatsApp**: Integrate WhatsApp Business API
  Web Chat**: Add webhook triggers for website chat
  Discord**: Connect Discord bot integration

  Analytics Enhancement
  Add sentiment analysis to customer messages
  Implement customer satisfaction scoring
  Create automated reporting dashboards
  Set up alert thresholds for escalation rates

  Integration Opportunities
  CRM Integration**: Connect to HubSpot, Salesforce, or Pipedrive
  Ticketing System**: Link to Zendesk, Freshdesk, or Jira Service Desk
  E-commerce Platform**: Integrate with Shopify, WooCommerce, or Magento
  Calendar Booking**: Connect to Calendly or Acuity for appointment scheduling

  Advanced Features
  Multi-language Support**: Add translation capabilities
  Voice Messages**: Integrate speech-to-text for Telegram voice notes
  Image Recognition**: Process customer screenshots for technical support
  Proactive Outreach**: Send follow-up messages based on customer behavior

  Workflow Maintenance

  Daily Tasks
  Review escalation queue
  Monitor error notifications
  Check response quality in interaction log

  Weekly Reviews
  Analyze customer interaction patterns
  Update knowledge base with new common questions
  Review escalation reasons and optimize AI prompts

  Monthly Optimization
  Export interaction data for detailed analysis
  Calculate key metrics (response time, resolution rate, escalation rate)
  Update AI model parameters based on performance
  Expand knowledge base with seasonal or trending topics

  Key Metrics to Track

  Response Time**: Average time from customer message to AI response
  Resolution Rate**: Percentage of inquiries resolved without escalation  
  Customer Satisfaction**: Based on follow-up surveys or sentiment analysis
  Escalation Rate**: Percentage of conversations requiring human intervention
  Channel Performance**: Effectiveness of Gmail vs Telegram vs other channels
  Knowledge Base Usage**: Which topics are accessed most frequently
  Peak Hours**: When customers contact support most often

  Troubleshooting

  Common Issues
  Gmail not triggering**: Check OAuth permissions and API quotas
  Telegram bot not responding**: Verify bot token and webhook configuration
  AI responses seem off**: Review and update system prompts
  Escalations not logging**: Check Google Sheets permissions and column mapping
  High escalation rate**: Expand knowledge base and refine AI instructions

  Performance Optimization
  Monitor OpenAI API usage and costs
  Adjust AI model temperature for response consistency
  Optimize knowledge base for faster searches
  Set appropriate conversation memory limits

  This workflow provides a solid foundation for automated customer support that can be extensively customized to match your specific business needs and grow with your company.

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

workflow_json:
  {"id":"iYX4vUmfNoVCA86T","meta":{"instanceId":"1037e065dca107c3c15857d49fe150792779e136a3c579aed02192a2b3d2a396","templateCredsSetupCompleted":true},"name":"🤖 Smart Customer Support AI Agent","tags":[],"nodes":[{"id":"696a1b2e-8f22-46ec-8fdd-3c7bb25f8429","name":"📋 Workflow Guide","type":"n8n-nodes-base.stickyNote","position":[1040,660],"parameters":{"color":6,"width":400,"height":1040,"content":"## 🤖 Smart Customer Support AI Agent\n\n**Who is this for?**\nSmall to medium businesses, e-commerce stores, SaaS companies, and service providers who want to automate their customer support while maintaining a personal touch.\n\n**What problem does this solve?**\n- Reduces response time to customer inquiries\n- Handles repetitive questions automatically\n- Provides 24/7 customer support coverage\n- Maintains consistent brand voice across channels\n- Escalates complex issues to human agents\n\n**What this workflow does:**\n1. Monitors Gmail and Telegram for customer messages\n2. Uses AI to understand customer intent and context\n3. Accesses your knowledge base (Google Sheets) for accurate responses\n4. Sends personalized, contextual replies\n5. Escalates complex issues to human agents\n6. Logs all interactions for analysis\n\n**FIXES APPLIED:**\n- Separated Gmail and Telegram processing paths\n- Individual AI agents for each channel\n- Proper conversation memory management\n- Channel-specific response handling\n\n**Setup Instructions:**\n1. Configure Gmail OAuth2 credentials\n2. Set up Telegram bot token\n3. Create your knowledge base in Google Sheets\n4. Add your OpenAI API key\n5. Customize the AI prompts for your business\n6. Test with sample customer inquiries\n\n**Customization Tips:**\n- Update the knowledge base with your FAQs\n- Modify AI prompts to match your brand voice\n- Add more communication channels as needed\n- Set up escalation rules for complex cases"},"typeVersion":1},{"id":"47324b70-8be7-4e92-a739-2ff60f37d14a","name":"💬 Telegram Customer Message Trigger","type":"n8n-nodes-base.telegramTrigger","position":[1500,1220],"webhookId":"customer-support-telegram","parameters":{"updates":["message"],"additionalFields":{}},"credentials":{"telegramApi":{"id":"RIK7bBarkKBJAV5R","name":"Telegram account"}},"typeVersion":1.1},{"id":"23ce0479-3ab0-4150-b893-3e08ed83fd73","name":"📋 Process Telegram Message","type":"n8n-nodes-base.set","position":[1780,1240],"parameters":{"options":{},"assignments":{"assignments":[{"id":"channel","name":"channel","type":"string","value":"telegram"},{"id":"customer_name","name":"customer_name","type":"string","value":"={{ $json.message.from.first_name }} {{ $json.message.from.last_name }}"},{"id":"customer_id","name":"customer_id","type":"string","value":"={{ $json.message.from.id }}"},{"id":"chat_id","name":"chat_id","type":"string","value":"={{ $json.message.chat.id }}"},{"id":"message_content","name":"message_content","type":"string","value":"={{ $json.message.text }}"},{"id":"message_id","name":"message_id","type":"string","value":"={{ $json.message.message_id }}"},{"id":"subject","name":"subject","type":"string","value":"Customer Support Inquiry"}]}},"typeVersion":3.4},{"id":"686affeb-1afb-45cf-b9b0-f3ba6c6ffb94","name":"🤖 Telegram AI Agent","type":"@n8n/n8n-nodes-langchain.agent","position":[2080,1180],"parameters":{"text":"={{ $json.message_content}}","options":{"systemMessage":"You are a helpful and professional customer support AI assistant for Telegram inquiries. Your role is to:\n\n1. Understand customer inquiries and provide accurate, helpful responses\n2. Use the knowledge base tool to find relevant information\n3. Maintain a friendly, professional tone that matches the company brand\n4. If you cannot fully resolve an issue, escalate it appropriately\n5. Always aim to provide value and resolve customer concerns\n\nImportant guidelines:\n- Be empathetic and understanding\n- Provide clear, actionable responses\n- Use the customer's name when possible\n- If information is not in the knowledge base, say so honestly\n- For complex technical issues, recommend escalation to human support\n\nCompany context: You represent a professional service business focused on customer satisfaction and quality support via Telegram."},"promptType":"define"},"typeVersion":1.7},{"id":"a5e67d73-73c2-4756-9c82-9c05c1dbc36a","name":"🧠 OpenAI Chat Model - Telegram","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[1900,1420],"parameters":{"options":{"maxTokens":100,"temperature":0.3}},"credentials":{"openAiApi":{"id":"IdjfTMR7gLjapSWH","name":"Open Ai"}},"typeVersion":1.1},{"id":"bfa0f8a9-58cc-4c15-8d7e-d633c23e10a6","name":"🧠 Telegram Memory","type":"@n8n/n8n-nodes-langchain.memoryBufferWindow","position":[2080,1440],"parameters":{"sessionKey":"telegram_{{ $json.customer_id }}","sessionIdType":"customKey"},"typeVersion":1.3},{"id":"64a05368-29f5-4333-b881-b0ba73e424cb","name":"💬 Send Telegram Reply","type":"n8n-nodes-base.telegram","position":[2460,1120],"parameters":{"text":"={{ $json.output }}","chatId":"={{ $('📋 Process Telegram Message').item.json.chat_id }}","additionalFields":{"parse_mode":"Markdown","reply_to_message_id":"={{ $('📋 Process Telegram Message').item.json.message_id }}"}},"credentials":{"telegramApi":{"id":"RIK7bBarkKBJAV5R","name":"Telegram account"}},"typeVersion":1.2},{"id":"64c36c02-b56d-45dd-b3bf-4f49b3e14b5c","name":"📧 Gmail Customer Inquiry Trigger","type":"n8n-nodes-base.gmailTrigger","position":[1540,720],"parameters":{"filters":{"labelIds":["INBOX","CATEGORY_PERSONAL"],"readStatus":"unread"},"pollTimes":{"item":[{"mode":"everyMinute"}]}},"credentials":{"gmailOAuth2":{"id":"YQWc9jqYGygA6lXT","name":"Gmail account"}},"typeVersion":1},{"id":"baf01d18-d626-4b5c-bbc9-ac45c83b8e0b","name":"📋 Process Gmail Message","type":"n8n-nodes-base.set","position":[1740,720],"parameters":{"options":{},"assignments":{"assignments":[{"id":"channel","name":"channel","type":"string","value":"gmail"},{"id":"customer_email","name":"customer_email","type":"string","value":"={{ $json[\"From\"].match(/<(.*?)>/)?.[1] || $json[\"From\"] }}"},{"id":"customer_name","name":"customer_name","type":"string","value":"={{ $json[\"From\"].split(\" <\")[0] }}"},{"id":"subject","name":"subject","type":"string","value":"={{ $json.Subject }}"},{"id":"message_content","name":"message_content","type":"string","value":"={{ $json.text || $json.snippet }}"},{"id":"message_id","name":"message_id","type":"string","value":"={{ $json.id }}"},{"id":"thread_id","name":"thread_id","type":"string","value":"={{ $json.threadId }}"}]}},"typeVersion":3.4},{"id":"4d1c0b8a-9fed-4977-8ec4-91cb4460c2b6","name":"🤖 Gmail AI Agent","type":"@n8n/n8n-nodes-langchain.agent","position":[1940,720],"parameters":{"text":"={{ $json.message_content}}","options":{"systemMessage":"You are a helpful and professional customer support AI assistant for Email inquiries. Your role is to:\n\n1. Understand customer inquiries and provide accurate, helpful responses\n2. Use the knowledge base tool to find relevant information\n3. Maintain a friendly, professional tone that matches the company brand\n4. If you cannot fully resolve an issue, escalate it appropriately\n5. Always aim to provide value and resolve customer concerns\n\nImportant guidelines:\n- Be empathetic and understanding\n- Provide clear, actionable responses\n- Use the customer's name when possible\n- If information is not in the knowledge base, say so honestly\n- For complex technical issues, recommend escalation to human support\n- Format responses appropriately for email\n\nCompany context: You represent a professional service business focused on customer satisfaction and quality support via Email."},"promptType":"define"},"typeVersion":1.7},{"id":"8da4c0b1-86b7-436b-8d73-e96d3777be29","name":"🧠 OpenAI Chat Model - Gmail","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[1900,900],"parameters":{"options":{"maxTokens":1000,"temperature":0.3}},"credentials":{"openAiApi":{"id":"IdjfTMR7gLjapSWH","name":"Open Ai"}},"typeVersion":1.1},{"id":"b4cb3e8b-3d5c-49fb-9cc2-f46ffe4cd683","name":"🧠 Gmail Memory","type":"@n8n/n8n-nodes-langchain.memoryBufferWindow","position":[2040,980],"parameters":{"sessionKey":"gmail_{{ $json.customer_email }}","sessionIdType":"customKey"},"typeVersion":1.3},{"id":"442e8879-e6c3-4cd6-8f3b-3f64879047c1","name":"📧 Send Gmail Reply","type":"n8n-nodes-base.gmail","position":[2240,720],"webhookId":"c09e3c26-5430-4b47-864d-2344b636fa4e","parameters":{"message":"={{ $json.output }}","options":{"ccList":"","bccList":"","replyToSenderOnly":true},"messageId":"={{ $('📋 Process Gmail Message').item.json.message_id }}","operation":"reply"},"credentials":{"gmailOAuth2":{"id":"YQWc9jqYGygA6lXT","name":"Gmail account"}},"typeVersion":2},{"id":"668afdd0-f68b-45cb-afde-93ebaf7627d3","name":"✅ Mark Gmail as Read","type":"n8n-nodes-base.gmail","position":[2480,620],"webhookId":"3bae576f-ba6e-4ee2-a389-82171a9101d8","parameters":{"messageId":"={{ $('📋 Process Gmail Message').item.json.message_id }}","operation":"markAsRead"},"credentials":{"gmailOAuth2":{"id":"YQWc9jqYGygA6lXT","name":"Gmail account"}},"typeVersion":2},{"id":"2233ac1c-b704-4485-a4dd-3d873fb04538","name":"📊 Log Gmail Interaction","type":"n8n-nodes-base.googleSheets","position":[2540,820],"parameters":{"columns":{"value":{"Status":"Completed","Channel":"Email","Timestamp":"={{ new Date().toISOString() }}","AI_Response":"={{ $('🤖 Gmail AI Agent').item.json.output }}","Customer_Name":"={{ $('📋 Process Gmail Message').item.json.customer_name }}","Response_Time":"={{ new Date().toISOString() }}","Inquiry_Subject":"={{ $json.subject || 'General Inquiry' }}","Customer_Contact":"={{ $('📋 Process Gmail Message').item.json.customer_email }}","Customer_Message":"={{ $('📋 Process Gmail Message').item.json.message_content }}"},"schema":[{"id":"Timestamp","type":"string","display":true,"required":false,"displayName":"Timestamp","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Channel","type":"string","display":true,"required":false,"displayName":"Channel","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Customer_Name","type":"string","display":true,"required":false,"displayName":"Customer_Name","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Customer_Contact","type":"string","display":true,"required":false,"displayName":"Customer_Contact","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Inquiry_Subject","type":"string","display":true,"required":false,"displayName":"Inquiry_Subject","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Customer_Message","type":"string","display":true,"required":false,"displayName":"Customer_Message","defaultMatch":false,"canBeUsedToMatch":true},{"id":"AI_Response","type":"string","display":true,"required":false,"displayName":"AI_Response","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Response_Time","type":"string","display":true,"required":false,"displayName":"Response_Time","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Status","type":"string","display":true,"required":false,"displayName":"Status","defaultMatch":false,"canBeUsedToMatch":true}],"mappingMode":"defineBelow","matchingColumns":[],"attemptToConvertTypes":false,"convertFieldsToString":false},"options":{},"operation":"append","sheetName":{"__rl":true,"mode":"list","value":1087576053,"cachedResultUrl":"https://docs.google.com/spreadsheets/d/1rEZ1A0Gd5ejT_b2F5tcYy9Xk4i0JvTrjss_oolf6WD8/edit#gid=1087576053","cachedResultName":"AI_Responses"},"documentId":{"__rl":true,"mode":"list","value":"1rEZ1A0Gd5ejT_b2F5tcYy9Xk4i0JvTrjss_oolf6WD8","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1rEZ1A0Gd5ejT_b2F5tcYy9Xk4i0JvTrjss_oolf6WD8/edit?usp=drivesdk","cachedResultName":"customer_support_knowledge_base"}},"credentials":{"googleSheetsOAuth2Api":{"id":"ubQXdpluCtk0bGFi","name":"Google Sheets account"}},"typeVersion":4.2},{"id":"6e641113-9da3-430c-873d-59fd0c2997fb","name":"📊 Log Telegram Interaction","type":"n8n-nodes-base.googleSheets","position":[2760,960],"parameters":{"columns":{"value":{"Status":"Completed","Channel":"={{ $('📋 Process Telegram Message').item.json.channel }}","Timestamp":"={{ new Date().toISOString() }}","AI_Response":"={{ $json.output }}","Customer_Name":"={{ $('📋 Process Telegram Message').item.json.customer_name }}","Response_Time":"={{ new Date().toISOString() }}","Inquiry_Subject":"={{ $('📋 Process Telegram Message').item.json.subject }}","Customer_Contact":"={{ $('📋 Process Telegram Message').item.json.customer_id }}","Customer_Message":"={{ $('📋 Process Telegram Message').item.json.message_content }}"},"schema":[{"id":"Timestamp","type":"string","display":true,"required":false,"displayName":"Timestamp","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Channel","type":"string","display":true,"required":false,"displayName":"Channel","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Customer_Name","type":"string","display":true,"required":false,"displayName":"Customer_Name","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Customer_Contact","type":"string","display":true,"required":false,"displayName":"Customer_Contact","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Inquiry_Subject","type":"string","display":true,"required":false,"displayName":"Inquiry_Subject","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Customer_Message","type":"string","display":true,"required":false,"displayName":"Customer_Message","defaultMatch":false,"canBeUsedToMatch":true},{"id":"AI_Response","type":"string","display":true,"required":false,"displayName":"AI_Response","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Response_Time","type":"string","display":true,"required":false,"displayName":"Response_Time","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Status","type":"string","display":true,"required":false,"displayName":"Status","defaultMatch":false,"canBeUsedToMatch":true}],"mappingMode":"defineBelow","matchingColumns":[],"attemptToConvertTypes":false,"convertFieldsToString":false},"options":{},"operation":"append","sheetName":{"__rl":true,"mode":"list","value":1087576053,"cachedResultUrl":"https://docs.google.com/spreadsheets/d/1rEZ1A0Gd5ejT_b2F5tcYy9Xk4i0JvTrjss_oolf6WD8/edit#gid=1087576053","cachedResultName":"AI_Responses"},"documentId":{"__rl":true,"mode":"list","value":"1rEZ1A0Gd5ejT_b2F5tcYy9Xk4i0JvTrjss_oolf6WD8","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1rEZ1A0Gd5ejT_b2F5tcYy9Xk4i0JvTrjss_oolf6WD8/edit?usp=drivesdk","cachedResultName":"customer_support_knowledge_base"}},"credentials":{"googleSheetsOAuth2Api":{"id":"ubQXdpluCtk0bGFi","name":"Google Sheets account"}},"typeVersion":4.2},{"id":"50ded0f7-2513-4515-8843-e24cb50c89ae","name":"⚠️ Error Handling Info","type":"n8n-nodes-base.stickyNote","position":[3100,980],"parameters":{"width":300,"height":280,"content":"## 🚨 Error Handling\n\nThis section handles any errors that occur during the workflow execution and notifies the admin team.\n\n**Features:**\n- Captures all workflow errors\n- Sends notifications to admin\n- Logs errors for debugging\n- Provides fallback responses"},"typeVersion":1},{"id":"8634105f-1844-4e58-97f3-07697d86ac48","name":"🚨 Error Trigger","type":"n8n-nodes-base.errorTrigger","position":[2760,1300],"parameters":{},"typeVersion":1},{"id":"807781dc-c1ac-4bca-b298-420a3a3d5c2c","name":"📢 Notify Admin of Error","type":"n8n-nodes-base.httpRequest","position":[3020,1300],"parameters":{"url":"https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK","method":"POST","options":{},"sendBody":true,"bodyParameters":{"parameters":[{"name":"text","value":"🚨 Customer Support AI Error Alert\n\nWorkflow: Smart Customer Support AI\nError: {{ $json.error.message }}\nNode: {{ $json.error.node.name }}\nTime: {{ new Date().toISOString() }}\n\nPlease check the workflow execution for details."}]}},"typeVersion":4.2},{"id":"4581974a-7e7c-4b61-b5c7-a6023ef931d0","name":"Gmail Escalation Logger","type":"n8n-nodes-base.googleSheetsTool","position":[2300,920],"parameters":{"options":{},"sheetName":{"__rl":true,"mode":"list","value":1478316494,"cachedResultUrl":"https://docs.google.com/spreadsheets/d/1rEZ1A0Gd5ejT_b2F5tcYy9Xk4i0JvTrjss_oolf6WD8/edit#gid=1478316494","cachedResultName":"Customer_Inquiries"},"documentId":{"__rl":true,"mode":"list","value":"1rEZ1A0Gd5ejT_b2F5tcYy9Xk4i0JvTrjss_oolf6WD8","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1rEZ1A0Gd5ejT_b2F5tcYy9Xk4i0JvTrjss_oolf6WD8/edit?usp=drivesdk","cachedResultName":"customer_support_knowledge_base"}},"credentials":{"googleSheetsOAuth2Api":{"id":"ubQXdpluCtk0bGFi","name":"Google Sheets account"}},"typeVersion":4.5},{"id":"d9f13fc4-0a68-4bee-a36f-67e779bef7fe","name":"knowledge base","type":"n8n-nodes-base.googleSheetsTool","position":[2180,1000],"parameters":{"options":{},"sheetName":{"__rl":true,"mode":"list","value":"gid=0","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1rEZ1A0Gd5ejT_b2F5tcYy9Xk4i0JvTrjss_oolf6WD8/edit#gid=0","cachedResultName":"Knowledge_Base"},"documentId":{"__rl":true,"mode":"list","value":"1rEZ1A0Gd5ejT_b2F5tcYy9Xk4i0JvTrjss_oolf6WD8","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1rEZ1A0Gd5ejT_b2F5tcYy9Xk4i0JvTrjss_oolf6WD8/edit?usp=drivesdk","cachedResultName":"customer_support_knowledge_base"}},"credentials":{"googleSheetsOAuth2Api":{"id":"ubQXdpluCtk0bGFi","name":"Google Sheets account"}},"typeVersion":4.5},{"id":"dfaba1db-fc45-4c09-b83d-2413086f52d8","name":"knowledge base1","type":"n8n-nodes-base.googleSheetsTool","position":[2240,1440],"parameters":{"options":{},"sheetName":{"__rl":true,"mode":"list","value":"gid=0","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1rEZ1A0Gd5ejT_b2F5tcYy9Xk4i0JvTrjss_oolf6WD8/edit#gid=0","cachedResultName":"Knowledge_Base"},"documentId":{"__rl":true,"mode":"list","value":"1rEZ1A0Gd5ejT_b2F5tcYy9Xk4i0JvTrjss_oolf6WD8","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1rEZ1A0Gd5ejT_b2F5tcYy9Xk4i0JvTrjss_oolf6WD8/edit?usp=drivesdk","cachedResultName":"customer_support_knowledge_base"}},"credentials":{"googleSheetsOAuth2Api":{"id":"ubQXdpluCtk0bGFi","name":"Google Sheets account"}},"typeVersion":4.5},{"id":"a79e16e6-409a-47b1-a7f9-60de7aac1700","name":"Telegram Escalation Logger","type":"n8n-nodes-base.googleSheetsTool","position":[2420,1400],"parameters":{"options":{},"sheetName":{"__rl":true,"mode":"list","value":1478316494,"cachedResultUrl":"https://docs.google.com/spreadsheets/d/1rEZ1A0Gd5ejT_b2F5tcYy9Xk4i0JvTrjss_oolf6WD8/edit#gid=1478316494","cachedResultName":"Customer_Inquiries"},"documentId":{"__rl":true,"mode":"list","value":"1rEZ1A0Gd5ejT_b2F5tcYy9Xk4i0JvTrjss_oolf6WD8","cachedResultUrl":"https://docs.google.com/spreadsheets/d/1rEZ1A0Gd5ejT_b2F5tcYy9Xk4i0JvTrjss_oolf6WD8/edit?usp=drivesdk","cachedResultName":"customer_support_knowledge_base"}},"credentials":{"googleSheetsOAuth2Api":{"id":"ubQXdpluCtk0bGFi","name":"Google Sheets account"}},"typeVersion":4.5}],"active":false,"settings":{"executionOrder":"v1"},"versionId":"791294ac-b7d5-45f8-951a-7146057b58f7","connections":{"knowledge base":{"ai_tool":[[{"node":"🤖 Gmail AI Agent","type":"ai_tool","index":0}]]},"knowledge base1":{"ai_tool":[[{"node":"🤖 Telegram AI Agent","type":"ai_tool","index":0}]]},"🧠 Gmail Memory":{"ai_memory":[[{"node":"🤖 Gmail AI Agent","type":"ai_memory","index":0}]]},"🚨 Error Trigger":{"main":[[{"node":"📢 Notify Admin of Error","type":"main","index":0}]]},"🤖 Gmail AI Agent":{"main":[[{"node":"📧 Send Gmail Reply","type":"main","index":0}]]},"🧠 Telegram Memory":{"ai_memory":[[{"node":"🤖 Telegram AI Agent","type":"ai_memory","index":0}]]},"📧 Send Gmail Reply":{"main":[[{"node":"✅ Mark Gmail as Read","type":"main","index":0},{"node":"📊 Log Gmail Interaction","type":"main","index":0}]]},"🤖 Telegram AI Agent":{"main":[[{"node":"💬 Send Telegram Reply","type":"main","index":0}]]},"Gmail Escalation Logger":{"ai_tool":[[{"node":"🤖 Gmail AI Agent","type":"ai_tool","index":0}]]},"💬 Send Telegram Reply":{"main":[[{"node":"📊 Log Telegram Interaction","type":"main","index":0}]]},"Telegram Escalation Logger":{"ai_tool":[[{"node":"🤖 Telegram AI Agent","type":"ai_tool","index":0}]]},"📋 Process Gmail Message":{"main":[[{"node":"🤖 Gmail AI Agent","type":"main","index":0}]]},"📋 Process Telegram Message":{"main":[[{"node":"🤖 Telegram AI Agent","type":"main","index":0}]]},"🧠 OpenAI Chat Model - Gmail":{"ai_languageModel":[[{"node":"🤖 Gmail AI Agent","type":"ai_languageModel","index":0}]]},"🧠 OpenAI Chat Model - Telegram":{"ai_languageModel":[[{"node":"🤖 Telegram AI Agent","type":"ai_languageModel","index":0}]]},"📧 Gmail Customer Inquiry Trigger":{"main":[[{"node":"📋 Process Gmail Message","type":"main","index":0}]]},"💬 Telegram Customer Message Trigger":{"main":[[{"node":"📋 Process Telegram Message","type":"main","index":0}]]}}}


name: Auto-Publish YouTube Videos to Facebook & Instagram with AI-Generated Captions
author_name: Yaron Been
author_username: yaron-nofluff
categories: []
created_at: 2025-05-29T07:09:15.501Z
updated_at: 2025-05-29T07:09:15.501Z
url: https://n8n.io/workflows/4478
scraped_at: 2025-07-06 21:16:30
description:
  Automatically turn your YouTube videos into engaging Facebook and Instagram posts with AI-generated captions.

  This powerful workflow monitors your YouTube channel for new uploads, generates engaging social media captions using AI, and automatically publishes to both Facebook pages and Instagram business accounts - maximizing your content reach across all major platforms.

  🚀 What It Does

  YouTube Channel Monitoring: Watches your YouTube RSS feed hourly for new video uploads and triggers cross-platform publishing

  AI Caption Generation: Uses GPT-4 to create engaging, platform-optimized social media captions with emojis and calls-to-action

  Facebook Auto-Publishing: Posts directly to your Facebook page with AI-generated captions and video links

  Instagram Business Posting: Creates Instagram posts using YouTube thumbnails as images with custom captions

  Smart Error Handling: Continues workflow even if one platform fails, ensuring maximum post distribution

  🎯 Key Benefits

  ✅ 3x Content Reach: Automatically distribute YouTube content across major social platforms  
  ✅ Save 5+ Hours Weekly: Eliminate manual cross-posting and caption writing  
  ✅ AI-Optimized Captions: Professional, engaging content tailored for social media  
  ✅ Instant Publishing: New YouTube videos become social posts within 1 hour  
  ✅ Professional Thumbnails: Uses high-quality YouTube thumbnails for Instagram  
  ✅ Set & Forget: Complete automation once configured  

  🏢 Perfect For

  Content Creators & YouTubers
  Individual creators maximizing content distribution
  Educational channels expanding social reach
  Entertainment creators building multi-platform presence
  Business channels driving traffic from social media

  Business Applications
  Brand Awareness**: Increase visibility across all major social platforms
  Traffic Generation**: Drive social media traffic back to YouTube content
  Audience Growth**: Reach different demographics on each platform
  Content Amplification**: Maximize ROI from video content creation

  ⚙️ What's Included

  Complete Cross-Platform Workflow: Ready-to-deploy multi-platform publishing system
  YouTube RSS Integration: Automatic monitoring of your channel for new uploads
  AI Caption Engine: GPT-4 powered social media caption generation
  Facebook Publishing: Direct integration with Facebook Pages API
  Instagram Business Integration: Full Instagram Business account posting capability
  Error-Resistant Design: Robust system continues working even if one platform fails

  🔧 Setup Requirements

  n8n Platform**: Cloud or self-hosted instance
  YouTube Channel**: RSS feed for monitoring new uploads
  Meta Developer Account**: Facebook app with required permissions
  OpenAI API**: GPT-4 access for caption generation
  Long-lived Access Token**: For Facebook and Instagram API access

  📊 Required Meta API Permissions

  Required Permissions:
  ✅ pages_manage_posts
  ✅ pages_read_engagement  
  ✅ pages_show_list
  ✅ instagram_content_publish
  ✅ instagram_basic

  Token Type: Long-lived access token
  API Version: v22.0

  🎨 Sample AI Caption Generation

  YouTube Video: "10 Tips for Better Photography"

  Generated Social Caption:
  📸 Just dropped my latest photography tutorial! 

  Discover 10 game-changing tips that will transform your photos from amateur to professional. Whether you're just starting out or looking to level up your skills, these techniques will make a huge difference! 

  ✨ What you'll learn:
  • Composition secrets the pros use
  • Lighting techniques for any situation  
  • Camera settings that actually matter

  Which tip surprised you the most? Drop a comment below! 👇

  Watch the full tutorial: [YouTube Link]

  #Photography #Tutorial #PhotoTips #ContentCreator #Learn

  🎯 Customization Options

  Caption Personalization: Adjust AI prompts for your brand voice, hashtags, and audience
  Platform-Specific Formatting: Different caption styles for Facebook vs Instagram
  Posting Schedule: Modify monitoring frequency (hourly, daily, custom intervals)
  Multiple Channels: Monitor multiple YouTube channels with different posting strategies
  Content Filtering: Add filters for specific video types or topics
  Brand Integration: Include consistent branding elements and calls-to-action

  🏷️ Tags & Categories

  #youtube-automation #social-media-publishing #cross-platform-marketing #facebook-automation #instagram-business #content-distribution #ai-caption-generation #social-media-management #multi-platform-posting #youtube-marketing #content-amplification #social-media-automation #creator-tools #video-marketing #workflow-automation

  💡 Use Case Examples

  Educational Creator: Automatically share tutorial videos across platforms to reach students on different social networks

  Product Review Channel: Distribute review videos to Facebook and Instagram to drive traffic and affiliate sales

  Business Coach: Share valuable content across platforms to build authority and attract consulting clients

  Entertainment Channel: Maximize viral potential by instantly distributing funny videos across all major platforms

  🛠️ Setup & Support

  Quick Configuration: Complete setup in 45 minutes with Meta Developer account and API tokens
  Template Access Tokens: Instructions for generating long-lived Facebook/Instagram tokens
  Channel Integration: Simple YouTube RSS feed configuration for any channel
  Testing Protocol: Built-in error handling and testing procedures

  📞 Get Help & Resources


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

  💼 Social Media Automation Support  
  LinkedIn: https://www.linkedin.com/in/yaronbeen/

  📧 Technical Configuration Help  
  Email: Yaron@nofluff.online - Response within 24 hours

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

workflow_json:
  {"id":"kPBvBnjidCFr5v69","meta":{"instanceId":"2c6d3d38af8a4c0f79fb39f43818e6004a0dbcc85be9dad124fc43e13d64847f","templateCredsSetupCompleted":true},"name":"Youtube to Instagram_Facebook","tags":[],"nodes":[{"id":"workflow-overview-social","name":"Workflow Overview","type":"n8n-nodes-base.stickyNote","position":[-1300,-320],"parameters":{"color":2,"width":350,"height":380,"content":"# 📱 YouTube to Social Media Automation\n\n**Purpose:** Auto-publish YouTube videos to Facebook & Instagram\n\n**Schedule:** Checks for new videos every hour\n\n**Required Setup:**\n1. YouTube channel RSS feed\n2. OpenAI API key (GPT-4o-mini)\n3. Meta App with permissions\n4. Long-lived access token\n\n## Workflow Steps:\n1. **Monitor** - RSS feed for new videos\n2. **Generate** - AI creates social caption\n3. **Publish** - Posts to FB & Instagram\n\n💡 Update all `<Access_Token>` and `<Facebook_PageID>` placeholders"},"typeVersion":1},{"id":"rss-trigger-note","name":"RSS Trigger Info","type":"n8n-nodes-base.stickyNote","position":[-1040,-320],"parameters":{"color":3,"width":280,"height":220,"content":"## 🎥 YouTube RSS Trigger\n\n**Monitors your YouTube channel:**\n- Checks every hour for new uploads\n- Uses YouTube RSS feed format\n\n**To find your channel ID:**\n1. Go to your YouTube channel\n2. View page source\n3. Search for \"channelId\"\n\n⚠️ Replace channel_id in RSS URL"},"typeVersion":1},{"id":"ai-caption-note","name":"AI Caption Generation","type":"n8n-nodes-base.stickyNote","position":[-740,-320],"parameters":{"color":5,"width":280,"height":200,"content":"## 🤖 AI Caption Generation\n\n**OpenAI GPT-4o-mini:**\n- Generates engaging social media captions\n- Includes emojis automatically\n- Adds call-to-action\n\n**Customize the prompt to:**\n- Match your brand voice\n- Include specific hashtags\n- Target your audience"},"typeVersion":1},{"id":"facebook-post-note","name":"Facebook Publishing","type":"n8n-nodes-base.stickyNote","position":[-390,-440],"parameters":{"color":4,"width":250,"height":180,"content":"## 📘 Facebook Publishing\n\n**Direct post to Facebook Page**\n\n⚠️ **Required updates:**\n- Replace `<Facebook_PageID>`\n- Replace `<Access_Token>`\n\n**Note:** Uses error handling to continue workflow even if Facebook fails"},"typeVersion":1},{"id":"instagram-flow-note","name":"Instagram Publishing Flow","type":"n8n-nodes-base.stickyNote","position":[-120,-180],"parameters":{"color":6,"width":300,"height":220,"content":"## 📸 Instagram Publishing Flow\n\n**3-step process:**\n1. Get Business Account ID\n2. Create media container with thumbnail\n3. Publish the post\n\n**Automatic thumbnail:**\nPulls YouTube video thumbnail as Instagram image\n\n⚠️ Requires Instagram Business Account linked to Facebook Page"},"typeVersion":1},{"id":"api-requirements-note","name":"API Requirements","type":"n8n-nodes-base.stickyNote","position":[-440,280],"parameters":{"color":1,"width":250,"height":200,"content":"⚠️ **Meta API Requirements**\n\n**Required Permissions:**\n- pages_manage_posts\n- pages_read_engagement\n- pages_show_list\n- instagram_content_publish\n- instagram_basic\n\n**Token Type:** Long-lived access token\n**API Version:** v22.0"},"typeVersion":1},{"id":"cda123c2-21a3-421d-918e-5a6973002aa3","name":"AI Agent","type":"@n8n/n8n-nodes-langchain.agent","notes":"Formats post caption using video metadata. Customize prompt for your brand voice and hashtags","position":[-740,-80],"parameters":{"text":"=Write a short, engaging social media post about this new YouTube video:\n\nTitle: {{ $json.title }}\nURL: {{ $json.link }}\n\nInclude emojis and a call to action.","options":{},"promptType":"define"},"typeVersion":1.9},{"id":"d215f6c3-f9d7-4103-8c26-419f468cf74b","name":"OpenAI Chat Model","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","notes":"Uses GPT-4o-mini to generate the caption text","position":[-740,160],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o-mini"},"options":{}},"credentials":{"openAiApi":{"id":"p5RrjC1K9qFbdflM","name":"OpenAi account"}},"typeVersion":1.2},{"id":"fbf6f102-1f8d-4e22-a850-1f5f163b94d5","name":"Post on Facebook","type":"n8n-nodes-base.httpRequest","notes":"Publishes the caption using Facebook Graph API. Replace <Facebook_PageID> and <Access_Token>","onError":"continueErrorOutput","position":[-340,-240],"parameters":{"url":"=https://graph.facebook.com/v22.0/<Facebook_PageID>/feed\n","method":"POST","options":{},"sendBody":true,"contentType":"form-urlencoded","authentication":"genericCredentialType","bodyParameters":{"parameters":[{"name":"message","value":"={{ $json.output }}"},{"name":"access_token","value":"<Access_Token>"}]},"genericAuthType":"httpHeaderAuth"},"credentials":{"httpHeaderAuth":{"id":"jfdonlZifjvvr","name":"Header Auth account"}},"typeVersion":4.2},{"id":"000891de-e3e2-4de8-8742-ad45a2a958db","name":"Publish Post On Instagram","type":"n8n-nodes-base.httpRequest","notes":"Publishes post to Instagram feed using the media container ID","position":[180,60],"parameters":{"url":"=https://graph.facebook.com/v22.0/{{ $('Get IG Business Account ID').item.json.instagram_business_account.id }}/media_publish\n","method":"POST","options":{},"sendBody":true,"contentType":"form-urlencoded","bodyParameters":{"parameters":[{"name":"creation_id","value":"={{ $json.id }}"},{"name":"access_token","value":"<Access_Token>"}]}},"typeVersion":4.2},{"id":"2e65dd2e-7f9e-4abd-b6c7-e811b3a86349","name":"Get IG Business Account ID","type":"n8n-nodes-base.httpRequest","notes":"Retrieves Instagram Business account ID linked to Facebook Page","onError":"continueErrorOutput","position":[-340,80],"parameters":{"url":"https://graph.facebook.com/v22.0/<Facebook_PageID>","options":{},"sendQuery":true,"queryParameters":{"parameters":[{"name":"fields","value":"instagram_business_account"},{"name":"access_token","value":"<Access_Token>"}]}},"typeVersion":4.2},{"id":"c2d089b9-754c-49fe-aa4d-976072340a0e","name":"Create Media Container","type":"n8n-nodes-base.httpRequest","notes":"Uploads YouTube thumbnail as Instagram image with AI-generated caption","position":[-80,60],"parameters":{"url":"=https://graph.facebook.com/v22.0/{{ $json.instagram_business_account.id }}/media","method":"POST","options":{},"sendBody":true,"contentType":"form-urlencoded","bodyParameters":{"parameters":[{"name":"image_url","value":"=https://img.youtube.com/vi/{{ $('Pull Youtube Video From Channel').item.json.link.split(\"=\")[1] }}/maxresdefault.jpg"},{"name":"caption","value":"={{ $('AI Agent').item.json.output }}"},{"name":"access_token","value":"<Access_Token>"}]}},"typeVersion":4.2},{"id":"29656ae1-d60e-4f4d-9326-17801ddcbb65","name":"Pull Youtube Video From Channel","type":"n8n-nodes-base.rssFeedReadTrigger","notes":"Monitors new uploads from your YouTube channel. Replace channel_id in RSS URL","position":[-1000,-80],"parameters":{"feedUrl":"https://www.youtube.com/feeds/videos.xml?channel_id=UC2Tf8MGUzFX-GPkuBEBSKMg","pollTimes":{"item":[{"mode":"everyHour"}]}},"typeVersion":1}],"active":false,"settings":{"executionOrder":"v1"},"versionId":"a459b777-6ecf-46d2-9543-061a888393a6","connections":{"AI Agent":{"main":[[{"node":"Get IG Business Account ID","type":"main","index":0},{"node":"Post on Facebook","type":"main","index":0}]]},"Post on Facebook":{"main":[[]]},"OpenAI Chat Model":{"ai_languageModel":[[{"node":"AI Agent","type":"ai_languageModel","index":0}]]},"Create Media Container":{"main":[[{"node":"Publish Post On Instagram","type":"main","index":0}]]},"Publish Post On Instagram":{"main":[[]]},"Get IG Business Account ID":{"main":[[{"node":"Create Media Container","type":"main","index":0}]]},"Pull Youtube Video From Channel":{"main":[[{"node":"AI Agent","type":"main","index":0}]]}}}


name: AI-Powered Candidate Screening and Evaluation Workflow using OpenAI and Airtable
author_name: Billy Christi
author_username: billy
categories: []
created_at: 2025-05-29T11:06:09.128Z
updated_at: 2025-05-29T11:06:09.128Z
url: https://n8n.io/workflows/4481
scraped_at: 2025-07-06 21:16:30
description:
  Who is this for?

  This workflow is ideal for:

  HR professionals* and *recruiters** who want to automate and enhance the hiring process
  Organizations** seeking AI-driven, consistent, and data-backed candidate evaluations
  Hiring managers** using Airtable as their recruitment database

  What problem is this workflow solving?

  Screening candidates manually is time-consuming, inconsistent, and difficult to scale. This workflow solves that by:

  Automating resume intake and AI evaluation**
  Matching candidates to job postings dynamically**
  Generating standardized suitability reports**
  Notifying HR only when candidates meet the criteria**
  Storing all applications in a structured Airtable database**

  What this workflow does

  This workflow builds an end-to-end AI-powered hiring pipeline using Airtable, OpenAI, and Google Drive. Here's how it works:

  Accept candidate applications via a public web form, including resume upload (PDF only)
  Extract text from uploaded resumes for processing
  Store resumes in Google Drive and generate shareable links
  Match the application to a job posting stored in Airtable
  Use AI to evaluate candidates (via OpenAI GPT-4) against job descriptions and requirements
  Generate suitability results including:

     Match percentage
     Screening status: Suitable, Not Suitable, Under Review
     Detailed notes
  Combine AI output and files into one data object
  Create a new candidate record in Airtable with all application data
  Automatically notify HR via Gmail if a candidate is marked “Suitable”

  Setup

  View & Copy the Airtable base here:  
  👉 Candidate Screening – Airtable Base Template  
  Set up Google Drive folder
  Connect your OpenAI API key for the AI agent model
  Connect your Gmail account for email notifications
  Deploy the public-facing form to start receiving applications
  Test the workflow using a sample job and resume

  How to customize this workflow to your needs

  Expand file support**: Allow DOC or DOCX uploads by adding format conversion nodes
  Add multi-recipient email alerts**: Extend Gmail node for multiple HR recipients
  Handle “Under Review” differently**: Add additional logic to notify or flag these candidates
  Send rejection emails automatically**: Extend the IF branch for “Not Suitable” candidates
  Schedule interviews**: Integrate with Google Calendar or Calendly APIs
  Add Slack notifications**: Send alerts to team channels for real-time updates

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

workflow_json:
  {"meta":{"instanceId":"d1786ab0d745a7498abf13a9c2cdabb1374c006e889b79eef64ce0386b8f8a41","templateCredsSetupCompleted":true},"nodes":[{"id":"eb5ebae6-b369-4540-93d4-de8bcc2be075","name":"Search Job Posting","type":"n8n-nodes-base.airtable","position":[2040,-80],"parameters":{"base":{"__rl":true,"mode":"list","value":"appgVjZcaRP8BsKf0","cachedResultUrl":"https://airtable.com/appgVjZcaRP8BsKf0","cachedResultName":"HR Database"},"limit":1,"table":{"__rl":true,"mode":"list","value":"tblla4rBCW3BhPtRO","cachedResultUrl":"https://airtable.com/appgVjZcaRP8BsKf0/tblla4rBCW3BhPtRO","cachedResultName":"Job Posting"},"options":{},"operation":"search","returnAll":false,"filterByFormula":"=FIND(LOWER(\"{{ $('Candidate Application Form').item.json['Position Applied For'] }}\"), LOWER({Job Title})) > 0"},"credentials":{"airtableTokenApi":{"id":"r2IibdsQurA56LDa","name":"Airtable Personal Access Token account"}},"typeVersion":2.1},{"id":"5a39a9d5-ae99-486a-9831-14a0c2945636","name":"Create Candidate","type":"n8n-nodes-base.airtable","position":[3000,140],"parameters":{"base":{"__rl":true,"mode":"list","value":"appgVjZcaRP8BsKf0","cachedResultUrl":"https://airtable.com/appgVjZcaRP8BsKf0","cachedResultName":"HR Database"},"table":{"__rl":true,"mode":"list","value":"tblQy83erGR5lQj5c","cachedResultUrl":"https://airtable.com/appgVjZcaRP8BsKf0/tblQy83erGR5lQj5c","cachedResultName":"Candidates"},"columns":{"value":{"Resume":"={{ $json.file_array }}","Full Name":"={{ $('Candidate Application Form').item.json['Full Name '] }}","Cover Letter":"={{ $('Candidate Application Form').item.json['Cover Letter'] }}","Date Applied":"={{ $now }}","Email Address":"={{ $('Candidate Application Form').item.json['Email Address'] }}","Relevant Skills":"={{ $('Candidate Application Form').item.json['Relevant Skills'] }}","Screening Notes":"={{ $json.output.screening_notes }}","Match Percentage":"={{ $json.output.match_percentage }}","Position Applied":"={{ $('Candidate Application Form').item.json['Position Applied For'] }}","Screening Status":"={{ $json.output.screening_status }}"},"schema":[{"id":"Candidate ID","type":"string","display":true,"removed":true,"readOnly":true,"required":false,"displayName":"Candidate ID","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Full Name","type":"string","display":true,"removed":false,"readOnly":false,"required":false,"displayName":"Full Name","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Email Address","type":"string","display":true,"removed":false,"readOnly":false,"required":false,"displayName":"Email Address","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Position Applied","type":"string","display":true,"removed":false,"readOnly":false,"required":false,"displayName":"Position Applied","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Relevant Skills","type":"string","display":true,"removed":false,"readOnly":false,"required":false,"displayName":"Relevant Skills","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Cover Letter","type":"string","display":true,"removed":false,"readOnly":false,"required":false,"displayName":"Cover Letter","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Resume","type":"array","display":true,"removed":false,"readOnly":false,"required":false,"displayName":"Resume","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Screening Status","type":"string","display":true,"removed":false,"readOnly":false,"required":false,"displayName":"Screening Status","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Match Percentage","type":"number","display":true,"removed":false,"readOnly":false,"required":false,"displayName":"Match Percentage","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Screening Notes","type":"string","display":true,"removed":false,"readOnly":false,"required":false,"displayName":"Screening Notes","defaultMatch":false,"canBeUsedToMatch":true},{"id":"Date Applied","type":"string","display":true,"removed":false,"readOnly":false,"required":false,"displayName":"Date Applied","defaultMatch":false,"canBeUsedToMatch":true},{"id":"test","type":"options","display":true,"options":[{"name":"1","value":"1"},{"name":"2","value":"2"},{"name":"3","value":"3"}],"removed":true,"readOnly":false,"required":false,"displayName":"test","defaultMatch":false,"canBeUsedToMatch":true}],"mappingMode":"defineBelow","matchingColumns":[],"attemptToConvertTypes":false,"convertFieldsToString":false},"options":{},"operation":"create"},"credentials":{"airtableTokenApi":{"id":"r2IibdsQurA56LDa","name":"Airtable Personal Access Token account"}},"typeVersion":2.1},{"id":"5604f43d-e7df-404a-b034-f82a667c9871","name":"OpenAI Chat Model","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[2320,140],"parameters":{"model":{"__rl":true,"mode":"list","value":"gpt-4o-mini"},"options":{}},"credentials":{"openAiApi":{"id":"MGwGMKEkdcjzlYCw","name":"OpenAi account"}},"typeVersion":1.2},{"id":"d2acb00b-9e36-4200-99e8-5a8918f7ddb1","name":"Structured Output Parser","type":"@n8n/n8n-nodes-langchain.outputParserStructured","position":[2500,140],"parameters":{"jsonSchemaExample":"{\n  \"screening_status\": \"Suitable\",\n  \"match_percentage\": 88,\n  \"screening_notes\": \"Detailed explanation of the assessment, including relevant skill matches, experience analysis, and justification for the screening status.\"\n}"},"typeVersion":1.2},{"id":"f5071709-8201-40e0-a3dd-ff77376eed11","name":"Candidate Screener AI Agent","type":"@n8n/n8n-nodes-langchain.agent","position":[2320,-80],"parameters":{"text":"=Candidate Screening Information:\n\n///\nUser Side:\n\nPosition Applied:  \n{{ $('Search Job Posting').item.json['Job Title'] }}\n\nRelevant Skills the Candidate Possesses:\n{{ $('Candidate Application Form').item.json['Relevant Skills'] }}\n\n\nCover Letter:  \n{{ $('Candidate Application Form').item.json['Cover Letter'] }}\n\nResume Content:  \n{{ $('Extract Resume PDF').item.json.text }}\n\n///\n\nEmployer Side:\n\nPosition Description:  \n{{ $('Search Job Posting').item.json['Job Description'] }}\n\nSkills Required:  \n{{ $('Search Job Posting').item.json['Required Skills'] }}\n\n///","options":{"systemMessage":"=You are a Candidate Screening AI Agent responsible for assessing candidate suitability for specific job positions based on the provided information. \n\nObjective:\nEvaluate the candidate’s fit for the applied position by analyzing their relevant skills, cover letter, and resume content. Compare this information with the job description and required skills provided by the employer to determine suitability, a match percentage, and screening notes.\n\nInput Fields:\n\nUser Side:\n- Position applied: The job position the candidate applied for.\n- Relevant skills: A list of key skills the candidate possesses.\n- Cover letter: Candidate’s introduction, work experience, and key achievements.\n- Resume: Parsed text content extracted from the resume in plain text format.\n\nEmployer Side:\n- Position description: Detailed job description including responsibilities and expectations.\n- Skills required: A list of required skills for the position.\n\nOutput Fields:\n- Screening Status: One of the following options: \"Suitable\", \"Not Suitable\", \"Under Review\".\n- Match Percentage: A numerical score indicating the percentage of relevant skills matching the job requirements.\n- Screening Notes: A summary of the assessment, including strengths, areas for improvement, and justification for the screening status.\n\nInstructions:\n1. Extract and analyze relevant skills mentioned in the cover letter and resume content.\n2. Compare the extracted skills with the job requirements and skills required by the employer.\n3. Assign a Match Percentage based on the alignment of skills and experience.\n4. Determine the Screening Status based on the skill match and relevance of the candidate’s experience to the position.\n5. Provide comprehensive Screening Notes to justify the assigned status and percentage, highlighting strengths and areas for improvement."},"promptType":"define","hasOutputParser":true},"typeVersion":1.9},{"id":"9050d69b-8fed-45ea-8b14-0456d88fe056","name":"Set File Array for airtable","type":"n8n-nodes-base.set","position":[2360,580],"parameters":{"mode":"raw","options":{},"jsonOutput":"={\"file_array\":[\n  {\n    \"url\": \"{{ $('Upload File').item.json.webContentLink }}\",\n    \"filename\": \"{{ $('Upload File').item.json.name }}\"\n  }\n]\n}"},"typeVersion":3.4},{"id":"584743e4-ddcd-4744-a01f-493ab6890b24","name":"Merge","type":"n8n-nodes-base.merge","position":[2760,140],"parameters":{"mode":"combine","options":{},"combineBy":"combineAll"},"typeVersion":3.1},{"id":"7ef768ee-58ef-4769-9abc-ff10e2a59fe9","name":"Upload File","type":"n8n-nodes-base.googleDrive","position":[1880,580],"parameters":{"name":"={{ $json.Resume.filename }}","driveId":{"__rl":true,"mode":"list","value":"My Drive"},"options":{},"folderId":{"__rl":true,"mode":"list","value":"13BuRkJofybsBlF77oqoS87A2qq4zD2aP","cachedResultUrl":"https://drive.google.com/drive/folders/13BuRkJofybsBlF77oqoS87A2qq4zD2aP","cachedResultName":"pdf dev"},"inputDataFieldName":"Resume"},"credentials":{"googleDriveOAuth2Api":{"id":"SEUhrgz30NMJS3cH","name":"Google Drive account"}},"typeVersion":3},{"id":"bd096e95-3c2c-450f-9779-e63977f89797","name":"Set File Permission","type":"n8n-nodes-base.googleDrive","position":[2120,580],"parameters":{"fileId":{"__rl":true,"mode":"id","value":"={{ $json.id }}"},"options":{},"operation":"share","permissionsUi":{"permissionsValues":{"role":"reader","type":"anyone"}}},"credentials":{"googleDriveOAuth2Api":{"id":"SEUhrgz30NMJS3cH","name":"Google Drive account"}},"typeVersion":3},{"id":"82bf4fbd-bed1-43be-b1df-be5319069a32","name":"Check if candidate is suitable","type":"n8n-nodes-base.if","position":[3200,140],"parameters":{"options":{},"conditions":{"options":{"version":2,"leftValue":"","caseSensitive":true,"typeValidation":"strict"},"combinator":"and","conditions":[{"id":"ab5102cf-0952-465e-9340-59ced9f39ce1","operator":{"name":"filter.operator.equals","type":"string","operation":"equals"},"leftValue":"={{ $('Merge').item.json.output.screening_status }}","rightValue":"Suitable"}]}},"typeVersion":2.2},{"id":"e886feba-772f-46a3-b22d-9fb0af1b2250","name":"Send email to HR","type":"n8n-nodes-base.gmail","position":[3480,140],"webhookId":"48fa841c-0312-4829-a80c-85cd37deec25","parameters":{"sendTo":"hr_team_n8n@yopmail.com","message":"=We have successfully completed the candidate screening process, and {{ $('Candidate Application Form').item.json['Full Name '] }} has been identified as a suitable candidate for the {{ $('Search Job Posting').item.json['Job Title'] }} position.  \n\nCandidate Details:  \n- Position Applied: {{ $('Search Job Posting').item.json['Job Title'] }}  \n- Match Percentage: {{ $('Candidate Screener AI Agent').item.json.output.match_percentage }}%  \n- Screening Notes: {{ $('Candidate Screener AI Agent').item.json.output.screening_notes }}\n\nPlease proceed with the next steps in the interview scheduling process. If you need any further information or clarification, feel free to reach out.  \n\nThank you,  \nSuper Awesome HR AI Agent","options":{"appendAttribution":false},"subject":"=Candidate {{ $('Candidate Application Form').item.json['Full Name '] }} - Suitable for {{ $('Search Job Posting').item.json['Job Title'] }}\n","emailType":"text"},"credentials":{"gmailOAuth2":{"id":"sWl7FFMkEUYBj0zM","name":"Gmail account"}},"typeVersion":2.1},{"id":"5d52401f-d9de-425e-88fb-b5bc51e04d78","name":"Candidate Application Form","type":"n8n-nodes-base.formTrigger","position":[1400,-80],"webhookId":"2d4004d0-4c93-49d5-9c3a-4e05264fc772","parameters":{"options":{},"formTitle":"Smart Candidate Screening Form","formFields":{"values":[{"fieldLabel":"Full Name ","requiredField":true},{"fieldType":"email","fieldLabel":"Email Address","requiredField":true},{"fieldLabel":"Position Applied For","requiredField":true},{"fieldType":"textarea","fieldLabel":"Relevant Skills","requiredField":true},{"fieldType":"textarea","fieldLabel":"Cover Letter","requiredField":true},{"fieldType":"file","fieldLabel":"Resume","multipleFiles":false,"acceptFileTypes":".pdf"}]}},"typeVersion":2.2},{"id":"1d3ed59d-4887-467a-977f-8a8f84a6528c","name":"Extract Resume PDF","type":"n8n-nodes-base.extractFromFile","position":[1720,-80],"parameters":{"options":{},"operation":"pdf","binaryPropertyName":"Resume"},"typeVersion":1},{"id":"3f489b80-48a6-4e56-b6b9-8db2ddeb3806","name":"Sticky Note","type":"n8n-nodes-base.stickyNote","position":[2280,-360],"parameters":{"color":4,"width":360,"height":680,"content":"🧠 Candidate Screener AI Agent\nUses OpenAI to analyze:\n- Resume content vs job requirements\n- Skills matching\n- Cover letter quality\n\n📊 OUTPUTS:\n- Screening Status (Suitable/Not Suitable/Under Review)\n- Match Percentage (0-100%)\n- Detailed screening notes\n"},"typeVersion":1},{"id":"335e8f4c-7c80-4cfd-9d7d-f8257d2fbe8c","name":"Sticky Note1","type":"n8n-nodes-base.stickyNote","position":[1920,-220],"parameters":{"color":4,"width":340,"height":300,"content":"## Search Job Posting (Job Matching)\nFinds the matching job posting for the applied position"},"typeVersion":1},{"id":"ecb40f1b-2fd5-468e-ac0b-fcf0d82ca110","name":"Sticky Note2","type":"n8n-nodes-base.stickyNote","position":[1800,380],"parameters":{"color":4,"width":760,"height":340,"content":"## File Preparation for Airtable Upload\n\n- Upload the file to Google Drive  \n- Set the permission to public  \n- Format the data to match the format required by Airtable for file uploads\n"},"typeVersion":1},{"id":"191f577e-9230-409d-a69e-d7a7dfef3963","name":"Sticky Note3","type":"n8n-nodes-base.stickyNote","position":[2720,-20],"parameters":{"color":4,"width":420,"height":380,"content":"## Merge & Create Candidate\n\n- Merge data from both flows (Candidate Screener AI Agent and File Flow)  \n- Use the merged data to create a candidate in Airtable\n"},"typeVersion":1},{"id":"e05d6d9a-75b6-4279-bf1b-10ff9514ad75","name":"Sticky Note4","type":"n8n-nodes-base.stickyNote","position":[3180,-60],"parameters":{"color":4,"width":420,"height":420,"content":"## Check Candidate & Send Email to HR\n\n- Check if the candidate is qualified or not  \n- If the candidate is qualified, the system will send an email to HR\n"},"typeVersion":1},{"id":"e8230b23-6e4f-446a-ab10-fc1cd1363713","name":"Sticky Note5","type":"n8n-nodes-base.stickyNote","position":[1320,-380],"parameters":{"color":4,"width":560,"height":580,"content":"## Candidate Application Form\n\nWeb form for candidates to submit applications\n\nFields:\n- Full Name (required)\n- Email Address (required, email validation)\n- Position Applied For (required)\n- Relevant Skills (textarea, required)\n- Cover Letter (textarea, required)\n- Resume (PDF file upload only)"},"typeVersion":1},{"id":"e8423226-d858-41c8-8387-2b4a937c84ac","name":"Sticky Note6","type":"n8n-nodes-base.stickyNote","position":[1000,-380],"parameters":{"color":4,"width":280,"height":280,"content":"## SETUP REQUIRED\n**Author:** [Billy Christi](https://n8n.io/creators/billy/)\n\nAirtable Base Structure:  \n[Copy this Airtable Base](https://airtable.com/appgVjZcaRP8BsKf0/shrQAqQ2JUW50EEyW/tblGIVbpACRwWzzlp/viwWS2Ohh6oXZLvyY?blocks=hide)\n\nRequired Credentials:  \n• Airtable API Key  \n• OpenAI API Key (GPT-4)  \n• Google Drive Credential\n• Gmail Credential\n"},"typeVersion":1},{"id":"55e89737-4449-4efb-9220-b40e9c1ff1af","name":"Sticky Note7","type":"n8n-nodes-base.stickyNote","position":[680,340],"parameters":{"color":5,"width":460,"height":460,"content":"## 🤖 AI-Powered Candidate Screening and Evaluation Workflow using OpenAI and Airtable\n\n**What This Template Does:**\n- Creates a web form for candidates to submit applications with resume uploads\n- Automatically extracts and processes text content from PDF resumes\n- Uses GPT-4 AI to intelligently match candidates against job requirements\n- Calculates compatibility scores and generates detailed screening notes\n- Stores candidate data and resumes in Airtable database and Google Drive\n- Automatically emails HR team when suitable candidates are found\n- Fully automates the entire hiring pipeline from application to notification"},"typeVersion":1},{"id":"9ea639a0-efb8-48f3-9143-e3eeb7a9d641","name":"Sticky Note8","type":"n8n-nodes-base.stickyNote","position":[1160,340],"parameters":{"color":5,"width":500,"height":460,"content":"## 📋 WORKFLOW PROCESS OVERVIEW\nStep 1: 📝 Candidate Application Form collects candidate details and PDF resume  \nStep 2: 📄 Extract Resume PDF converts uploaded PDF into readable text  \nStep 3: 📁 Upload File stores resume in Google Drive and sets permissions  \nStep 4: 🔍 Search Job Posting finds matching job in Airtable database  \nStep 5: 🤖 AI Agent (OpenAI) evaluates candidate fit and generates screening results  \nStep 6: 💾 Create Candidate stores complete record in Airtable with AI results  \nStep 7: ✅ Check Suitability determines if candidate meets requirements  \nStep 8: 📧 Send Email to HR notifies team when candidate is suitable"},"typeVersion":1}],"connections":{"Merge":{"main":[[{"node":"Create Candidate","type":"main","index":0}]]},"Upload File":{"main":[[{"node":"Set File Permission","type":"main","index":0}]]},"Create Candidate":{"main":[[{"node":"Check if candidate is suitable","type":"main","index":0}]]},"OpenAI Chat Model":{"ai_languageModel":[[{"node":"Candidate Screener AI Agent","type":"ai_languageModel","index":0}]]},"Extract Resume PDF":{"main":[[{"node":"Search Job Posting","type":"main","index":0}]]},"Search Job Posting":{"main":[[{"node":"Candidate Screener AI Agent","type":"main","index":0}]]},"Set File Permission":{"main":[[{"node":"Set File Array for airtable","type":"main","index":0}]]},"Structured Output Parser":{"ai_outputParser":[[{"node":"Candidate Screener AI Agent","type":"ai_outputParser","index":0}]]},"Candidate Application Form":{"main":[[{"node":"Extract Resume PDF","type":"main","index":0},{"node":"Upload File","type":"main","index":0}]]},"Candidate Screener AI Agent":{"main":[[{"node":"Merge","type":"main","index":0}]]},"Set File Array for airtable":{"main":[[{"node":"Merge","type":"main","index":1}]]},"Check if candidate is suitable":{"main":[[{"node":"Send email to HR","type":"main","index":0}]]}}}


name: LinkedIn Post Automation with AI (GPT-4o) Generation & Slack Approval
author_name: Amit Mehta
author_username: amitswba
categories: []
created_at: 2025-05-29T11:20:45.319Z
updated_at: 2025-05-29T11:20:45.319Z
url: https://n8n.io/workflows/4483
scraped_at: 2025-07-06 21:16:30
description:
  LinkedIn Post Automation with AI Generation (Gpt-4o) & Slack Approval

  How it Works

  This workflow automates the creation and publishing of LinkedIn posts with AI-generated content and human approval via Slack, using Google Sheets, OpenAI (GPT-4), Slack Interactive Messages, and the LinkedIn API.

  Whether you're a social media manager, content creator, or marketing professional, this workflow helps you maintain consistent LinkedIn presence and scale content creation while keeping human oversight — all managed from a simple spreadsheet.

  🎯 Use Case

  Ideal for:
  Content Marketers** managing multiple LinkedIn accounts
  Personal Brand Builders** maintaining regular posting schedule  
  Agencies** handling client social media presence
  Teams** requiring content approval workflows

  Setup Instructions

  1. Prepare the Spreadsheet

  File name: Linkedin Post
  Main sheet structure:
  | ID | Linkedin Post Title | Status | Image URL |
  Groups sheet structure:
  | GroupIds |
  Add post topics and set their Status as Pending

  2. Configure Google Sheets Nodes

  Connect your Google account to:
  Linkedin-Post-Topic (Trigger node)
  Update-Status 
  Get-Group-id

  3. Add API Credentials

  OpenAI API Key** → for GPT-4 content generation
  Slack OAuth Token** → for approval messages
  LinkedIn Access Token** → for posting content
  HTTP Header Auth** → Bearer token for LinkedIn API

  4. Configure Webhooks

  Set up Slack Interactive Components webhook
  Point Request URL to your N8N webhook endpoint
  Enable interactive messages in Slack app

  5. Activate the Workflow

  Once live, the workflow will:
  Monitor spreadsheet for new topics every minute
  Generate LinkedIn post using GPT-4
  Send to Slack for approval/editing
  Upload image to LinkedIn
  Publish to profile and groups
  Update spreadsheet status to Posted

  🔁 Workflow Logic

  Trigger: New/updated row with Pending status
  Generate: AI creates engaging LinkedIn post
  Approve: Slack message for review/edit
  Process: Handle approval response
  Upload: Register and upload image
  Publish: Post to LinkedIn profile & groups
  Update: Mark as Posted in sheet

  🧩 Node Descriptions

  | Node Name | Description |
  |-----------|-------------|
  | Linkedin-Post-Topic | Monitors spreadsheet for new post topics |
  | Validate-Status | Filters only 'Pending' items |
  | Limit | Processes one item at a time |
  | Linedin-Post-Creator | Generates post content using GPT-4 |
  | Format-Content | Prepares content for Slack display |
  | Approval-on-Slack | Sends interactive approval message |
  | Webhook | Receives Slack button responses |
  | Format-Response | Extracts edited content from Slack |
  | Set-Final-Message | Prepares approved content |
  | Linkedin-User-Detail | Fetches LinkedIn user info |
  | Register Image | Initiates LinkedIn image upload |
  | Upload Image | Uploads image to LinkedIn |
  | Linkedin-post | Publishes to personal profile |
  | Get-Group-id | Retrieves LinkedIn group IDs |
  | Post-Linkedin-Groups | Posts to multiple groups |
  | Update-Status | Marks as completed in sheet |

  🛠️ Customization Tips

  Adjust AI prompt for brand voice and hashtags
  Change Slack approver or add multiple reviewers
  Modify posting schedule with delay nodes
  Add analytics tracking with additional API calls
  Filter groups based on specific criteria
  Include URL shortening for tracking

  📒 Suggested Sticky Notes for Workflow

  | Node/Section | Sticky Note Content |
  |--------------|---------------------|
  | Linkedin-Post-Topic | "Triggers every minute for new posts in your spreadsheet" |
  | Validate-Status | "Filters to process only 'Pending' items - prevents duplicates" |
  | Linedin-Post-Creator | "Uses GPT-4 to generate LinkedIn content - customize prompt for your brand voice" |
  | Approval-on-Slack | "Sends for human review - edit the Slack user to change approver" |
  | Webhook | "Receives approval responses - ensure URL is configured in Slack app" |
  | Register Image | "Initiates LinkedIn media upload - requires valid image URL from sheet" |
  | Linkedin-post | "Publishes to your profile - update with your LinkedIn credentials" |
  | Post-Linkedin-Groups | "Posts to multiple groups - add group IDs in Groups sheet" |
  | Update-Status | "Marks as 'Posted' to prevent reprocessing" |

  💡 AI Prompt Configuration

  The workflow uses a sophisticated prompt that:
  Creates compelling hooks
  Includes 3-4 informative paragraphs
  Adds engagement questions
  Inserts relevant emojis
  Generates 4-6 hashtags
  Formats with proper spacing

  🔒 Security & Permissions

  LinkedIn App Requirements:
  r_liteprofile - Read profile data
  r_emailaddress - Access email
  w_member_social - Post content
  rw_organization_admin - Group posting

  Slack Bot Permissions:
  chat:write - Send messages
  im:write - Direct messages
  users:read - User information

  📎 Required Components

  | Component | Purpose |
  |-----------|---------|
  | Google Sheet | Store post topics and status |
  | LinkedIn App | API access for posting |
  | Slack App | Interactive approval flow |
  | OpenAI Account | GPT-4 content generation |
  | N8N Instance | Workflow execution |

  🧪 Testing Tips

  Start with one test topic marked as Pending
  Verify Slack message appears correctly
  Test both "Approve" and "Edit" buttons
  Check image upload completes
  Confirm post appears on LinkedIn
  Verify status updates to Posted

  ⚠️ Common Issues & Solutions

  LinkedIn API Errors:
  Token expiration → Refresh access token
  Rate limits → Add delays between posts
  Group restrictions → Check posting permissions

  Slack Integration:
  Missing responses → Verify webhook URL
  Button not working → Check interactive components
  User not found → Confirm Slack user ID

  Image Upload Failures:
  Invalid URL → Validate image accessibility
  Size limits → Compress images under 10MB
  Format issues → Use JPEG or PNG only

  📊 Workflow Benefits

  Time Savings**: 80% reduction in content publishing time
  Consistency**: Regular posting schedule maintained
  Quality Control**: Human review ensures brand standards
  Scalability**: Handle multiple accounts and groups
  Flexibility**: Easy to modify and extend

  📎 Required Files

  | File Name | Purpose |
  |-----------|---------|
  | Linkedin Post | Google Sheet to hold post topics and status |

  🏷 Suggested Tags & Categories

  #LinkedIn
  #AI
  #ContentAutomation
  #SocialMedia
  #Slack
  #GPT4
  #Marketing
  #WorkflowAutomation

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

workflow_json:
  {"id":"YOUR_WORKFLOW_ID","meta":{"instanceId":"YOUR_INSTANCE_ID","templateCredsSetupCompleted":true},"name":"LinkedIn Post Automation with AI & Slack Approval","tags":[],"nodes":[{"id":"workflow-overview-linkedin","name":"Workflow Overview","type":"n8n-nodes-base.stickyNote","position":[-1050,-450],"parameters":{"content":""},"typeVersion":1},{"id":"sheets-trigger-note","name":"Sheets Trigger Info","type":"n8n-nodes-base.stickyNote","position":[-750,-400],"parameters":{"content":""},"typeVersion":1},{"id":"ai-generation-note","name":"AI Generation","type":"n8n-nodes-base.stickyNote","position":[130,-400],"parameters":{"content":""},"typeVersion":1},{"id":"slack-approval-note","name":"Slack Approval","type":"n8n-nodes-base.stickyNote","position":[730,-380],"parameters":{"content":""},"typeVersion":1},{"id":"webhook-handler-note","name":"Webhook Handler","type":"n8n-nodes-base.stickyNote","position":[-750,-800],"parameters":{"content":""},"typeVersion":1},{"id":"image-upload-note","name":"Image Upload Process","type":"n8n-nodes-base.stickyNote","position":[950,-800],"parameters":{"content":""},"typeVersion":1},{"id":"linkedin-publish-note","name":"LinkedIn Publishing","type":"n8n-nodes-base.stickyNote","position":[1450,-780],"parameters":{"content":""},"typeVersion":1},{"id":"status-update-note","name":"Status Update","type":"n8n-nodes-base.stickyNote","position":[2110,-900],"parameters":{"content":""},"typeVersion":1},{"id":"0cd3e628-1720-49f7-9280-a1039d2c2ca9","name":"Limit","type":"n8n-nodes-base.limit","notes":"Processes one item at a time to prevent API overload","position":[-260,-180],"parameters":{},"typeVersion":1},{"id":"c36d36d6-0035-49ac-a757-4598d56e574e","name":"Structured Output Parser","type":"@n8n/n8n-nodes-langchain.outputParserStructured","position":[328,40],"parameters":{},"typeVersion":1.2},{"id":"9f521172-07f4-4a17-b358-bd998e9a9d02","name":"OpenAI Chat Model","type":"@n8n/n8n-nodes-langchain.lmChatOpenAi","position":[208,40],"parameters":{},"typeVersion":1.2},{"id":"09b0b22f-eb64-468f-85b0-1c9a0608631e","name":"Webhook","type":"n8n-nodes-base.webhook","notes":"Receives approval responses - ensure URL is configured in Slack app","position":[-700,-590],"webhookId":"YOUR_WEBHOOK_ID","parameters":{},"typeVersion":2},{"id":"4e2954d7-e4de-48bf-a974-5ec80c7b7b0c","name":"Linkedin-Post-Topic","type":"n8n-nodes-base.googleSheetsTrigger","notes":"Triggers every minute for new posts in your spreadsheet","position":[-700,-180],"parameters":{},"typeVersion":1},{"id":"47c4cdd0-48ef-4e41-996b-ed29811b092e","name":"Validate-Status","type":"n8n-nodes-base.if","notes":"Filters to process only 'Pending' items - prevents duplicates","position":[-480,-180],"parameters":{},"typeVersion":2.2},{"id":"908eee31-78eb-482c-b331-2d3467d56b0d","name":"Linedin-Post-Creator","type":"@n8n/n8n-nodes-langchain.agent","notes":"Uses GPT-4 to generate LinkedIn content - customize prompt for your brand voice","position":[180,-180],"parameters":{},"typeVersion":1.9},{"id":"882d6e5c-a7f0-425f-a501-1f7179f8857b","name":"Format-Content","type":"n8n-nodes-base.code","notes":"Formats content for Slack display - handles special characters and newlines","position":[556,-180],"parameters":{},"typeVersion":2},{"id":"31aea874-516c-47c7-9c5f-bde873faae4d","name":"Approval-on-Slack","type":"n8n-nodes-base.slack","notes":"Sends for human review - edit the Slack user to change approver","position":[780,-180],"webhookId":"YOUR_SLACK_WEBHOOK_ID","parameters":{},"notesInFlow":true,"typeVersion":2.3},{"id":"8592224a-0370-48c3-b803-fe3653284545","name":"Format-Response","type":"n8n-nodes-base.code","notes":"Extracts edited content from Slack response","position":[-260,-590],"parameters":{},"typeVersion":2},{"id":"2c503653-e3b6-4229-a733-25fa666ba85a","name":"Validate-Response","type":"n8n-nodes-base.if","notes":"Ensures response contains content before proceeding","position":[-40,-590],"parameters":{},"typeVersion":2.2},{"id":"be68592f-f6a8-4698-8343-58d439eed3ac","name":"Set-Final-Message","type":"n8n-nodes-base.set","notes":"Prepares approved content for publishing","position":[180,-590],"parameters":{},"typeVersion":3.4},{"id":"4ec34acf-1704-4fd7-b14d-680409acbeda","name":"Linkedin-User-Detail","type":"n8n-nodes-base.httpRequest","notes":"Fetches LinkedIn user ID for post attribution","position":[400,-580],"parameters":{},"typeVersion":4.2},{"id":"78293261-7fbd-4757-8353-c2275ba2089a","name":"Linkedin-post","type":"n8n-nodes-base.httpRequest","notes":"Publishes to your profile - update with your LinkedIn credentials","position":[1500,-590],"parameters":{},"typeVersion":4.2},{"id":"54ee84f1-42e2-4f25-96a4-958b27f798f4","name":"Get-Group-id","type":"n8n-nodes-base.googleSheets","notes":"Retrieves LinkedIn group IDs from Groups sheet","position":[1720,-590],"parameters":{},"typeVersion":4.5},{"id":"4e3e1fc5-a0ae-469f-8399-79b9bf98ff41","name":"Pick 1 by 1","type":"n8n-nodes-base.splitInBatches","notes":"Processes groups one at a time to avoid rate limits","position":[1940,-590],"parameters":{},"typeVersion":3},{"id":"7309d6c0-bfec-4d06-b3c3-5b05ccab6df3","name":"Post-Linkedin-Groups","type":"n8n-nodes-base.httpRequest","notes":"Posts to multiple groups - add group IDs in Groups sheet","onError":"continueRegularOutput","position":[2160,-540],"parameters":{},"typeVersion":4.2},{"id":"63b25ac7-e5dc-4836-96cf-5767b57c7784","name":"Update-Status","type":"n8n-nodes-base.googleSheets","notes":"Marks as 'Posted' to prevent reprocessing","position":[2160,-740],"parameters":{},"typeVersion":4.5},{"id":"348ca4b6-fbb0-4a07-9c3d-9a581b95c7fe","name":"Register Image","type":"n8n-nodes-base.httpRequest","notes":"Initiates LinkedIn media upload - requires valid image URL from sheet","position":[620,-580],"parameters":{},"typeVersion":4.2},{"id":"2dfdfc17-78f7-488b-82f2-cb229488062f","name":"Upload-Image-data","type":"n8n-nodes-base.set","notes":"Extracts upload URL and asset ID from LinkedIn response","position":[840,-580],"parameters":{},"typeVersion":3.4},{"id":"a68a5ba8-8913-455f-9893-12013322e9c0","name":"Get Image Binary","type":"n8n-nodes-base.httpRequest","notes":"Downloads image from URL specified in spreadsheet","position":[1060,-590],"parameters":{},"typeVersion":4.2},{"id":"37cfc754-d66f-43f8-b881-4b5f0e927fa2","name":"Upload Image","type":"n8n-nodes-base.httpRequest","notes":"Uploads image binary to LinkedIn servers","position":[1280,-590],"parameters":{},"typeVersion":4.2},{"id":"c67c5ae9-c0c0-4400-a5ed-c2f96842e24d","name":"Edit Fields","type":"n8n-nodes-base.set","notes":"Extracts post ID for tracking through workflow","position":[-40,-180],"parameters":{},"typeVersion":3.4},{"id":"8202c5f6-aa24-44d9-989e-b67d0c481e17","name":"Set Topics and Images for Processing","type":"n8n-nodes-base.code","notes":"Extracts post ID and image URL from Slack approval response","position":[-480,-600],"parameters":{},"typeVersion":2}],"active":false,"settings":{"executionOrder":"v1"},"versionId":"YOUR_VERSION_ID","connections":{"Limit":{"main":[[{"node":"Edit Fields","type":"main","index":0}]]},"Webhook":{"main":[[{"node":"Set Topics and Images for Processing","type":"main","index":0}]]},"Edit Fields":{"main":[[{"node":"Linedin-Post-Creator","type":"main","index":0}]]},"Pick 1 by 1":{"main":[[{"node":"Update-Status","type":"main","index":0}],[{"node":"Post-Linkedin-Groups","type":"main","index":0}]]},"Get-Group-id":{"main":[[{"node":"Pick 1 by 1","type":"main","index":0}]]},"Upload Image":{"main":[[{"node":"Linkedin-post","type":"main","index":0}]]},"Linkedin-post":{"main":[[{"node":"Get-Group-id","type":"main","index":0}]]},"Update-Status":{"main":[[]]},"Format-Content":{"main":[[{"node":"Approval-on-Slack","type":"main","index":0}]]},"Register Image":{"main":[[{"node":"Upload-Image-data","type":"main","index":0}]]},"Format-Response":{"main":[[{"node":"Validate-Response","type":"main","index":0}]]},"Validate-Status":{"main":[[{"node":"Limit","type":"main","index":0}]]},"Get Image Binary":{"main":[[{"node":"Upload Image","type":"main","index":0}]]},"Approval-on-Slack":{"main":[[]]},"OpenAI Chat Model":{"ai_languageModel":[[{"node":"Linedin-Post-Creator","type":"ai_languageModel","index":0}]]},"Set-Final-Message":{"main":[[{"node":"Linkedin-User-Detail","type":"main","index":0}]]},"Upload-Image-data":{"main":[[{"node":"Get Image Binary","type":"main","index":0}]]},"Validate-Response":{"main":[[{"node":"Set-Final-Message","type":"main","index":0}]]},"Linkedin-Post-Topic":{"main":[[{"node":"Validate-Status","type":"main","index":0}]]},"Linedin-Post-Creator":{"main":[[{"node":"Format-Content","type":"main","index":0}]]},"Linkedin-User-Detail":{"main":[[{"node":"Register Image","type":"main","index":0}]]},"Post-Linkedin-Groups":{"main":[[{"node":"Pick 1 by 1","type":"main","index":0}]]},"Structured Output Parser":{"ai_outputParser":[[{"node":"Linedin-Post-Creator","type":"ai_outputParser","index":0}]]},"Set Topics and Images for Processing":{"main":[[{"node":"Format-Response","type":"main","index":0}]]}}}


